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/* Use posix_fallocate() if it is available
26474*/
26475#if !defined(HAVE_POSIX_FALLOCATE) \
26476      && (_XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L)
26477# define HAVE_POSIX_FALLOCATE 1
26478#endif
26479
26480/*
26481** There are various methods for file locking used for concurrency
26482** control:
26483**
26484**   1. POSIX locking (the default),
26485**   2. No locking,
26486**   3. Dot-file locking,
26487**   4. flock() locking,
26488**   5. AFP locking (OSX only),
26489**   6. Named POSIX semaphores (VXWorks only),
26490**   7. proxy locking. (OSX only)
26491**
26492** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
26493** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
26494** selection of the appropriate locking style based on the filesystem
26495** where the database is located.
26496*/
26497#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
26498#  if defined(__APPLE__)
26499#    define SQLITE_ENABLE_LOCKING_STYLE 1
26500#  else
26501#    define SQLITE_ENABLE_LOCKING_STYLE 0
26502#  endif
26503#endif
26504
26505/*
26506** standard include files.
26507*/
26508#include <sys/types.h>
26509#include <sys/stat.h>
26510#include <fcntl.h>
26511#include <unistd.h>
26512/* #include <time.h> */
26513#include <sys/time.h>
26514#include <errno.h>
26515#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
26516# include <sys/mman.h>
26517#endif
26518
26519#if SQLITE_ENABLE_LOCKING_STYLE
26520# include <sys/ioctl.h>
26521# include <sys/file.h>
26522# include <sys/param.h>
26523#endif /* SQLITE_ENABLE_LOCKING_STYLE */
26524
26525#if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
26526                           (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
26527#  if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
26528       && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
26529#    define HAVE_GETHOSTUUID 1
26530#  else
26531#    warning "gethostuuid() is disabled."
26532#  endif
26533#endif
26534
26535
26536#if OS_VXWORKS
26537/* # include <sys/ioctl.h> */
26538# include <semaphore.h>
26539# include <limits.h>
26540#endif /* OS_VXWORKS */
26541
26542#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
26543# include <sys/mount.h>
26544#endif
26545
26546#ifdef HAVE_UTIME
26547# include <utime.h>
26548#endif
26549
26550/*
26551** Allowed values of unixFile.fsFlags
26552*/
26553#define SQLITE_FSFLAGS_IS_MSDOS     0x1
26554
26555/*
26556** If we are to be thread-safe, include the pthreads header and define
26557** the SQLITE_UNIX_THREADS macro.
26558*/
26559#if SQLITE_THREADSAFE
26560/* # include <pthread.h> */
26561# define SQLITE_UNIX_THREADS 1
26562#endif
26563
26564/*
26565** Default permissions when creating a new file
26566*/
26567#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
26568# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
26569#endif
26570
26571/*
26572** Default permissions when creating auto proxy dir
26573*/
26574#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
26575# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
26576#endif
26577
26578/*
26579** Maximum supported path-length.
26580*/
26581#define MAX_PATHNAME 512
26582
26583/* Always cast the getpid() return type for compatibility with
26584** kernel modules in VxWorks. */
26585#define osGetpid(X) (pid_t)getpid()
26586
26587/*
26588** Only set the lastErrno if the error code is a real error and not
26589** a normal expected return code of SQLITE_BUSY or SQLITE_OK
26590*/
26591#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
26592
26593/* Forward references */
26594typedef struct unixShm unixShm;               /* Connection shared memory */
26595typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
26596typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
26597typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
26598
26599/*
26600** Sometimes, after a file handle is closed by SQLite, the file descriptor
26601** cannot be closed immediately. In these cases, instances of the following
26602** structure are used to store the file descriptor while waiting for an
26603** opportunity to either close or reuse it.
26604*/
26605struct UnixUnusedFd {
26606  int fd;                   /* File descriptor to close */
26607  int flags;                /* Flags this file descriptor was opened with */
26608  UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
26609};
26610
26611/*
26612** The unixFile structure is subclass of sqlite3_file specific to the unix
26613** VFS implementations.
26614*/
26615typedef struct unixFile unixFile;
26616struct unixFile {
26617  sqlite3_io_methods const *pMethod;  /* Always the first entry */
26618  sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
26619  unixInodeInfo *pInode;              /* Info about locks on this inode */
26620  int h;                              /* The file descriptor */
26621  unsigned char eFileLock;            /* The type of lock held on this fd */
26622  unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
26623  int lastErrno;                      /* The unix errno from last I/O error */
26624  void *lockingContext;               /* Locking style specific state */
26625  UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
26626  const char *zPath;                  /* Name of the file */
26627  unixShm *pShm;                      /* Shared memory segment information */
26628  int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
26629#if SQLITE_MAX_MMAP_SIZE>0
26630  int nFetchOut;                      /* Number of outstanding xFetch refs */
26631  sqlite3_int64 mmapSize;             /* Usable size of mapping at pMapRegion */
26632  sqlite3_int64 mmapSizeActual;       /* Actual size of mapping at pMapRegion */
26633  sqlite3_int64 mmapSizeMax;          /* Configured FCNTL_MMAP_SIZE value */
26634  void *pMapRegion;                   /* Memory mapped region */
26635#endif
26636#ifdef __QNXNTO__
26637  int sectorSize;                     /* Device sector size */
26638  int deviceCharacteristics;          /* Precomputed device characteristics */
26639#endif
26640#if SQLITE_ENABLE_LOCKING_STYLE
26641  int openFlags;                      /* The flags specified at open() */
26642#endif
26643#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
26644  unsigned fsFlags;                   /* cached details from statfs() */
26645#endif
26646#if OS_VXWORKS
26647  struct vxworksFileId *pId;          /* Unique file ID */
26648#endif
26649#ifdef SQLITE_DEBUG
26650  /* The next group of variables are used to track whether or not the
26651  ** transaction counter in bytes 24-27 of database files are updated
26652  ** whenever any part of the database changes.  An assertion fault will
26653  ** occur if a file is updated without also updating the transaction
26654  ** counter.  This test is made to avoid new problems similar to the
26655  ** one described by ticket #3584.
26656  */
26657  unsigned char transCntrChng;   /* True if the transaction counter changed */
26658  unsigned char dbUpdate;        /* True if any part of database file changed */
26659  unsigned char inNormalWrite;   /* True if in a normal write operation */
26660
26661#endif
26662
26663#ifdef SQLITE_TEST
26664  /* In test mode, increase the size of this structure a bit so that
26665  ** it is larger than the struct CrashFile defined in test6.c.
26666  */
26667  char aPadding[32];
26668#endif
26669};
26670
26671/* This variable holds the process id (pid) from when the xRandomness()
26672** method was called.  If xOpen() is called from a different process id,
26673** indicating that a fork() has occurred, the PRNG will be reset.
26674*/
26675static pid_t randomnessPid = 0;
26676
26677/*
26678** Allowed values for the unixFile.ctrlFlags bitmask:
26679*/
26680#define UNIXFILE_EXCL        0x01     /* Connections from one process only */
26681#define UNIXFILE_RDONLY      0x02     /* Connection is read only */
26682#define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
26683#ifndef SQLITE_DISABLE_DIRSYNC
26684# define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
26685#else
26686# define UNIXFILE_DIRSYNC    0x00
26687#endif
26688#define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
26689#define UNIXFILE_DELETE      0x20     /* Delete on close */
26690#define UNIXFILE_URI         0x40     /* Filename might have query parameters */
26691#define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
26692#define UNIXFILE_WARNED    0x0100     /* verifyDbFile() warnings issued */
26693#define UNIXFILE_BLOCK     0x0200     /* Next SHM lock might block */
26694
26695/*
26696** Include code that is common to all os_*.c files
26697*/
26698/************** Include os_common.h in the middle of os_unix.c ***************/
26699/************** Begin file os_common.h ***************************************/
26700/*
26701** 2004 May 22
26702**
26703** The author disclaims copyright to this source code.  In place of
26704** a legal notice, here is a blessing:
26705**
26706**    May you do good and not evil.
26707**    May you find forgiveness for yourself and forgive others.
26708**    May you share freely, never taking more than you give.
26709**
26710******************************************************************************
26711**
26712** This file contains macros and a little bit of code that is common to
26713** all of the platform-specific files (os_*.c) and is #included into those
26714** files.
26715**
26716** This file should be #included by the os_*.c files only.  It is not a
26717** general purpose header file.
26718*/
26719#ifndef _OS_COMMON_H_
26720#define _OS_COMMON_H_
26721
26722/*
26723** At least two bugs have slipped in because we changed the MEMORY_DEBUG
26724** macro to SQLITE_DEBUG and some older makefiles have not yet made the
26725** switch.  The following code should catch this problem at compile-time.
26726*/
26727#ifdef MEMORY_DEBUG
26728# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
26729#endif
26730
26731/*
26732** Macros for performance tracing.  Normally turned off.  Only works
26733** on i486 hardware.
26734*/
26735#ifdef SQLITE_PERFORMANCE_TRACE
26736
26737/*
26738** hwtime.h contains inline assembler code for implementing
26739** high-performance timing routines.
26740*/
26741/************** Include hwtime.h in the middle of os_common.h ****************/
26742/************** Begin file hwtime.h ******************************************/
26743/*
26744** 2008 May 27
26745**
26746** The author disclaims copyright to this source code.  In place of
26747** a legal notice, here is a blessing:
26748**
26749**    May you do good and not evil.
26750**    May you find forgiveness for yourself and forgive others.
26751**    May you share freely, never taking more than you give.
26752**
26753******************************************************************************
26754**
26755** This file contains inline asm code for retrieving "high-performance"
26756** counters for x86 class CPUs.
26757*/
26758#ifndef _HWTIME_H_
26759#define _HWTIME_H_
26760
26761/*
26762** The following routine only works on pentium-class (or newer) processors.
26763** It uses the RDTSC opcode to read the cycle count value out of the
26764** processor and returns that value.  This can be used for high-res
26765** profiling.
26766*/
26767#if (defined(__GNUC__) || defined(_MSC_VER)) && \
26768      (defined(i386) || defined(__i386__) || defined(_M_IX86))
26769
26770  #if defined(__GNUC__)
26771
26772  __inline__ sqlite_uint64 sqlite3Hwtime(void){
26773     unsigned int lo, hi;
26774     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
26775     return (sqlite_uint64)hi << 32 | lo;
26776  }
26777
26778  #elif defined(_MSC_VER)
26779
26780  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
26781     __asm {
26782        rdtsc
26783        ret       ; return value at EDX:EAX
26784     }
26785  }
26786
26787  #endif
26788
26789#elif (defined(__GNUC__) && defined(__x86_64__))
26790
26791  __inline__ sqlite_uint64 sqlite3Hwtime(void){
26792      unsigned long val;
26793      __asm__ __volatile__ ("rdtsc" : "=A" (val));
26794      return val;
26795  }
26796
26797#elif (defined(__GNUC__) && defined(__ppc__))
26798
26799  __inline__ sqlite_uint64 sqlite3Hwtime(void){
26800      unsigned long long retval;
26801      unsigned long junk;
26802      __asm__ __volatile__ ("\n\
26803          1:      mftbu   %1\n\
26804                  mftb    %L0\n\
26805                  mftbu   %0\n\
26806                  cmpw    %0,%1\n\
26807                  bne     1b"
26808                  : "=r" (retval), "=r" (junk));
26809      return retval;
26810  }
26811
26812#else
26813
26814  #error Need implementation of sqlite3Hwtime() for your platform.
26815
26816  /*
26817  ** To compile without implementing sqlite3Hwtime() for your platform,
26818  ** you can remove the above #error and use the following
26819  ** stub function.  You will lose timing support for many
26820  ** of the debugging and testing utilities, but it should at
26821  ** least compile and run.
26822  */
26823SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
26824
26825#endif
26826
26827#endif /* !defined(_HWTIME_H_) */
26828
26829/************** End of hwtime.h **********************************************/
26830/************** Continuing where we left off in os_common.h ******************/
26831
26832static sqlite_uint64 g_start;
26833static sqlite_uint64 g_elapsed;
26834#define TIMER_START       g_start=sqlite3Hwtime()
26835#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
26836#define TIMER_ELAPSED     g_elapsed
26837#else
26838#define TIMER_START
26839#define TIMER_END
26840#define TIMER_ELAPSED     ((sqlite_uint64)0)
26841#endif
26842
26843/*
26844** If we compile with the SQLITE_TEST macro set, then the following block
26845** of code will give us the ability to simulate a disk I/O error.  This
26846** is used for testing the I/O recovery logic.
26847*/
26848#ifdef SQLITE_TEST
26849SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
26850SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
26851SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
26852SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
26853SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
26854SQLITE_API int sqlite3_diskfull_pending = 0;
26855SQLITE_API int sqlite3_diskfull = 0;
26856#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
26857#define SimulateIOError(CODE)  \
26858  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
26859       || sqlite3_io_error_pending-- == 1 )  \
26860              { local_ioerr(); CODE; }
26861static void local_ioerr(){
26862  IOTRACE(("IOERR\n"));
26863  sqlite3_io_error_hit++;
26864  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
26865}
26866#define SimulateDiskfullError(CODE) \
26867   if( sqlite3_diskfull_pending ){ \
26868     if( sqlite3_diskfull_pending == 1 ){ \
26869       local_ioerr(); \
26870       sqlite3_diskfull = 1; \
26871       sqlite3_io_error_hit = 1; \
26872       CODE; \
26873     }else{ \
26874       sqlite3_diskfull_pending--; \
26875     } \
26876   }
26877#else
26878#define SimulateIOErrorBenign(X)
26879#define SimulateIOError(A)
26880#define SimulateDiskfullError(A)
26881#endif
26882
26883/*
26884** When testing, keep a count of the number of open files.
26885*/
26886#ifdef SQLITE_TEST
26887SQLITE_API int sqlite3_open_file_count = 0;
26888#define OpenCounter(X)  sqlite3_open_file_count+=(X)
26889#else
26890#define OpenCounter(X)
26891#endif
26892
26893#endif /* !defined(_OS_COMMON_H_) */
26894
26895/************** End of os_common.h *******************************************/
26896/************** Continuing where we left off in os_unix.c ********************/
26897
26898/*
26899** Define various macros that are missing from some systems.
26900*/
26901#ifndef O_LARGEFILE
26902# define O_LARGEFILE 0
26903#endif
26904#ifdef SQLITE_DISABLE_LFS
26905# undef O_LARGEFILE
26906# define O_LARGEFILE 0
26907#endif
26908#ifndef O_NOFOLLOW
26909# define O_NOFOLLOW 0
26910#endif
26911#ifndef O_BINARY
26912# define O_BINARY 0
26913#endif
26914
26915/*
26916** The threadid macro resolves to the thread-id or to 0.  Used for
26917** testing and debugging only.
26918*/
26919#if SQLITE_THREADSAFE
26920#define threadid pthread_self()
26921#else
26922#define threadid 0
26923#endif
26924
26925/*
26926** HAVE_MREMAP defaults to true on Linux and false everywhere else.
26927*/
26928#if !defined(HAVE_MREMAP)
26929# if defined(__linux__) && defined(_GNU_SOURCE)
26930#  define HAVE_MREMAP 1
26931# else
26932#  define HAVE_MREMAP 0
26933# endif
26934#endif
26935
26936/*
26937** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
26938** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
26939*/
26940#ifdef __ANDROID__
26941# define lseek lseek64
26942#endif
26943
26944/*
26945** Different Unix systems declare open() in different ways.  Same use
26946** open(const char*,int,mode_t).  Others use open(const char*,int,...).
26947** The difference is important when using a pointer to the function.
26948**
26949** The safest way to deal with the problem is to always use this wrapper
26950** which always has the same well-defined interface.
26951*/
26952static int posixOpen(const char *zFile, int flags, int mode){
26953  return open(zFile, flags, mode);
26954}
26955
26956/*
26957** On some systems, calls to fchown() will trigger a message in a security
26958** log if they come from non-root processes.  So avoid calling fchown() if
26959** we are not running as root.
26960*/
26961static int posixFchown(int fd, uid_t uid, gid_t gid){
26962#if OS_VXWORKS
26963  return 0;
26964#else
26965  return geteuid() ? 0 : fchown(fd,uid,gid);
26966#endif
26967}
26968
26969/* Forward reference */
26970static int openDirectory(const char*, int*);
26971static int unixGetpagesize(void);
26972
26973/*
26974** Many system calls are accessed through pointer-to-functions so that
26975** they may be overridden at runtime to facilitate fault injection during
26976** testing and sandboxing.  The following array holds the names and pointers
26977** to all overrideable system calls.
26978*/
26979static struct unix_syscall {
26980  const char *zName;            /* Name of the system call */
26981  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
26982  sqlite3_syscall_ptr pDefault; /* Default value */
26983} aSyscall[] = {
26984  { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
26985#define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
26986
26987  { "close",        (sqlite3_syscall_ptr)close,      0  },
26988#define osClose     ((int(*)(int))aSyscall[1].pCurrent)
26989
26990  { "access",       (sqlite3_syscall_ptr)access,     0  },
26991#define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
26992
26993  { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
26994#define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
26995
26996  { "stat",         (sqlite3_syscall_ptr)stat,       0  },
26997#define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
26998
26999/*
27000** The DJGPP compiler environment looks mostly like Unix, but it
27001** lacks the fcntl() system call.  So redefine fcntl() to be something
27002** that always succeeds.  This means that locking does not occur under
27003** DJGPP.  But it is DOS - what did you expect?
27004*/
27005#ifdef __DJGPP__
27006  { "fstat",        0,                 0  },
27007#define osFstat(a,b,c)    0
27008#else
27009  { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
27010#define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
27011#endif
27012
27013  { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
27014#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
27015
27016  { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
27017#define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
27018
27019  { "read",         (sqlite3_syscall_ptr)read,       0  },
27020#define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
27021
27022#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
27023  { "pread",        (sqlite3_syscall_ptr)pread,      0  },
27024#else
27025  { "pread",        (sqlite3_syscall_ptr)0,          0  },
27026#endif
27027#define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
27028
27029#if defined(USE_PREAD64)
27030  { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
27031#else
27032  { "pread64",      (sqlite3_syscall_ptr)0,          0  },
27033#endif
27034#ifdef ANDROID
27035// Bionic defines pread64 using off64_t rather than off_t.
27036#define osPread64   ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
27037#else
27038#define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
27039#endif
27040
27041  { "write",        (sqlite3_syscall_ptr)write,      0  },
27042#define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
27043
27044#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
27045  { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
27046#else
27047  { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
27048#endif
27049#define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
27050                    aSyscall[12].pCurrent)
27051
27052#if defined(USE_PREAD64)
27053  { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
27054#else
27055  { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
27056#endif
27057#ifdef ANDROID
27058// Bionic defines pwrite64 using off64_t rather than off_t.
27059#define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off64_t))\
27060                    aSyscall[13].pCurrent)
27061#else
27062#define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
27063                    aSyscall[13].pCurrent)
27064#endif
27065
27066  { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
27067#define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
27068
27069#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
27070  { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
27071#else
27072  { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
27073#endif
27074#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
27075
27076  { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
27077#define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
27078
27079  { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
27080#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
27081
27082  { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
27083#define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
27084
27085  { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
27086#define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
27087
27088  { "fchown",       (sqlite3_syscall_ptr)posixFchown,     0 },
27089#define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
27090
27091#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
27092  { "mmap",       (sqlite3_syscall_ptr)mmap,     0 },
27093#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
27094
27095  { "munmap",       (sqlite3_syscall_ptr)munmap,          0 },
27096#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
27097
27098#if HAVE_MREMAP
27099  { "mremap",       (sqlite3_syscall_ptr)mremap,          0 },
27100#else
27101  { "mremap",       (sqlite3_syscall_ptr)0,               0 },
27102#endif
27103#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
27104  { "getpagesize",  (sqlite3_syscall_ptr)unixGetpagesize, 0 },
27105#define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
27106
27107#endif
27108
27109}; /* End of the overrideable system calls */
27110
27111/*
27112** This is the xSetSystemCall() method of sqlite3_vfs for all of the
27113** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
27114** system call pointer, or SQLITE_NOTFOUND if there is no configurable
27115** system call named zName.
27116*/
27117static int unixSetSystemCall(
27118  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
27119  const char *zName,            /* Name of system call to override */
27120  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
27121){
27122  unsigned int i;
27123  int rc = SQLITE_NOTFOUND;
27124
27125  UNUSED_PARAMETER(pNotUsed);
27126  if( zName==0 ){
27127    /* If no zName is given, restore all system calls to their default
27128    ** settings and return NULL
27129    */
27130    rc = SQLITE_OK;
27131    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
27132      if( aSyscall[i].pDefault ){
27133        aSyscall[i].pCurrent = aSyscall[i].pDefault;
27134      }
27135    }
27136  }else{
27137    /* If zName is specified, operate on only the one system call
27138    ** specified.
27139    */
27140    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
27141      if( strcmp(zName, aSyscall[i].zName)==0 ){
27142        if( aSyscall[i].pDefault==0 ){
27143          aSyscall[i].pDefault = aSyscall[i].pCurrent;
27144        }
27145        rc = SQLITE_OK;
27146        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
27147        aSyscall[i].pCurrent = pNewFunc;
27148        break;
27149      }
27150    }
27151  }
27152  return rc;
27153}
27154
27155/*
27156** Return the value of a system call.  Return NULL if zName is not a
27157** recognized system call name.  NULL is also returned if the system call
27158** is currently undefined.
27159*/
27160static sqlite3_syscall_ptr unixGetSystemCall(
27161  sqlite3_vfs *pNotUsed,
27162  const char *zName
27163){
27164  unsigned int i;
27165
27166  UNUSED_PARAMETER(pNotUsed);
27167  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
27168    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
27169  }
27170  return 0;
27171}
27172
27173/*
27174** Return the name of the first system call after zName.  If zName==NULL
27175** then return the name of the first system call.  Return NULL if zName
27176** is the last system call or if zName is not the name of a valid
27177** system call.
27178*/
27179static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
27180  int i = -1;
27181
27182  UNUSED_PARAMETER(p);
27183  if( zName ){
27184    for(i=0; i<ArraySize(aSyscall)-1; i++){
27185      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
27186    }
27187  }
27188  for(i++; i<ArraySize(aSyscall); i++){
27189    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
27190  }
27191  return 0;
27192}
27193
27194/*
27195** Do not accept any file descriptor less than this value, in order to avoid
27196** opening database file using file descriptors that are commonly used for
27197** standard input, output, and error.
27198*/
27199#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
27200# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
27201#endif
27202
27203/*
27204** Invoke open().  Do so multiple times, until it either succeeds or
27205** fails for some reason other than EINTR.
27206**
27207** If the file creation mode "m" is 0 then set it to the default for
27208** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
27209** 0644) as modified by the system umask.  If m is not 0, then
27210** make the file creation mode be exactly m ignoring the umask.
27211**
27212** The m parameter will be non-zero only when creating -wal, -journal,
27213** and -shm files.  We want those files to have *exactly* the same
27214** permissions as their original database, unadulterated by the umask.
27215** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
27216** transaction crashes and leaves behind hot journals, then any
27217** process that is able to write to the database will also be able to
27218** recover the hot journals.
27219*/
27220static int robust_open(const char *z, int f, mode_t m){
27221  int fd;
27222  mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
27223  while(1){
27224#if defined(O_CLOEXEC)
27225    fd = osOpen(z,f|O_CLOEXEC,m2);
27226#else
27227    fd = osOpen(z,f,m2);
27228#endif
27229    if( fd<0 ){
27230      if( errno==EINTR ) continue;
27231      break;
27232    }
27233    if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
27234    osClose(fd);
27235    sqlite3_log(SQLITE_WARNING,
27236                "attempt to open \"%s\" as file descriptor %d", z, fd);
27237    fd = -1;
27238    if( osOpen("/dev/null", f, m)<0 ) break;
27239  }
27240  if( fd>=0 ){
27241    if( m!=0 ){
27242      struct stat statbuf;
27243      if( osFstat(fd, &statbuf)==0
27244       && statbuf.st_size==0
27245       && (statbuf.st_mode&0777)!=m
27246      ){
27247        osFchmod(fd, m);
27248      }
27249    }
27250#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
27251    osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
27252#endif
27253  }
27254  return fd;
27255}
27256
27257/*
27258** Helper functions to obtain and relinquish the global mutex. The
27259** global mutex is used to protect the unixInodeInfo and
27260** vxworksFileId objects used by this file, all of which may be
27261** shared by multiple threads.
27262**
27263** Function unixMutexHeld() is used to assert() that the global mutex
27264** is held when required. This function is only used as part of assert()
27265** statements. e.g.
27266**
27267**   unixEnterMutex()
27268**     assert( unixMutexHeld() );
27269**   unixEnterLeave()
27270*/
27271static void unixEnterMutex(void){
27272  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
27273}
27274static void unixLeaveMutex(void){
27275  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
27276}
27277#ifdef SQLITE_DEBUG
27278static int unixMutexHeld(void) {
27279  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
27280}
27281#endif
27282
27283
27284#ifdef SQLITE_HAVE_OS_TRACE
27285/*
27286** Helper function for printing out trace information from debugging
27287** binaries. This returns the string representation of the supplied
27288** integer lock-type.
27289*/
27290static const char *azFileLock(int eFileLock){
27291  switch( eFileLock ){
27292    case NO_LOCK: return "NONE";
27293    case SHARED_LOCK: return "SHARED";
27294    case RESERVED_LOCK: return "RESERVED";
27295    case PENDING_LOCK: return "PENDING";
27296    case EXCLUSIVE_LOCK: return "EXCLUSIVE";
27297  }
27298  return "ERROR";
27299}
27300#endif
27301
27302#ifdef SQLITE_LOCK_TRACE
27303/*
27304** Print out information about all locking operations.
27305**
27306** This routine is used for troubleshooting locks on multithreaded
27307** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
27308** command-line option on the compiler.  This code is normally
27309** turned off.
27310*/
27311static int lockTrace(int fd, int op, struct flock *p){
27312  char *zOpName, *zType;
27313  int s;
27314  int savedErrno;
27315  if( op==F_GETLK ){
27316    zOpName = "GETLK";
27317  }else if( op==F_SETLK ){
27318    zOpName = "SETLK";
27319  }else{
27320    s = osFcntl(fd, op, p);
27321    sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
27322    return s;
27323  }
27324  if( p->l_type==F_RDLCK ){
27325    zType = "RDLCK";
27326  }else if( p->l_type==F_WRLCK ){
27327    zType = "WRLCK";
27328  }else if( p->l_type==F_UNLCK ){
27329    zType = "UNLCK";
27330  }else{
27331    assert( 0 );
27332  }
27333  assert( p->l_whence==SEEK_SET );
27334  s = osFcntl(fd, op, p);
27335  savedErrno = errno;
27336  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
27337     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
27338     (int)p->l_pid, s);
27339  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
27340    struct flock l2;
27341    l2 = *p;
27342    osFcntl(fd, F_GETLK, &l2);
27343    if( l2.l_type==F_RDLCK ){
27344      zType = "RDLCK";
27345    }else if( l2.l_type==F_WRLCK ){
27346      zType = "WRLCK";
27347    }else if( l2.l_type==F_UNLCK ){
27348      zType = "UNLCK";
27349    }else{
27350      assert( 0 );
27351    }
27352    sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
27353       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
27354  }
27355  errno = savedErrno;
27356  return s;
27357}
27358#undef osFcntl
27359#define osFcntl lockTrace
27360#endif /* SQLITE_LOCK_TRACE */
27361
27362/*
27363** Retry ftruncate() calls that fail due to EINTR
27364**
27365** All calls to ftruncate() within this file should be made through
27366** this wrapper.  On the Android platform, bypassing the logic below
27367** could lead to a corrupt database.
27368*/
27369static int robust_ftruncate(int h, sqlite3_int64 sz){
27370  int rc;
27371#ifdef __ANDROID__
27372  /* On Android, ftruncate() always uses 32-bit offsets, even if
27373  ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
27374  ** truncate a file to any size larger than 2GiB. Silently ignore any
27375  ** such attempts.  */
27376  if( sz>(sqlite3_int64)0x7FFFFFFF ){
27377    rc = SQLITE_OK;
27378  }else
27379#endif
27380  do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
27381  return rc;
27382}
27383
27384/*
27385** This routine translates a standard POSIX errno code into something
27386** useful to the clients of the sqlite3 functions.  Specifically, it is
27387** intended to translate a variety of "try again" errors into SQLITE_BUSY
27388** and a variety of "please close the file descriptor NOW" errors into
27389** SQLITE_IOERR
27390**
27391** Errors during initialization of locks, or file system support for locks,
27392** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
27393*/
27394static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
27395  switch (posixError) {
27396#if 0
27397  /* At one point this code was not commented out. In theory, this branch
27398  ** should never be hit, as this function should only be called after
27399  ** a locking-related function (i.e. fcntl()) has returned non-zero with
27400  ** the value of errno as the first argument. Since a system call has failed,
27401  ** errno should be non-zero.
27402  **
27403  ** Despite this, if errno really is zero, we still don't want to return
27404  ** SQLITE_OK. The system call failed, and *some* SQLite error should be
27405  ** propagated back to the caller. Commenting this branch out means errno==0
27406  ** will be handled by the "default:" case below.
27407  */
27408  case 0:
27409    return SQLITE_OK;
27410#endif
27411
27412  case EAGAIN:
27413  case ETIMEDOUT:
27414  case EBUSY:
27415  case EINTR:
27416  case ENOLCK:
27417    /* random NFS retry error, unless during file system support
27418     * introspection, in which it actually means what it says */
27419    return SQLITE_BUSY;
27420
27421  case EACCES:
27422    /* EACCES is like EAGAIN during locking operations, but not any other time*/
27423    if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
27424        (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
27425        (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
27426        (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
27427      return SQLITE_BUSY;
27428    }
27429    /* else fall through */
27430  case EPERM:
27431    return SQLITE_PERM;
27432
27433#if EOPNOTSUPP!=ENOTSUP
27434  case EOPNOTSUPP:
27435    /* something went terribly awry, unless during file system support
27436     * introspection, in which it actually means what it says */
27437#endif
27438#ifdef ENOTSUP
27439  case ENOTSUP:
27440    /* invalid fd, unless during file system support introspection, in which
27441     * it actually means what it says */
27442#endif
27443  case EIO:
27444  case EBADF:
27445  case EINVAL:
27446  case ENOTCONN:
27447  case ENODEV:
27448  case ENXIO:
27449  case ENOENT:
27450#ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
27451  case ESTALE:
27452#endif
27453  case ENOSYS:
27454    /* these should force the client to close the file and reconnect */
27455
27456  default:
27457    return sqliteIOErr;
27458  }
27459}
27460
27461
27462/******************************************************************************
27463****************** Begin Unique File ID Utility Used By VxWorks ***************
27464**
27465** On most versions of unix, we can get a unique ID for a file by concatenating
27466** the device number and the inode number.  But this does not work on VxWorks.
27467** On VxWorks, a unique file id must be based on the canonical filename.
27468**
27469** A pointer to an instance of the following structure can be used as a
27470** unique file ID in VxWorks.  Each instance of this structure contains
27471** a copy of the canonical filename.  There is also a reference count.
27472** The structure is reclaimed when the number of pointers to it drops to
27473** zero.
27474**
27475** There are never very many files open at one time and lookups are not
27476** a performance-critical path, so it is sufficient to put these
27477** structures on a linked list.
27478*/
27479struct vxworksFileId {
27480  struct vxworksFileId *pNext;  /* Next in a list of them all */
27481  int nRef;                     /* Number of references to this one */
27482  int nName;                    /* Length of the zCanonicalName[] string */
27483  char *zCanonicalName;         /* Canonical filename */
27484};
27485
27486#if OS_VXWORKS
27487/*
27488** All unique filenames are held on a linked list headed by this
27489** variable:
27490*/
27491static struct vxworksFileId *vxworksFileList = 0;
27492
27493/*
27494** Simplify a filename into its canonical form
27495** by making the following changes:
27496**
27497**  * removing any trailing and duplicate /
27498**  * convert /./ into just /
27499**  * convert /A/../ where A is any simple name into just /
27500**
27501** Changes are made in-place.  Return the new name length.
27502**
27503** The original filename is in z[0..n-1].  Return the number of
27504** characters in the simplified name.
27505*/
27506static int vxworksSimplifyName(char *z, int n){
27507  int i, j;
27508  while( n>1 && z[n-1]=='/' ){ n--; }
27509  for(i=j=0; i<n; i++){
27510    if( z[i]=='/' ){
27511      if( z[i+1]=='/' ) continue;
27512      if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
27513        i += 1;
27514        continue;
27515      }
27516      if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
27517        while( j>0 && z[j-1]!='/' ){ j--; }
27518        if( j>0 ){ j--; }
27519        i += 2;
27520        continue;
27521      }
27522    }
27523    z[j++] = z[i];
27524  }
27525  z[j] = 0;
27526  return j;
27527}
27528
27529/*
27530** Find a unique file ID for the given absolute pathname.  Return
27531** a pointer to the vxworksFileId object.  This pointer is the unique
27532** file ID.
27533**
27534** The nRef field of the vxworksFileId object is incremented before
27535** the object is returned.  A new vxworksFileId object is created
27536** and added to the global list if necessary.
27537**
27538** If a memory allocation error occurs, return NULL.
27539*/
27540static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
27541  struct vxworksFileId *pNew;         /* search key and new file ID */
27542  struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
27543  int n;                              /* Length of zAbsoluteName string */
27544
27545  assert( zAbsoluteName[0]=='/' );
27546  n = (int)strlen(zAbsoluteName);
27547  pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
27548  if( pNew==0 ) return 0;
27549  pNew->zCanonicalName = (char*)&pNew[1];
27550  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
27551  n = vxworksSimplifyName(pNew->zCanonicalName, n);
27552
27553  /* Search for an existing entry that matching the canonical name.
27554  ** If found, increment the reference count and return a pointer to
27555  ** the existing file ID.
27556  */
27557  unixEnterMutex();
27558  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
27559    if( pCandidate->nName==n
27560     && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
27561    ){
27562       sqlite3_free(pNew);
27563       pCandidate->nRef++;
27564       unixLeaveMutex();
27565       return pCandidate;
27566    }
27567  }
27568
27569  /* No match was found.  We will make a new file ID */
27570  pNew->nRef = 1;
27571  pNew->nName = n;
27572  pNew->pNext = vxworksFileList;
27573  vxworksFileList = pNew;
27574  unixLeaveMutex();
27575  return pNew;
27576}
27577
27578/*
27579** Decrement the reference count on a vxworksFileId object.  Free
27580** the object when the reference count reaches zero.
27581*/
27582static void vxworksReleaseFileId(struct vxworksFileId *pId){
27583  unixEnterMutex();
27584  assert( pId->nRef>0 );
27585  pId->nRef--;
27586  if( pId->nRef==0 ){
27587    struct vxworksFileId **pp;
27588    for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
27589    assert( *pp==pId );
27590    *pp = pId->pNext;
27591    sqlite3_free(pId);
27592  }
27593  unixLeaveMutex();
27594}
27595#endif /* OS_VXWORKS */
27596/*************** End of Unique File ID Utility Used By VxWorks ****************
27597******************************************************************************/
27598
27599
27600/******************************************************************************
27601*************************** Posix Advisory Locking ****************************
27602**
27603** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
27604** section 6.5.2.2 lines 483 through 490 specify that when a process
27605** sets or clears a lock, that operation overrides any prior locks set
27606** by the same process.  It does not explicitly say so, but this implies
27607** that it overrides locks set by the same process using a different
27608** file descriptor.  Consider this test case:
27609**
27610**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
27611**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
27612**
27613** Suppose ./file1 and ./file2 are really the same file (because
27614** one is a hard or symbolic link to the other) then if you set
27615** an exclusive lock on fd1, then try to get an exclusive lock
27616** on fd2, it works.  I would have expected the second lock to
27617** fail since there was already a lock on the file due to fd1.
27618** But not so.  Since both locks came from the same process, the
27619** second overrides the first, even though they were on different
27620** file descriptors opened on different file names.
27621**
27622** This means that we cannot use POSIX locks to synchronize file access
27623** among competing threads of the same process.  POSIX locks will work fine
27624** to synchronize access for threads in separate processes, but not
27625** threads within the same process.
27626**
27627** To work around the problem, SQLite has to manage file locks internally
27628** on its own.  Whenever a new database is opened, we have to find the
27629** specific inode of the database file (the inode is determined by the
27630** st_dev and st_ino fields of the stat structure that fstat() fills in)
27631** and check for locks already existing on that inode.  When locks are
27632** created or removed, we have to look at our own internal record of the
27633** locks to see if another thread has previously set a lock on that same
27634** inode.
27635**
27636** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
27637** For VxWorks, we have to use the alternative unique ID system based on
27638** canonical filename and implemented in the previous division.)
27639**
27640** The sqlite3_file structure for POSIX is no longer just an integer file
27641** descriptor.  It is now a structure that holds the integer file
27642** descriptor and a pointer to a structure that describes the internal
27643** locks on the corresponding inode.  There is one locking structure
27644** per inode, so if the same inode is opened twice, both unixFile structures
27645** point to the same locking structure.  The locking structure keeps
27646** a reference count (so we will know when to delete it) and a "cnt"
27647** field that tells us its internal lock status.  cnt==0 means the
27648** file is unlocked.  cnt==-1 means the file has an exclusive lock.
27649** cnt>0 means there are cnt shared locks on the file.
27650**
27651** Any attempt to lock or unlock a file first checks the locking
27652** structure.  The fcntl() system call is only invoked to set a
27653** POSIX lock if the internal lock structure transitions between
27654** a locked and an unlocked state.
27655**
27656** But wait:  there are yet more problems with POSIX advisory locks.
27657**
27658** If you close a file descriptor that points to a file that has locks,
27659** all locks on that file that are owned by the current process are
27660** released.  To work around this problem, each unixInodeInfo object
27661** maintains a count of the number of pending locks on tha inode.
27662** When an attempt is made to close an unixFile, if there are
27663** other unixFile open on the same inode that are holding locks, the call
27664** to close() the file descriptor is deferred until all of the locks clear.
27665** The unixInodeInfo structure keeps a list of file descriptors that need to
27666** be closed and that list is walked (and cleared) when the last lock
27667** clears.
27668**
27669** Yet another problem:  LinuxThreads do not play well with posix locks.
27670**
27671** Many older versions of linux use the LinuxThreads library which is
27672** not posix compliant.  Under LinuxThreads, a lock created by thread
27673** A cannot be modified or overridden by a different thread B.
27674** Only thread A can modify the lock.  Locking behavior is correct
27675** if the appliation uses the newer Native Posix Thread Library (NPTL)
27676** on linux - with NPTL a lock created by thread A can override locks
27677** in thread B.  But there is no way to know at compile-time which
27678** threading library is being used.  So there is no way to know at
27679** compile-time whether or not thread A can override locks on thread B.
27680** One has to do a run-time check to discover the behavior of the
27681** current process.
27682**
27683** SQLite used to support LinuxThreads.  But support for LinuxThreads
27684** was dropped beginning with version 3.7.0.  SQLite will still work with
27685** LinuxThreads provided that (1) there is no more than one connection
27686** per database file in the same process and (2) database connections
27687** do not move across threads.
27688*/
27689
27690/*
27691** An instance of the following structure serves as the key used
27692** to locate a particular unixInodeInfo object.
27693*/
27694struct unixFileId {
27695  dev_t dev;                  /* Device number */
27696#if OS_VXWORKS
27697  struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
27698#else
27699  ino_t ino;                  /* Inode number */
27700#endif
27701};
27702
27703/*
27704** An instance of the following structure is allocated for each open
27705** inode.  Or, on LinuxThreads, there is one of these structures for
27706** each inode opened by each thread.
27707**
27708** A single inode can have multiple file descriptors, so each unixFile
27709** structure contains a pointer to an instance of this object and this
27710** object keeps a count of the number of unixFile pointing to it.
27711*/
27712struct unixInodeInfo {
27713  struct unixFileId fileId;       /* The lookup key */
27714  int nShared;                    /* Number of SHARED locks held */
27715  unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
27716  unsigned char bProcessLock;     /* An exclusive process lock is held */
27717  int nRef;                       /* Number of pointers to this structure */
27718  unixShmNode *pShmNode;          /* Shared memory associated with this inode */
27719  int nLock;                      /* Number of outstanding file locks */
27720  UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
27721  unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
27722  unixInodeInfo *pPrev;           /*    .... doubly linked */
27723#if SQLITE_ENABLE_LOCKING_STYLE
27724  unsigned long long sharedByte;  /* for AFP simulated shared lock */
27725#endif
27726#if OS_VXWORKS
27727  sem_t *pSem;                    /* Named POSIX semaphore */
27728  char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
27729#endif
27730};
27731
27732/*
27733** A lists of all unixInodeInfo objects.
27734*/
27735static unixInodeInfo *inodeList = 0;
27736
27737/*
27738**
27739** This function - unixLogError_x(), is only ever called via the macro
27740** unixLogError().
27741**
27742** It is invoked after an error occurs in an OS function and errno has been
27743** set. It logs a message using sqlite3_log() containing the current value of
27744** errno and, if possible, the human-readable equivalent from strerror() or
27745** strerror_r().
27746**
27747** The first argument passed to the macro should be the error code that
27748** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
27749** The two subsequent arguments should be the name of the OS function that
27750** failed (e.g. "unlink", "open") and the associated file-system path,
27751** if any.
27752*/
27753#define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
27754static int unixLogErrorAtLine(
27755  int errcode,                    /* SQLite error code */
27756  const char *zFunc,              /* Name of OS function that failed */
27757  const char *zPath,              /* File path associated with error */
27758  int iLine                       /* Source line number where error occurred */
27759){
27760  char *zErr;                     /* Message from strerror() or equivalent */
27761  int iErrno = errno;             /* Saved syscall error number */
27762
27763  /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
27764  ** the strerror() function to obtain the human-readable error message
27765  ** equivalent to errno. Otherwise, use strerror_r().
27766  */
27767#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
27768  char aErr[80];
27769  memset(aErr, 0, sizeof(aErr));
27770  zErr = aErr;
27771
27772  /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
27773  ** assume that the system provides the GNU version of strerror_r() that
27774  ** returns a pointer to a buffer containing the error message. That pointer
27775  ** may point to aErr[], or it may point to some static storage somewhere.
27776  ** Otherwise, assume that the system provides the POSIX version of
27777  ** strerror_r(), which always writes an error message into aErr[].
27778  **
27779  ** If the code incorrectly assumes that it is the POSIX version that is
27780  ** available, the error message will often be an empty string. Not a
27781  ** huge problem. Incorrectly concluding that the GNU version is available
27782  ** could lead to a segfault though.
27783  */
27784#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
27785  zErr =
27786# endif
27787  strerror_r(iErrno, aErr, sizeof(aErr)-1);
27788
27789#elif SQLITE_THREADSAFE
27790  /* This is a threadsafe build, but strerror_r() is not available. */
27791  zErr = "";
27792#else
27793  /* Non-threadsafe build, use strerror(). */
27794  zErr = strerror(iErrno);
27795#endif
27796
27797  if( zPath==0 ) zPath = "";
27798  sqlite3_log(errcode,
27799      "os_unix.c:%d: (%d) %s(%s) - %s",
27800      iLine, iErrno, zFunc, zPath, zErr
27801  );
27802
27803  return errcode;
27804}
27805
27806/*
27807** Close a file descriptor.
27808**
27809** We assume that close() almost always works, since it is only in a
27810** very sick application or on a very sick platform that it might fail.
27811** If it does fail, simply leak the file descriptor, but do log the
27812** error.
27813**
27814** Note that it is not safe to retry close() after EINTR since the
27815** file descriptor might have already been reused by another thread.
27816** So we don't even try to recover from an EINTR.  Just log the error
27817** and move on.
27818*/
27819static void robust_close(unixFile *pFile, int h, int lineno){
27820  if( osClose(h) ){
27821    unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
27822                       pFile ? pFile->zPath : 0, lineno);
27823  }
27824}
27825
27826/*
27827** Set the pFile->lastErrno.  Do this in a subroutine as that provides
27828** a convenient place to set a breakpoint.
27829*/
27830static void storeLastErrno(unixFile *pFile, int error){
27831  pFile->lastErrno = error;
27832}
27833
27834/*
27835** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
27836*/
27837static void closePendingFds(unixFile *pFile){
27838  unixInodeInfo *pInode = pFile->pInode;
27839  UnixUnusedFd *p;
27840  UnixUnusedFd *pNext;
27841  for(p=pInode->pUnused; p; p=pNext){
27842    pNext = p->pNext;
27843    robust_close(pFile, p->fd, __LINE__);
27844    sqlite3_free(p);
27845  }
27846  pInode->pUnused = 0;
27847}
27848
27849/*
27850** Release a unixInodeInfo structure previously allocated by findInodeInfo().
27851**
27852** The mutex entered using the unixEnterMutex() function must be held
27853** when this function is called.
27854*/
27855static void releaseInodeInfo(unixFile *pFile){
27856  unixInodeInfo *pInode = pFile->pInode;
27857  assert( unixMutexHeld() );
27858  if( ALWAYS(pInode) ){
27859    pInode->nRef--;
27860    if( pInode->nRef==0 ){
27861      assert( pInode->pShmNode==0 );
27862      closePendingFds(pFile);
27863      if( pInode->pPrev ){
27864        assert( pInode->pPrev->pNext==pInode );
27865        pInode->pPrev->pNext = pInode->pNext;
27866      }else{
27867        assert( inodeList==pInode );
27868        inodeList = pInode->pNext;
27869      }
27870      if( pInode->pNext ){
27871        assert( pInode->pNext->pPrev==pInode );
27872        pInode->pNext->pPrev = pInode->pPrev;
27873      }
27874      sqlite3_free(pInode);
27875    }
27876  }
27877}
27878
27879/*
27880** Given a file descriptor, locate the unixInodeInfo object that
27881** describes that file descriptor.  Create a new one if necessary.  The
27882** return value might be uninitialized if an error occurs.
27883**
27884** The mutex entered using the unixEnterMutex() function must be held
27885** when this function is called.
27886**
27887** Return an appropriate error code.
27888*/
27889static int findInodeInfo(
27890  unixFile *pFile,               /* Unix file with file desc used in the key */
27891  unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
27892){
27893  int rc;                        /* System call return code */
27894  int fd;                        /* The file descriptor for pFile */
27895  struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
27896  struct stat statbuf;           /* Low-level file information */
27897  unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
27898
27899  assert( unixMutexHeld() );
27900
27901  /* Get low-level information about the file that we can used to
27902  ** create a unique name for the file.
27903  */
27904  fd = pFile->h;
27905  rc = osFstat(fd, &statbuf);
27906  if( rc!=0 ){
27907    storeLastErrno(pFile, errno);
27908#ifdef EOVERFLOW
27909    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
27910#endif
27911    return SQLITE_IOERR;
27912  }
27913
27914#ifdef __APPLE__
27915  /* On OS X on an msdos filesystem, the inode number is reported
27916  ** incorrectly for zero-size files.  See ticket #3260.  To work
27917  ** around this problem (we consider it a bug in OS X, not SQLite)
27918  ** we always increase the file size to 1 by writing a single byte
27919  ** prior to accessing the inode number.  The one byte written is
27920  ** an ASCII 'S' character which also happens to be the first byte
27921  ** in the header of every SQLite database.  In this way, if there
27922  ** is a race condition such that another thread has already populated
27923  ** the first page of the database, no damage is done.
27924  */
27925  if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
27926    do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
27927    if( rc!=1 ){
27928      storeLastErrno(pFile, errno);
27929      return SQLITE_IOERR;
27930    }
27931    rc = osFstat(fd, &statbuf);
27932    if( rc!=0 ){
27933      storeLastErrno(pFile, errno);
27934      return SQLITE_IOERR;
27935    }
27936  }
27937#endif
27938
27939  memset(&fileId, 0, sizeof(fileId));
27940  fileId.dev = statbuf.st_dev;
27941#if OS_VXWORKS
27942  fileId.pId = pFile->pId;
27943#else
27944  fileId.ino = statbuf.st_ino;
27945#endif
27946  pInode = inodeList;
27947  while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
27948    pInode = pInode->pNext;
27949  }
27950  if( pInode==0 ){
27951    pInode = sqlite3_malloc64( sizeof(*pInode) );
27952    if( pInode==0 ){
27953      return SQLITE_NOMEM;
27954    }
27955    memset(pInode, 0, sizeof(*pInode));
27956    memcpy(&pInode->fileId, &fileId, sizeof(fileId));
27957    pInode->nRef = 1;
27958    pInode->pNext = inodeList;
27959    pInode->pPrev = 0;
27960    if( inodeList ) inodeList->pPrev = pInode;
27961    inodeList = pInode;
27962  }else{
27963    pInode->nRef++;
27964  }
27965  *ppInode = pInode;
27966  return SQLITE_OK;
27967}
27968
27969/*
27970** Return TRUE if pFile has been renamed or unlinked since it was first opened.
27971*/
27972static int fileHasMoved(unixFile *pFile){
27973#if OS_VXWORKS
27974  return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
27975#else
27976  struct stat buf;
27977  return pFile->pInode!=0 &&
27978      (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
27979#endif
27980}
27981
27982
27983/*
27984** Check a unixFile that is a database.  Verify the following:
27985**
27986** (1) There is exactly one hard link on the file
27987** (2) The file is not a symbolic link
27988** (3) The file has not been renamed or unlinked
27989**
27990** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
27991*/
27992static void verifyDbFile(unixFile *pFile){
27993  struct stat buf;
27994  int rc;
27995  if( pFile->ctrlFlags & UNIXFILE_WARNED ){
27996    /* One or more of the following warnings have already been issued.  Do not
27997    ** repeat them so as not to clutter the error log */
27998    return;
27999  }
28000  rc = osFstat(pFile->h, &buf);
28001  if( rc!=0 ){
28002    sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
28003    pFile->ctrlFlags |= UNIXFILE_WARNED;
28004    return;
28005  }
28006  if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
28007    sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
28008    pFile->ctrlFlags |= UNIXFILE_WARNED;
28009    return;
28010  }
28011  if( buf.st_nlink>1 ){
28012    sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
28013    pFile->ctrlFlags |= UNIXFILE_WARNED;
28014    return;
28015  }
28016  if( fileHasMoved(pFile) ){
28017    sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
28018    pFile->ctrlFlags |= UNIXFILE_WARNED;
28019    return;
28020  }
28021}
28022
28023
28024/*
28025** This routine checks if there is a RESERVED lock held on the specified
28026** file by this or any other process. If such a lock is held, set *pResOut
28027** to a non-zero value otherwise *pResOut is set to zero.  The return value
28028** is set to SQLITE_OK unless an I/O error occurs during lock checking.
28029*/
28030static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
28031  int rc = SQLITE_OK;
28032  int reserved = 0;
28033  unixFile *pFile = (unixFile*)id;
28034
28035  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
28036
28037  assert( pFile );
28038  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
28039
28040  /* Check if a thread in this process holds such a lock */
28041  if( pFile->pInode->eFileLock>SHARED_LOCK ){
28042    reserved = 1;
28043  }
28044
28045  /* Otherwise see if some other process holds it.
28046  */
28047#ifndef __DJGPP__
28048  if( !reserved && !pFile->pInode->bProcessLock ){
28049    struct flock lock;
28050    lock.l_whence = SEEK_SET;
28051    lock.l_start = RESERVED_BYTE;
28052    lock.l_len = 1;
28053    lock.l_type = F_WRLCK;
28054    if( osFcntl(pFile->h, F_GETLK, &lock) ){
28055      rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
28056      storeLastErrno(pFile, errno);
28057    } else if( lock.l_type!=F_UNLCK ){
28058      reserved = 1;
28059    }
28060  }
28061#endif
28062
28063  unixLeaveMutex();
28064  OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
28065
28066  *pResOut = reserved;
28067  return rc;
28068}
28069
28070/*
28071** Attempt to set a system-lock on the file pFile.  The lock is
28072** described by pLock.
28073**
28074** If the pFile was opened read/write from unix-excl, then the only lock
28075** ever obtained is an exclusive lock, and it is obtained exactly once
28076** the first time any lock is attempted.  All subsequent system locking
28077** operations become no-ops.  Locking operations still happen internally,
28078** in order to coordinate access between separate database connections
28079** within this process, but all of that is handled in memory and the
28080** operating system does not participate.
28081**
28082** This function is a pass-through to fcntl(F_SETLK) if pFile is using
28083** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
28084** and is read-only.
28085**
28086** Zero is returned if the call completes successfully, or -1 if a call
28087** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
28088*/
28089static int unixFileLock(unixFile *pFile, struct flock *pLock){
28090  int rc;
28091  unixInodeInfo *pInode = pFile->pInode;
28092  assert( unixMutexHeld() );
28093  assert( pInode!=0 );
28094  if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
28095   && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
28096  ){
28097    if( pInode->bProcessLock==0 ){
28098      struct flock lock;
28099      assert( pInode->nLock==0 );
28100      lock.l_whence = SEEK_SET;
28101      lock.l_start = SHARED_FIRST;
28102      lock.l_len = SHARED_SIZE;
28103      lock.l_type = F_WRLCK;
28104      rc = osFcntl(pFile->h, F_SETLK, &lock);
28105      if( rc<0 ) return rc;
28106      pInode->bProcessLock = 1;
28107      pInode->nLock++;
28108    }else{
28109      rc = 0;
28110    }
28111  }else{
28112    rc = osFcntl(pFile->h, F_SETLK, pLock);
28113  }
28114  return rc;
28115}
28116
28117/*
28118** Lock the file with the lock specified by parameter eFileLock - one
28119** of the following:
28120**
28121**     (1) SHARED_LOCK
28122**     (2) RESERVED_LOCK
28123**     (3) PENDING_LOCK
28124**     (4) EXCLUSIVE_LOCK
28125**
28126** Sometimes when requesting one lock state, additional lock states
28127** are inserted in between.  The locking might fail on one of the later
28128** transitions leaving the lock state different from what it started but
28129** still short of its goal.  The following chart shows the allowed
28130** transitions and the inserted intermediate states:
28131**
28132**    UNLOCKED -> SHARED
28133**    SHARED -> RESERVED
28134**    SHARED -> (PENDING) -> EXCLUSIVE
28135**    RESERVED -> (PENDING) -> EXCLUSIVE
28136**    PENDING -> EXCLUSIVE
28137**
28138** This routine will only increase a lock.  Use the sqlite3OsUnlock()
28139** routine to lower a locking level.
28140*/
28141static int unixLock(sqlite3_file *id, int eFileLock){
28142  /* The following describes the implementation of the various locks and
28143  ** lock transitions in terms of the POSIX advisory shared and exclusive
28144  ** lock primitives (called read-locks and write-locks below, to avoid
28145  ** confusion with SQLite lock names). The algorithms are complicated
28146  ** slightly in order to be compatible with windows systems simultaneously
28147  ** accessing the same database file, in case that is ever required.
28148  **
28149  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
28150  ** byte', each single bytes at well known offsets, and the 'shared byte
28151  ** range', a range of 510 bytes at a well known offset.
28152  **
28153  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
28154  ** byte'.  If this is successful, a random byte from the 'shared byte
28155  ** range' is read-locked and the lock on the 'pending byte' released.
28156  **
28157  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
28158  ** A RESERVED lock is implemented by grabbing a write-lock on the
28159  ** 'reserved byte'.
28160  **
28161  ** A process may only obtain a PENDING lock after it has obtained a
28162  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
28163  ** on the 'pending byte'. This ensures that no new SHARED locks can be
28164  ** obtained, but existing SHARED locks are allowed to persist. A process
28165  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
28166  ** This property is used by the algorithm for rolling back a journal file
28167  ** after a crash.
28168  **
28169  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
28170  ** implemented by obtaining a write-lock on the entire 'shared byte
28171  ** range'. Since all other locks require a read-lock on one of the bytes
28172  ** within this range, this ensures that no other locks are held on the
28173  ** database.
28174  **
28175  ** The reason a single byte cannot be used instead of the 'shared byte
28176  ** range' is that some versions of windows do not support read-locks. By
28177  ** locking a random byte from a range, concurrent SHARED locks may exist
28178  ** even if the locking primitive used is always a write-lock.
28179  */
28180  int rc = SQLITE_OK;
28181  unixFile *pFile = (unixFile*)id;
28182  unixInodeInfo *pInode;
28183  struct flock lock;
28184  int tErrno = 0;
28185
28186  assert( pFile );
28187  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
28188      azFileLock(eFileLock), azFileLock(pFile->eFileLock),
28189      azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
28190      osGetpid(0)));
28191
28192  /* If there is already a lock of this type or more restrictive on the
28193  ** unixFile, do nothing. Don't use the end_lock: exit path, as
28194  ** unixEnterMutex() hasn't been called yet.
28195  */
28196  if( pFile->eFileLock>=eFileLock ){
28197    OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
28198            azFileLock(eFileLock)));
28199    return SQLITE_OK;
28200  }
28201
28202  /* Make sure the locking sequence is correct.
28203  **  (1) We never move from unlocked to anything higher than shared lock.
28204  **  (2) SQLite never explicitly requests a pendig lock.
28205  **  (3) A shared lock is always held when a reserve lock is requested.
28206  */
28207  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
28208  assert( eFileLock!=PENDING_LOCK );
28209  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
28210
28211  /* This mutex is needed because pFile->pInode is shared across threads
28212  */
28213  unixEnterMutex();
28214  pInode = pFile->pInode;
28215
28216  /* If some thread using this PID has a lock via a different unixFile*
28217  ** handle that precludes the requested lock, return BUSY.
28218  */
28219  if( (pFile->eFileLock!=pInode->eFileLock &&
28220          (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
28221  ){
28222    rc = SQLITE_BUSY;
28223    goto end_lock;
28224  }
28225
28226  /* If a SHARED lock is requested, and some thread using this PID already
28227  ** has a SHARED or RESERVED lock, then increment reference counts and
28228  ** return SQLITE_OK.
28229  */
28230  if( eFileLock==SHARED_LOCK &&
28231      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
28232    assert( eFileLock==SHARED_LOCK );
28233    assert( pFile->eFileLock==0 );
28234    assert( pInode->nShared>0 );
28235    pFile->eFileLock = SHARED_LOCK;
28236    pInode->nShared++;
28237    pInode->nLock++;
28238    goto end_lock;
28239  }
28240
28241
28242  /* A PENDING lock is needed before acquiring a SHARED lock and before
28243  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
28244  ** be released.
28245  */
28246  lock.l_len = 1L;
28247  lock.l_whence = SEEK_SET;
28248  if( eFileLock==SHARED_LOCK
28249      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
28250  ){
28251    lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
28252    lock.l_start = PENDING_BYTE;
28253    if( unixFileLock(pFile, &lock) ){
28254      tErrno = errno;
28255      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
28256      if( rc!=SQLITE_BUSY ){
28257        storeLastErrno(pFile, tErrno);
28258      }
28259      goto end_lock;
28260    }
28261  }
28262
28263
28264  /* If control gets to this point, then actually go ahead and make
28265  ** operating system calls for the specified lock.
28266  */
28267  if( eFileLock==SHARED_LOCK ){
28268    assert( pInode->nShared==0 );
28269    assert( pInode->eFileLock==0 );
28270    assert( rc==SQLITE_OK );
28271
28272    /* Now get the read-lock */
28273    lock.l_start = SHARED_FIRST;
28274    lock.l_len = SHARED_SIZE;
28275    if( unixFileLock(pFile, &lock) ){
28276      tErrno = errno;
28277      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
28278    }
28279
28280    /* Drop the temporary PENDING lock */
28281    lock.l_start = PENDING_BYTE;
28282    lock.l_len = 1L;
28283    lock.l_type = F_UNLCK;
28284    if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
28285      /* This could happen with a network mount */
28286      tErrno = errno;
28287      rc = SQLITE_IOERR_UNLOCK;
28288    }
28289
28290    if( rc ){
28291      if( rc!=SQLITE_BUSY ){
28292        storeLastErrno(pFile, tErrno);
28293      }
28294      goto end_lock;
28295    }else{
28296      pFile->eFileLock = SHARED_LOCK;
28297      pInode->nLock++;
28298      pInode->nShared = 1;
28299    }
28300  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
28301    /* We are trying for an exclusive lock but another thread in this
28302    ** same process is still holding a shared lock. */
28303    rc = SQLITE_BUSY;
28304  }else{
28305    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
28306    ** assumed that there is a SHARED or greater lock on the file
28307    ** already.
28308    */
28309    assert( 0!=pFile->eFileLock );
28310    lock.l_type = F_WRLCK;
28311
28312    assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
28313    if( eFileLock==RESERVED_LOCK ){
28314      lock.l_start = RESERVED_BYTE;
28315      lock.l_len = 1L;
28316    }else{
28317      lock.l_start = SHARED_FIRST;
28318      lock.l_len = SHARED_SIZE;
28319    }
28320
28321    if( unixFileLock(pFile, &lock) ){
28322      tErrno = errno;
28323      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
28324      if( rc!=SQLITE_BUSY ){
28325        storeLastErrno(pFile, tErrno);
28326      }
28327    }
28328  }
28329
28330
28331#ifdef SQLITE_DEBUG
28332  /* Set up the transaction-counter change checking flags when
28333  ** transitioning from a SHARED to a RESERVED lock.  The change
28334  ** from SHARED to RESERVED marks the beginning of a normal
28335  ** write operation (not a hot journal rollback).
28336  */
28337  if( rc==SQLITE_OK
28338   && pFile->eFileLock<=SHARED_LOCK
28339   && eFileLock==RESERVED_LOCK
28340  ){
28341    pFile->transCntrChng = 0;
28342    pFile->dbUpdate = 0;
28343    pFile->inNormalWrite = 1;
28344  }
28345#endif
28346
28347
28348  if( rc==SQLITE_OK ){
28349    pFile->eFileLock = eFileLock;
28350    pInode->eFileLock = eFileLock;
28351  }else if( eFileLock==EXCLUSIVE_LOCK ){
28352    pFile->eFileLock = PENDING_LOCK;
28353    pInode->eFileLock = PENDING_LOCK;
28354  }
28355
28356end_lock:
28357  unixLeaveMutex();
28358  OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
28359      rc==SQLITE_OK ? "ok" : "failed"));
28360  return rc;
28361}
28362
28363/*
28364** Add the file descriptor used by file handle pFile to the corresponding
28365** pUnused list.
28366*/
28367static void setPendingFd(unixFile *pFile){
28368  unixInodeInfo *pInode = pFile->pInode;
28369  UnixUnusedFd *p = pFile->pUnused;
28370  p->pNext = pInode->pUnused;
28371  pInode->pUnused = p;
28372  pFile->h = -1;
28373  pFile->pUnused = 0;
28374}
28375
28376/*
28377** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28378** must be either NO_LOCK or SHARED_LOCK.
28379**
28380** If the locking level of the file descriptor is already at or below
28381** the requested locking level, this routine is a no-op.
28382**
28383** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
28384** the byte range is divided into 2 parts and the first part is unlocked then
28385** set to a read lock, then the other part is simply unlocked.  This works
28386** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
28387** remove the write lock on a region when a read lock is set.
28388*/
28389static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
28390  unixFile *pFile = (unixFile*)id;
28391  unixInodeInfo *pInode;
28392  struct flock lock;
28393  int rc = SQLITE_OK;
28394
28395  assert( pFile );
28396  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
28397      pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
28398      osGetpid(0)));
28399
28400  assert( eFileLock<=SHARED_LOCK );
28401  if( pFile->eFileLock<=eFileLock ){
28402    return SQLITE_OK;
28403  }
28404  unixEnterMutex();
28405  pInode = pFile->pInode;
28406  assert( pInode->nShared!=0 );
28407  if( pFile->eFileLock>SHARED_LOCK ){
28408    assert( pInode->eFileLock==pFile->eFileLock );
28409
28410#ifdef SQLITE_DEBUG
28411    /* When reducing a lock such that other processes can start
28412    ** reading the database file again, make sure that the
28413    ** transaction counter was updated if any part of the database
28414    ** file changed.  If the transaction counter is not updated,
28415    ** other connections to the same file might not realize that
28416    ** the file has changed and hence might not know to flush their
28417    ** cache.  The use of a stale cache can lead to database corruption.
28418    */
28419    pFile->inNormalWrite = 0;
28420#endif
28421
28422    /* downgrading to a shared lock on NFS involves clearing the write lock
28423    ** before establishing the readlock - to avoid a race condition we downgrade
28424    ** the lock in 2 blocks, so that part of the range will be covered by a
28425    ** write lock until the rest is covered by a read lock:
28426    **  1:   [WWWWW]
28427    **  2:   [....W]
28428    **  3:   [RRRRW]
28429    **  4:   [RRRR.]
28430    */
28431    if( eFileLock==SHARED_LOCK ){
28432#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
28433      (void)handleNFSUnlock;
28434      assert( handleNFSUnlock==0 );
28435#endif
28436#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28437      if( handleNFSUnlock ){
28438        int tErrno;               /* Error code from system call errors */
28439        off_t divSize = SHARED_SIZE - 1;
28440
28441        lock.l_type = F_UNLCK;
28442        lock.l_whence = SEEK_SET;
28443        lock.l_start = SHARED_FIRST;
28444        lock.l_len = divSize;
28445        if( unixFileLock(pFile, &lock)==(-1) ){
28446          tErrno = errno;
28447          rc = SQLITE_IOERR_UNLOCK;
28448          if( IS_LOCK_ERROR(rc) ){
28449            storeLastErrno(pFile, tErrno);
28450          }
28451          goto end_unlock;
28452        }
28453        lock.l_type = F_RDLCK;
28454        lock.l_whence = SEEK_SET;
28455        lock.l_start = SHARED_FIRST;
28456        lock.l_len = divSize;
28457        if( unixFileLock(pFile, &lock)==(-1) ){
28458          tErrno = errno;
28459          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
28460          if( IS_LOCK_ERROR(rc) ){
28461            storeLastErrno(pFile, tErrno);
28462          }
28463          goto end_unlock;
28464        }
28465        lock.l_type = F_UNLCK;
28466        lock.l_whence = SEEK_SET;
28467        lock.l_start = SHARED_FIRST+divSize;
28468        lock.l_len = SHARED_SIZE-divSize;
28469        if( unixFileLock(pFile, &lock)==(-1) ){
28470          tErrno = errno;
28471          rc = SQLITE_IOERR_UNLOCK;
28472          if( IS_LOCK_ERROR(rc) ){
28473            storeLastErrno(pFile, tErrno);
28474          }
28475          goto end_unlock;
28476        }
28477      }else
28478#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28479      {
28480        lock.l_type = F_RDLCK;
28481        lock.l_whence = SEEK_SET;
28482        lock.l_start = SHARED_FIRST;
28483        lock.l_len = SHARED_SIZE;
28484        if( unixFileLock(pFile, &lock) ){
28485          /* In theory, the call to unixFileLock() cannot fail because another
28486          ** process is holding an incompatible lock. If it does, this
28487          ** indicates that the other process is not following the locking
28488          ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
28489          ** SQLITE_BUSY would confuse the upper layer (in practice it causes
28490          ** an assert to fail). */
28491          rc = SQLITE_IOERR_RDLOCK;
28492          storeLastErrno(pFile, errno);
28493          goto end_unlock;
28494        }
28495      }
28496    }
28497    lock.l_type = F_UNLCK;
28498    lock.l_whence = SEEK_SET;
28499    lock.l_start = PENDING_BYTE;
28500    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
28501    if( unixFileLock(pFile, &lock)==0 ){
28502      pInode->eFileLock = SHARED_LOCK;
28503    }else{
28504      rc = SQLITE_IOERR_UNLOCK;
28505      storeLastErrno(pFile, errno);
28506      goto end_unlock;
28507    }
28508  }
28509  if( eFileLock==NO_LOCK ){
28510    /* Decrement the shared lock counter.  Release the lock using an
28511    ** OS call only when all threads in this same process have released
28512    ** the lock.
28513    */
28514    pInode->nShared--;
28515    if( pInode->nShared==0 ){
28516      lock.l_type = F_UNLCK;
28517      lock.l_whence = SEEK_SET;
28518      lock.l_start = lock.l_len = 0L;
28519      if( unixFileLock(pFile, &lock)==0 ){
28520        pInode->eFileLock = NO_LOCK;
28521      }else{
28522        rc = SQLITE_IOERR_UNLOCK;
28523        storeLastErrno(pFile, errno);
28524        pInode->eFileLock = NO_LOCK;
28525        pFile->eFileLock = NO_LOCK;
28526      }
28527    }
28528
28529    /* Decrement the count of locks against this same file.  When the
28530    ** count reaches zero, close any other file descriptors whose close
28531    ** was deferred because of outstanding locks.
28532    */
28533    pInode->nLock--;
28534    assert( pInode->nLock>=0 );
28535    if( pInode->nLock==0 ){
28536      closePendingFds(pFile);
28537    }
28538  }
28539
28540end_unlock:
28541  unixLeaveMutex();
28542  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
28543  return rc;
28544}
28545
28546/*
28547** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28548** must be either NO_LOCK or SHARED_LOCK.
28549**
28550** If the locking level of the file descriptor is already at or below
28551** the requested locking level, this routine is a no-op.
28552*/
28553static int unixUnlock(sqlite3_file *id, int eFileLock){
28554#if SQLITE_MAX_MMAP_SIZE>0
28555  assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
28556#endif
28557  return posixUnlock(id, eFileLock, 0);
28558}
28559
28560#if SQLITE_MAX_MMAP_SIZE>0
28561static int unixMapfile(unixFile *pFd, i64 nByte);
28562static void unixUnmapfile(unixFile *pFd);
28563#endif
28564
28565/*
28566** This function performs the parts of the "close file" operation
28567** common to all locking schemes. It closes the directory and file
28568** handles, if they are valid, and sets all fields of the unixFile
28569** structure to 0.
28570**
28571** It is *not* necessary to hold the mutex when this routine is called,
28572** even on VxWorks.  A mutex will be acquired on VxWorks by the
28573** vxworksReleaseFileId() routine.
28574*/
28575static int closeUnixFile(sqlite3_file *id){
28576  unixFile *pFile = (unixFile*)id;
28577#if SQLITE_MAX_MMAP_SIZE>0
28578  unixUnmapfile(pFile);
28579#endif
28580  if( pFile->h>=0 ){
28581    robust_close(pFile, pFile->h, __LINE__);
28582    pFile->h = -1;
28583  }
28584#if OS_VXWORKS
28585  if( pFile->pId ){
28586    if( pFile->ctrlFlags & UNIXFILE_DELETE ){
28587      osUnlink(pFile->pId->zCanonicalName);
28588    }
28589    vxworksReleaseFileId(pFile->pId);
28590    pFile->pId = 0;
28591  }
28592#endif
28593#ifdef SQLITE_UNLINK_AFTER_CLOSE
28594  if( pFile->ctrlFlags & UNIXFILE_DELETE ){
28595    osUnlink(pFile->zPath);
28596    sqlite3_free(*(char**)&pFile->zPath);
28597    pFile->zPath = 0;
28598  }
28599#endif
28600  OSTRACE(("CLOSE   %-3d\n", pFile->h));
28601  OpenCounter(-1);
28602  sqlite3_free(pFile->pUnused);
28603  memset(pFile, 0, sizeof(unixFile));
28604  return SQLITE_OK;
28605}
28606
28607/*
28608** Close a file.
28609*/
28610static int unixClose(sqlite3_file *id){
28611  int rc = SQLITE_OK;
28612  unixFile *pFile = (unixFile *)id;
28613  verifyDbFile(pFile);
28614  unixUnlock(id, NO_LOCK);
28615  unixEnterMutex();
28616
28617  /* unixFile.pInode is always valid here. Otherwise, a different close
28618  ** routine (e.g. nolockClose()) would be called instead.
28619  */
28620  assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
28621  if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
28622    /* If there are outstanding locks, do not actually close the file just
28623    ** yet because that would clear those locks.  Instead, add the file
28624    ** descriptor to pInode->pUnused list.  It will be automatically closed
28625    ** when the last lock is cleared.
28626    */
28627    setPendingFd(pFile);
28628  }
28629  releaseInodeInfo(pFile);
28630  rc = closeUnixFile(id);
28631  unixLeaveMutex();
28632  return rc;
28633}
28634
28635/************** End of the posix advisory lock implementation *****************
28636******************************************************************************/
28637
28638/******************************************************************************
28639****************************** No-op Locking **********************************
28640**
28641** Of the various locking implementations available, this is by far the
28642** simplest:  locking is ignored.  No attempt is made to lock the database
28643** file for reading or writing.
28644**
28645** This locking mode is appropriate for use on read-only databases
28646** (ex: databases that are burned into CD-ROM, for example.)  It can
28647** also be used if the application employs some external mechanism to
28648** prevent simultaneous access of the same database by two or more
28649** database connections.  But there is a serious risk of database
28650** corruption if this locking mode is used in situations where multiple
28651** database connections are accessing the same database file at the same
28652** time and one or more of those connections are writing.
28653*/
28654
28655static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
28656  UNUSED_PARAMETER(NotUsed);
28657  *pResOut = 0;
28658  return SQLITE_OK;
28659}
28660static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
28661  UNUSED_PARAMETER2(NotUsed, NotUsed2);
28662  return SQLITE_OK;
28663}
28664static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
28665  UNUSED_PARAMETER2(NotUsed, NotUsed2);
28666  return SQLITE_OK;
28667}
28668
28669/*
28670** Close the file.
28671*/
28672static int nolockClose(sqlite3_file *id) {
28673  return closeUnixFile(id);
28674}
28675
28676/******************* End of the no-op lock implementation *********************
28677******************************************************************************/
28678
28679/******************************************************************************
28680************************* Begin dot-file Locking ******************************
28681**
28682** The dotfile locking implementation uses the existence of separate lock
28683** files (really a directory) to control access to the database.  This works
28684** on just about every filesystem imaginable.  But there are serious downsides:
28685**
28686**    (1)  There is zero concurrency.  A single reader blocks all other
28687**         connections from reading or writing the database.
28688**
28689**    (2)  An application crash or power loss can leave stale lock files
28690**         sitting around that need to be cleared manually.
28691**
28692** Nevertheless, a dotlock is an appropriate locking mode for use if no
28693** other locking strategy is available.
28694**
28695** Dotfile locking works by creating a subdirectory in the same directory as
28696** the database and with the same name but with a ".lock" extension added.
28697** The existence of a lock directory implies an EXCLUSIVE lock.  All other
28698** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
28699*/
28700
28701/*
28702** The file suffix added to the data base filename in order to create the
28703** lock directory.
28704*/
28705#define DOTLOCK_SUFFIX ".lock"
28706
28707/*
28708** This routine checks if there is a RESERVED lock held on the specified
28709** file by this or any other process. If such a lock is held, set *pResOut
28710** to a non-zero value otherwise *pResOut is set to zero.  The return value
28711** is set to SQLITE_OK unless an I/O error occurs during lock checking.
28712**
28713** In dotfile locking, either a lock exists or it does not.  So in this
28714** variation of CheckReservedLock(), *pResOut is set to true if any lock
28715** is held on the file and false if the file is unlocked.
28716*/
28717static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
28718  int rc = SQLITE_OK;
28719  int reserved = 0;
28720  unixFile *pFile = (unixFile*)id;
28721
28722  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
28723
28724  assert( pFile );
28725
28726  /* Check if a thread in this process holds such a lock */
28727  if( pFile->eFileLock>SHARED_LOCK ){
28728    /* Either this connection or some other connection in the same process
28729    ** holds a lock on the file.  No need to check further. */
28730    reserved = 1;
28731  }else{
28732    /* The lock is held if and only if the lockfile exists */
28733    const char *zLockFile = (const char*)pFile->lockingContext;
28734    reserved = osAccess(zLockFile, 0)==0;
28735  }
28736  OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
28737  *pResOut = reserved;
28738  return rc;
28739}
28740
28741/*
28742** Lock the file with the lock specified by parameter eFileLock - one
28743** of the following:
28744**
28745**     (1) SHARED_LOCK
28746**     (2) RESERVED_LOCK
28747**     (3) PENDING_LOCK
28748**     (4) EXCLUSIVE_LOCK
28749**
28750** Sometimes when requesting one lock state, additional lock states
28751** are inserted in between.  The locking might fail on one of the later
28752** transitions leaving the lock state different from what it started but
28753** still short of its goal.  The following chart shows the allowed
28754** transitions and the inserted intermediate states:
28755**
28756**    UNLOCKED -> SHARED
28757**    SHARED -> RESERVED
28758**    SHARED -> (PENDING) -> EXCLUSIVE
28759**    RESERVED -> (PENDING) -> EXCLUSIVE
28760**    PENDING -> EXCLUSIVE
28761**
28762** This routine will only increase a lock.  Use the sqlite3OsUnlock()
28763** routine to lower a locking level.
28764**
28765** With dotfile locking, we really only support state (4): EXCLUSIVE.
28766** But we track the other locking levels internally.
28767*/
28768static int dotlockLock(sqlite3_file *id, int eFileLock) {
28769  unixFile *pFile = (unixFile*)id;
28770  char *zLockFile = (char *)pFile->lockingContext;
28771  int rc = SQLITE_OK;
28772
28773
28774  /* If we have any lock, then the lock file already exists.  All we have
28775  ** to do is adjust our internal record of the lock level.
28776  */
28777  if( pFile->eFileLock > NO_LOCK ){
28778    pFile->eFileLock = eFileLock;
28779    /* Always update the timestamp on the old file */
28780#ifdef HAVE_UTIME
28781    utime(zLockFile, NULL);
28782#else
28783    utimes(zLockFile, NULL);
28784#endif
28785    return SQLITE_OK;
28786  }
28787
28788  /* grab an exclusive lock */
28789  rc = osMkdir(zLockFile, 0777);
28790  if( rc<0 ){
28791    /* failed to open/create the lock directory */
28792    int tErrno = errno;
28793    if( EEXIST == tErrno ){
28794      rc = SQLITE_BUSY;
28795    } else {
28796      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
28797      if( IS_LOCK_ERROR(rc) ){
28798        storeLastErrno(pFile, tErrno);
28799      }
28800    }
28801    return rc;
28802  }
28803
28804  /* got it, set the type and return ok */
28805  pFile->eFileLock = eFileLock;
28806  return rc;
28807}
28808
28809/*
28810** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28811** must be either NO_LOCK or SHARED_LOCK.
28812**
28813** If the locking level of the file descriptor is already at or below
28814** the requested locking level, this routine is a no-op.
28815**
28816** When the locking level reaches NO_LOCK, delete the lock file.
28817*/
28818static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
28819  unixFile *pFile = (unixFile*)id;
28820  char *zLockFile = (char *)pFile->lockingContext;
28821  int rc;
28822
28823  assert( pFile );
28824  OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
28825           pFile->eFileLock, osGetpid(0)));
28826  assert( eFileLock<=SHARED_LOCK );
28827
28828  /* no-op if possible */
28829  if( pFile->eFileLock==eFileLock ){
28830    return SQLITE_OK;
28831  }
28832
28833  /* To downgrade to shared, simply update our internal notion of the
28834  ** lock state.  No need to mess with the file on disk.
28835  */
28836  if( eFileLock==SHARED_LOCK ){
28837    pFile->eFileLock = SHARED_LOCK;
28838    return SQLITE_OK;
28839  }
28840
28841  /* To fully unlock the database, delete the lock file */
28842  assert( eFileLock==NO_LOCK );
28843  rc = osRmdir(zLockFile);
28844  if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
28845  if( rc<0 ){
28846    int tErrno = errno;
28847    rc = 0;
28848    if( ENOENT != tErrno ){
28849      rc = SQLITE_IOERR_UNLOCK;
28850    }
28851    if( IS_LOCK_ERROR(rc) ){
28852      storeLastErrno(pFile, tErrno);
28853    }
28854    return rc;
28855  }
28856  pFile->eFileLock = NO_LOCK;
28857  return SQLITE_OK;
28858}
28859
28860/*
28861** Close a file.  Make sure the lock has been released before closing.
28862*/
28863static int dotlockClose(sqlite3_file *id) {
28864  int rc = SQLITE_OK;
28865  if( id ){
28866    unixFile *pFile = (unixFile*)id;
28867    dotlockUnlock(id, NO_LOCK);
28868    sqlite3_free(pFile->lockingContext);
28869    rc = closeUnixFile(id);
28870  }
28871  return rc;
28872}
28873/****************** End of the dot-file lock implementation *******************
28874******************************************************************************/
28875
28876/******************************************************************************
28877************************** Begin flock Locking ********************************
28878**
28879** Use the flock() system call to do file locking.
28880**
28881** flock() locking is like dot-file locking in that the various
28882** fine-grain locking levels supported by SQLite are collapsed into
28883** a single exclusive lock.  In other words, SHARED, RESERVED, and
28884** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
28885** still works when you do this, but concurrency is reduced since
28886** only a single process can be reading the database at a time.
28887**
28888** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
28889*/
28890#if SQLITE_ENABLE_LOCKING_STYLE
28891
28892/*
28893** Retry flock() calls that fail with EINTR
28894*/
28895#ifdef EINTR
28896static int robust_flock(int fd, int op){
28897  int rc;
28898  do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
28899  return rc;
28900}
28901#else
28902# define robust_flock(a,b) flock(a,b)
28903#endif
28904
28905
28906/*
28907** This routine checks if there is a RESERVED lock held on the specified
28908** file by this or any other process. If such a lock is held, set *pResOut
28909** to a non-zero value otherwise *pResOut is set to zero.  The return value
28910** is set to SQLITE_OK unless an I/O error occurs during lock checking.
28911*/
28912static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
28913  int rc = SQLITE_OK;
28914  int reserved = 0;
28915  unixFile *pFile = (unixFile*)id;
28916
28917  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
28918
28919  assert( pFile );
28920
28921  /* Check if a thread in this process holds such a lock */
28922  if( pFile->eFileLock>SHARED_LOCK ){
28923    reserved = 1;
28924  }
28925
28926  /* Otherwise see if some other process holds it. */
28927  if( !reserved ){
28928    /* attempt to get the lock */
28929    int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
28930    if( !lrc ){
28931      /* got the lock, unlock it */
28932      lrc = robust_flock(pFile->h, LOCK_UN);
28933      if ( lrc ) {
28934        int tErrno = errno;
28935        /* unlock failed with an error */
28936        lrc = SQLITE_IOERR_UNLOCK;
28937        if( IS_LOCK_ERROR(lrc) ){
28938          storeLastErrno(pFile, tErrno);
28939          rc = lrc;
28940        }
28941      }
28942    } else {
28943      int tErrno = errno;
28944      reserved = 1;
28945      /* someone else might have it reserved */
28946      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
28947      if( IS_LOCK_ERROR(lrc) ){
28948        storeLastErrno(pFile, tErrno);
28949        rc = lrc;
28950      }
28951    }
28952  }
28953  OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
28954
28955#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
28956  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
28957    rc = SQLITE_OK;
28958    reserved=1;
28959  }
28960#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
28961  *pResOut = reserved;
28962  return rc;
28963}
28964
28965/*
28966** Lock the file with the lock specified by parameter eFileLock - one
28967** of the following:
28968**
28969**     (1) SHARED_LOCK
28970**     (2) RESERVED_LOCK
28971**     (3) PENDING_LOCK
28972**     (4) EXCLUSIVE_LOCK
28973**
28974** Sometimes when requesting one lock state, additional lock states
28975** are inserted in between.  The locking might fail on one of the later
28976** transitions leaving the lock state different from what it started but
28977** still short of its goal.  The following chart shows the allowed
28978** transitions and the inserted intermediate states:
28979**
28980**    UNLOCKED -> SHARED
28981**    SHARED -> RESERVED
28982**    SHARED -> (PENDING) -> EXCLUSIVE
28983**    RESERVED -> (PENDING) -> EXCLUSIVE
28984**    PENDING -> EXCLUSIVE
28985**
28986** flock() only really support EXCLUSIVE locks.  We track intermediate
28987** lock states in the sqlite3_file structure, but all locks SHARED or
28988** above are really EXCLUSIVE locks and exclude all other processes from
28989** access the file.
28990**
28991** This routine will only increase a lock.  Use the sqlite3OsUnlock()
28992** routine to lower a locking level.
28993*/
28994static int flockLock(sqlite3_file *id, int eFileLock) {
28995  int rc = SQLITE_OK;
28996  unixFile *pFile = (unixFile*)id;
28997
28998  assert( pFile );
28999
29000  /* if we already have a lock, it is exclusive.
29001  ** Just adjust level and punt on outta here. */
29002  if (pFile->eFileLock > NO_LOCK) {
29003    pFile->eFileLock = eFileLock;
29004    return SQLITE_OK;
29005  }
29006
29007  /* grab an exclusive lock */
29008
29009  if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
29010    int tErrno = errno;
29011    /* didn't get, must be busy */
29012    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
29013    if( IS_LOCK_ERROR(rc) ){
29014      storeLastErrno(pFile, tErrno);
29015    }
29016  } else {
29017    /* got it, set the type and return ok */
29018    pFile->eFileLock = eFileLock;
29019  }
29020  OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
29021           rc==SQLITE_OK ? "ok" : "failed"));
29022#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
29023  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
29024    rc = SQLITE_BUSY;
29025  }
29026#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
29027  return rc;
29028}
29029
29030
29031/*
29032** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
29033** must be either NO_LOCK or SHARED_LOCK.
29034**
29035** If the locking level of the file descriptor is already at or below
29036** the requested locking level, this routine is a no-op.
29037*/
29038static int flockUnlock(sqlite3_file *id, int eFileLock) {
29039  unixFile *pFile = (unixFile*)id;
29040
29041  assert( pFile );
29042  OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
29043           pFile->eFileLock, osGetpid(0)));
29044  assert( eFileLock<=SHARED_LOCK );
29045
29046  /* no-op if possible */
29047  if( pFile->eFileLock==eFileLock ){
29048    return SQLITE_OK;
29049  }
29050
29051  /* shared can just be set because we always have an exclusive */
29052  if (eFileLock==SHARED_LOCK) {
29053    pFile->eFileLock = eFileLock;
29054    return SQLITE_OK;
29055  }
29056
29057  /* no, really, unlock. */
29058  if( robust_flock(pFile->h, LOCK_UN) ){
29059#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
29060    return SQLITE_OK;
29061#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
29062    return SQLITE_IOERR_UNLOCK;
29063  }else{
29064    pFile->eFileLock = NO_LOCK;
29065    return SQLITE_OK;
29066  }
29067}
29068
29069/*
29070** Close a file.
29071*/
29072static int flockClose(sqlite3_file *id) {
29073  int rc = SQLITE_OK;
29074  if( id ){
29075    flockUnlock(id, NO_LOCK);
29076    rc = closeUnixFile(id);
29077  }
29078  return rc;
29079}
29080
29081#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
29082
29083/******************* End of the flock lock implementation *********************
29084******************************************************************************/
29085
29086/******************************************************************************
29087************************ Begin Named Semaphore Locking ************************
29088**
29089** Named semaphore locking is only supported on VxWorks.
29090**
29091** Semaphore locking is like dot-lock and flock in that it really only
29092** supports EXCLUSIVE locking.  Only a single process can read or write
29093** the database file at a time.  This reduces potential concurrency, but
29094** makes the lock implementation much easier.
29095*/
29096#if OS_VXWORKS
29097
29098/*
29099** This routine checks if there is a RESERVED lock held on the specified
29100** file by this or any other process. If such a lock is held, set *pResOut
29101** to a non-zero value otherwise *pResOut is set to zero.  The return value
29102** is set to SQLITE_OK unless an I/O error occurs during lock checking.
29103*/
29104static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
29105  int rc = SQLITE_OK;
29106  int reserved = 0;
29107  unixFile *pFile = (unixFile*)id;
29108
29109  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
29110
29111  assert( pFile );
29112
29113  /* Check if a thread in this process holds such a lock */
29114  if( pFile->eFileLock>SHARED_LOCK ){
29115    reserved = 1;
29116  }
29117
29118  /* Otherwise see if some other process holds it. */
29119  if( !reserved ){
29120    sem_t *pSem = pFile->pInode->pSem;
29121
29122    if( sem_trywait(pSem)==-1 ){
29123      int tErrno = errno;
29124      if( EAGAIN != tErrno ){
29125        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
29126        storeLastErrno(pFile, tErrno);
29127      } else {
29128        /* someone else has the lock when we are in NO_LOCK */
29129        reserved = (pFile->eFileLock < SHARED_LOCK);
29130      }
29131    }else{
29132      /* we could have it if we want it */
29133      sem_post(pSem);
29134    }
29135  }
29136  OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
29137
29138  *pResOut = reserved;
29139  return rc;
29140}
29141
29142/*
29143** Lock the file with the lock specified by parameter eFileLock - one
29144** of the following:
29145**
29146**     (1) SHARED_LOCK
29147**     (2) RESERVED_LOCK
29148**     (3) PENDING_LOCK
29149**     (4) EXCLUSIVE_LOCK
29150**
29151** Sometimes when requesting one lock state, additional lock states
29152** are inserted in between.  The locking might fail on one of the later
29153** transitions leaving the lock state different from what it started but
29154** still short of its goal.  The following chart shows the allowed
29155** transitions and the inserted intermediate states:
29156**
29157**    UNLOCKED -> SHARED
29158**    SHARED -> RESERVED
29159**    SHARED -> (PENDING) -> EXCLUSIVE
29160**    RESERVED -> (PENDING) -> EXCLUSIVE
29161**    PENDING -> EXCLUSIVE
29162**
29163** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
29164** lock states in the sqlite3_file structure, but all locks SHARED or
29165** above are really EXCLUSIVE locks and exclude all other processes from
29166** access the file.
29167**
29168** This routine will only increase a lock.  Use the sqlite3OsUnlock()
29169** routine to lower a locking level.
29170*/
29171static int semXLock(sqlite3_file *id, int eFileLock) {
29172  unixFile *pFile = (unixFile*)id;
29173  sem_t *pSem = pFile->pInode->pSem;
29174  int rc = SQLITE_OK;
29175
29176  /* if we already have a lock, it is exclusive.
29177  ** Just adjust level and punt on outta here. */
29178  if (pFile->eFileLock > NO_LOCK) {
29179    pFile->eFileLock = eFileLock;
29180    rc = SQLITE_OK;
29181    goto sem_end_lock;
29182  }
29183
29184  /* lock semaphore now but bail out when already locked. */
29185  if( sem_trywait(pSem)==-1 ){
29186    rc = SQLITE_BUSY;
29187    goto sem_end_lock;
29188  }
29189
29190  /* got it, set the type and return ok */
29191  pFile->eFileLock = eFileLock;
29192
29193 sem_end_lock:
29194  return rc;
29195}
29196
29197/*
29198** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
29199** must be either NO_LOCK or SHARED_LOCK.
29200**
29201** If the locking level of the file descriptor is already at or below
29202** the requested locking level, this routine is a no-op.
29203*/
29204static int semXUnlock(sqlite3_file *id, int eFileLock) {
29205  unixFile *pFile = (unixFile*)id;
29206  sem_t *pSem = pFile->pInode->pSem;
29207
29208  assert( pFile );
29209  assert( pSem );
29210  OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
29211           pFile->eFileLock, osGetpid(0)));
29212  assert( eFileLock<=SHARED_LOCK );
29213
29214  /* no-op if possible */
29215  if( pFile->eFileLock==eFileLock ){
29216    return SQLITE_OK;
29217  }
29218
29219  /* shared can just be set because we always have an exclusive */
29220  if (eFileLock==SHARED_LOCK) {
29221    pFile->eFileLock = eFileLock;
29222    return SQLITE_OK;
29223  }
29224
29225  /* no, really unlock. */
29226  if ( sem_post(pSem)==-1 ) {
29227    int rc, tErrno = errno;
29228    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
29229    if( IS_LOCK_ERROR(rc) ){
29230      storeLastErrno(pFile, tErrno);
29231    }
29232    return rc;
29233  }
29234  pFile->eFileLock = NO_LOCK;
29235  return SQLITE_OK;
29236}
29237
29238/*
29239 ** Close a file.
29240 */
29241static int semXClose(sqlite3_file *id) {
29242  if( id ){
29243    unixFile *pFile = (unixFile*)id;
29244    semXUnlock(id, NO_LOCK);
29245    assert( pFile );
29246    unixEnterMutex();
29247    releaseInodeInfo(pFile);
29248    unixLeaveMutex();
29249    closeUnixFile(id);
29250  }
29251  return SQLITE_OK;
29252}
29253
29254#endif /* OS_VXWORKS */
29255/*
29256** Named semaphore locking is only available on VxWorks.
29257**
29258*************** End of the named semaphore lock implementation ****************
29259******************************************************************************/
29260
29261
29262/******************************************************************************
29263*************************** Begin AFP Locking *********************************
29264**
29265** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
29266** on Apple Macintosh computers - both OS9 and OSX.
29267**
29268** Third-party implementations of AFP are available.  But this code here
29269** only works on OSX.
29270*/
29271
29272#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29273/*
29274** The afpLockingContext structure contains all afp lock specific state
29275*/
29276typedef struct afpLockingContext afpLockingContext;
29277struct afpLockingContext {
29278  int reserved;
29279  const char *dbPath;             /* Name of the open file */
29280};
29281
29282struct ByteRangeLockPB2
29283{
29284  unsigned long long offset;        /* offset to first byte to lock */
29285  unsigned long long length;        /* nbr of bytes to lock */
29286  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
29287  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
29288  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
29289  int fd;                           /* file desc to assoc this lock with */
29290};
29291
29292#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
29293
29294/*
29295** This is a utility for setting or clearing a bit-range lock on an
29296** AFP filesystem.
29297**
29298** Return SQLITE_OK on success, SQLITE_BUSY on failure.
29299*/
29300static int afpSetLock(
29301  const char *path,              /* Name of the file to be locked or unlocked */
29302  unixFile *pFile,               /* Open file descriptor on path */
29303  unsigned long long offset,     /* First byte to be locked */
29304  unsigned long long length,     /* Number of bytes to lock */
29305  int setLockFlag                /* True to set lock.  False to clear lock */
29306){
29307  struct ByteRangeLockPB2 pb;
29308  int err;
29309
29310  pb.unLockFlag = setLockFlag ? 0 : 1;
29311  pb.startEndFlag = 0;
29312  pb.offset = offset;
29313  pb.length = length;
29314  pb.fd = pFile->h;
29315
29316  OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
29317    (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
29318    offset, length));
29319  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
29320  if ( err==-1 ) {
29321    int rc;
29322    int tErrno = errno;
29323    OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
29324             path, tErrno, strerror(tErrno)));
29325#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
29326    rc = SQLITE_BUSY;
29327#else
29328    rc = sqliteErrorFromPosixError(tErrno,
29329                    setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
29330#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
29331    if( IS_LOCK_ERROR(rc) ){
29332      storeLastErrno(pFile, tErrno);
29333    }
29334    return rc;
29335  } else {
29336    return SQLITE_OK;
29337  }
29338}
29339
29340/*
29341** This routine checks if there is a RESERVED lock held on the specified
29342** file by this or any other process. If such a lock is held, set *pResOut
29343** to a non-zero value otherwise *pResOut is set to zero.  The return value
29344** is set to SQLITE_OK unless an I/O error occurs during lock checking.
29345*/
29346static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
29347  int rc = SQLITE_OK;
29348  int reserved = 0;
29349  unixFile *pFile = (unixFile*)id;
29350  afpLockingContext *context;
29351
29352  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
29353
29354  assert( pFile );
29355  context = (afpLockingContext *) pFile->lockingContext;
29356  if( context->reserved ){
29357    *pResOut = 1;
29358    return SQLITE_OK;
29359  }
29360  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
29361
29362  /* Check if a thread in this process holds such a lock */
29363  if( pFile->pInode->eFileLock>SHARED_LOCK ){
29364    reserved = 1;
29365  }
29366
29367  /* Otherwise see if some other process holds it.
29368   */
29369  if( !reserved ){
29370    /* lock the RESERVED byte */
29371    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
29372    if( SQLITE_OK==lrc ){
29373      /* if we succeeded in taking the reserved lock, unlock it to restore
29374      ** the original state */
29375      lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
29376    } else {
29377      /* if we failed to get the lock then someone else must have it */
29378      reserved = 1;
29379    }
29380    if( IS_LOCK_ERROR(lrc) ){
29381      rc=lrc;
29382    }
29383  }
29384
29385  unixLeaveMutex();
29386  OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
29387
29388  *pResOut = reserved;
29389  return rc;
29390}
29391
29392/*
29393** Lock the file with the lock specified by parameter eFileLock - one
29394** of the following:
29395**
29396**     (1) SHARED_LOCK
29397**     (2) RESERVED_LOCK
29398**     (3) PENDING_LOCK
29399**     (4) EXCLUSIVE_LOCK
29400**
29401** Sometimes when requesting one lock state, additional lock states
29402** are inserted in between.  The locking might fail on one of the later
29403** transitions leaving the lock state different from what it started but
29404** still short of its goal.  The following chart shows the allowed
29405** transitions and the inserted intermediate states:
29406**
29407**    UNLOCKED -> SHARED
29408**    SHARED -> RESERVED
29409**    SHARED -> (PENDING) -> EXCLUSIVE
29410**    RESERVED -> (PENDING) -> EXCLUSIVE
29411**    PENDING -> EXCLUSIVE
29412**
29413** This routine will only increase a lock.  Use the sqlite3OsUnlock()
29414** routine to lower a locking level.
29415*/
29416static int afpLock(sqlite3_file *id, int eFileLock){
29417  int rc = SQLITE_OK;
29418  unixFile *pFile = (unixFile*)id;
29419  unixInodeInfo *pInode = pFile->pInode;
29420  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
29421
29422  assert( pFile );
29423  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
29424           azFileLock(eFileLock), azFileLock(pFile->eFileLock),
29425           azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
29426
29427  /* If there is already a lock of this type or more restrictive on the
29428  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
29429  ** unixEnterMutex() hasn't been called yet.
29430  */
29431  if( pFile->eFileLock>=eFileLock ){
29432    OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
29433           azFileLock(eFileLock)));
29434    return SQLITE_OK;
29435  }
29436
29437  /* Make sure the locking sequence is correct
29438  **  (1) We never move from unlocked to anything higher than shared lock.
29439  **  (2) SQLite never explicitly requests a pendig lock.
29440  **  (3) A shared lock is always held when a reserve lock is requested.
29441  */
29442  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
29443  assert( eFileLock!=PENDING_LOCK );
29444  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
29445
29446  /* This mutex is needed because pFile->pInode is shared across threads
29447  */
29448  unixEnterMutex();
29449  pInode = pFile->pInode;
29450
29451  /* If some thread using this PID has a lock via a different unixFile*
29452  ** handle that precludes the requested lock, return BUSY.
29453  */
29454  if( (pFile->eFileLock!=pInode->eFileLock &&
29455       (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
29456     ){
29457    rc = SQLITE_BUSY;
29458    goto afp_end_lock;
29459  }
29460
29461  /* If a SHARED lock is requested, and some thread using this PID already
29462  ** has a SHARED or RESERVED lock, then increment reference counts and
29463  ** return SQLITE_OK.
29464  */
29465  if( eFileLock==SHARED_LOCK &&
29466     (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
29467    assert( eFileLock==SHARED_LOCK );
29468    assert( pFile->eFileLock==0 );
29469    assert( pInode->nShared>0 );
29470    pFile->eFileLock = SHARED_LOCK;
29471    pInode->nShared++;
29472    pInode->nLock++;
29473    goto afp_end_lock;
29474  }
29475
29476  /* A PENDING lock is needed before acquiring a SHARED lock and before
29477  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
29478  ** be released.
29479  */
29480  if( eFileLock==SHARED_LOCK
29481      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
29482  ){
29483    int failed;
29484    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
29485    if (failed) {
29486      rc = failed;
29487      goto afp_end_lock;
29488    }
29489  }
29490
29491  /* If control gets to this point, then actually go ahead and make
29492  ** operating system calls for the specified lock.
29493  */
29494  if( eFileLock==SHARED_LOCK ){
29495    int lrc1, lrc2, lrc1Errno = 0;
29496    long lk, mask;
29497
29498    assert( pInode->nShared==0 );
29499    assert( pInode->eFileLock==0 );
29500
29501    mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
29502    /* Now get the read-lock SHARED_LOCK */
29503    /* note that the quality of the randomness doesn't matter that much */
29504    lk = random();
29505    pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
29506    lrc1 = afpSetLock(context->dbPath, pFile,
29507          SHARED_FIRST+pInode->sharedByte, 1, 1);
29508    if( IS_LOCK_ERROR(lrc1) ){
29509      lrc1Errno = pFile->lastErrno;
29510    }
29511    /* Drop the temporary PENDING lock */
29512    lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
29513
29514    if( IS_LOCK_ERROR(lrc1) ) {
29515      storeLastErrno(pFile, lrc1Errno);
29516      rc = lrc1;
29517      goto afp_end_lock;
29518    } else if( IS_LOCK_ERROR(lrc2) ){
29519      rc = lrc2;
29520      goto afp_end_lock;
29521    } else if( lrc1 != SQLITE_OK ) {
29522      rc = lrc1;
29523    } else {
29524      pFile->eFileLock = SHARED_LOCK;
29525      pInode->nLock++;
29526      pInode->nShared = 1;
29527    }
29528  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
29529    /* We are trying for an exclusive lock but another thread in this
29530     ** same process is still holding a shared lock. */
29531    rc = SQLITE_BUSY;
29532  }else{
29533    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
29534    ** assumed that there is a SHARED or greater lock on the file
29535    ** already.
29536    */
29537    int failed = 0;
29538    assert( 0!=pFile->eFileLock );
29539    if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
29540        /* Acquire a RESERVED lock */
29541        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
29542      if( !failed ){
29543        context->reserved = 1;
29544      }
29545    }
29546    if (!failed && eFileLock == EXCLUSIVE_LOCK) {
29547      /* Acquire an EXCLUSIVE lock */
29548
29549      /* Remove the shared lock before trying the range.  we'll need to
29550      ** reestablish the shared lock if we can't get the  afpUnlock
29551      */
29552      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
29553                         pInode->sharedByte, 1, 0)) ){
29554        int failed2 = SQLITE_OK;
29555        /* now attemmpt to get the exclusive lock range */
29556        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
29557                               SHARED_SIZE, 1);
29558        if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
29559                       SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
29560          /* Can't reestablish the shared lock.  Sqlite can't deal, this is
29561          ** a critical I/O error
29562          */
29563          rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
29564               SQLITE_IOERR_LOCK;
29565          goto afp_end_lock;
29566        }
29567      }else{
29568        rc = failed;
29569      }
29570    }
29571    if( failed ){
29572      rc = failed;
29573    }
29574  }
29575
29576  if( rc==SQLITE_OK ){
29577    pFile->eFileLock = eFileLock;
29578    pInode->eFileLock = eFileLock;
29579  }else if( eFileLock==EXCLUSIVE_LOCK ){
29580    pFile->eFileLock = PENDING_LOCK;
29581    pInode->eFileLock = PENDING_LOCK;
29582  }
29583
29584afp_end_lock:
29585  unixLeaveMutex();
29586  OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
29587         rc==SQLITE_OK ? "ok" : "failed"));
29588  return rc;
29589}
29590
29591/*
29592** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
29593** must be either NO_LOCK or SHARED_LOCK.
29594**
29595** If the locking level of the file descriptor is already at or below
29596** the requested locking level, this routine is a no-op.
29597*/
29598static int afpUnlock(sqlite3_file *id, int eFileLock) {
29599  int rc = SQLITE_OK;
29600  unixFile *pFile = (unixFile*)id;
29601  unixInodeInfo *pInode;
29602  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
29603  int skipShared = 0;
29604#ifdef SQLITE_TEST
29605  int h = pFile->h;
29606#endif
29607
29608  assert( pFile );
29609  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
29610           pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
29611           osGetpid(0)));
29612
29613  assert( eFileLock<=SHARED_LOCK );
29614  if( pFile->eFileLock<=eFileLock ){
29615    return SQLITE_OK;
29616  }
29617  unixEnterMutex();
29618  pInode = pFile->pInode;
29619  assert( pInode->nShared!=0 );
29620  if( pFile->eFileLock>SHARED_LOCK ){
29621    assert( pInode->eFileLock==pFile->eFileLock );
29622    SimulateIOErrorBenign(1);
29623    SimulateIOError( h=(-1) )
29624    SimulateIOErrorBenign(0);
29625
29626#ifdef SQLITE_DEBUG
29627    /* When reducing a lock such that other processes can start
29628    ** reading the database file again, make sure that the
29629    ** transaction counter was updated if any part of the database
29630    ** file changed.  If the transaction counter is not updated,
29631    ** other connections to the same file might not realize that
29632    ** the file has changed and hence might not know to flush their
29633    ** cache.  The use of a stale cache can lead to database corruption.
29634    */
29635    assert( pFile->inNormalWrite==0
29636           || pFile->dbUpdate==0
29637           || pFile->transCntrChng==1 );
29638    pFile->inNormalWrite = 0;
29639#endif
29640
29641    if( pFile->eFileLock==EXCLUSIVE_LOCK ){
29642      rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
29643      if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
29644        /* only re-establish the shared lock if necessary */
29645        int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
29646        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
29647      } else {
29648        skipShared = 1;
29649      }
29650    }
29651    if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
29652      rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
29653    }
29654    if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
29655      rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
29656      if( !rc ){
29657        context->reserved = 0;
29658      }
29659    }
29660    if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
29661      pInode->eFileLock = SHARED_LOCK;
29662    }
29663  }
29664  if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
29665
29666    /* Decrement the shared lock counter.  Release the lock using an
29667    ** OS call only when all threads in this same process have released
29668    ** the lock.
29669    */
29670    unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
29671    pInode->nShared--;
29672    if( pInode->nShared==0 ){
29673      SimulateIOErrorBenign(1);
29674      SimulateIOError( h=(-1) )
29675      SimulateIOErrorBenign(0);
29676      if( !skipShared ){
29677        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
29678      }
29679      if( !rc ){
29680        pInode->eFileLock = NO_LOCK;
29681        pFile->eFileLock = NO_LOCK;
29682      }
29683    }
29684    if( rc==SQLITE_OK ){
29685      pInode->nLock--;
29686      assert( pInode->nLock>=0 );
29687      if( pInode->nLock==0 ){
29688        closePendingFds(pFile);
29689      }
29690    }
29691  }
29692
29693  unixLeaveMutex();
29694  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
29695  return rc;
29696}
29697
29698/*
29699** Close a file & cleanup AFP specific locking context
29700*/
29701static int afpClose(sqlite3_file *id) {
29702  int rc = SQLITE_OK;
29703  if( id ){
29704    unixFile *pFile = (unixFile*)id;
29705    afpUnlock(id, NO_LOCK);
29706    unixEnterMutex();
29707    if( pFile->pInode && pFile->pInode->nLock ){
29708      /* If there are outstanding locks, do not actually close the file just
29709      ** yet because that would clear those locks.  Instead, add the file
29710      ** descriptor to pInode->aPending.  It will be automatically closed when
29711      ** the last lock is cleared.
29712      */
29713      setPendingFd(pFile);
29714    }
29715    releaseInodeInfo(pFile);
29716    sqlite3_free(pFile->lockingContext);
29717    rc = closeUnixFile(id);
29718    unixLeaveMutex();
29719  }
29720  return rc;
29721}
29722
29723#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
29724/*
29725** The code above is the AFP lock implementation.  The code is specific
29726** to MacOSX and does not work on other unix platforms.  No alternative
29727** is available.  If you don't compile for a mac, then the "unix-afp"
29728** VFS is not available.
29729**
29730********************* End of the AFP lock implementation **********************
29731******************************************************************************/
29732
29733/******************************************************************************
29734*************************** Begin NFS Locking ********************************/
29735
29736#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29737/*
29738 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
29739 ** must be either NO_LOCK or SHARED_LOCK.
29740 **
29741 ** If the locking level of the file descriptor is already at or below
29742 ** the requested locking level, this routine is a no-op.
29743 */
29744static int nfsUnlock(sqlite3_file *id, int eFileLock){
29745  return posixUnlock(id, eFileLock, 1);
29746}
29747
29748#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
29749/*
29750** The code above is the NFS lock implementation.  The code is specific
29751** to MacOSX and does not work on other unix platforms.  No alternative
29752** is available.
29753**
29754********************* End of the NFS lock implementation **********************
29755******************************************************************************/
29756
29757/******************************************************************************
29758**************** Non-locking sqlite3_file methods *****************************
29759**
29760** The next division contains implementations for all methods of the
29761** sqlite3_file object other than the locking methods.  The locking
29762** methods were defined in divisions above (one locking method per
29763** division).  Those methods that are common to all locking modes
29764** are gather together into this division.
29765*/
29766
29767/*
29768** Seek to the offset passed as the second argument, then read cnt
29769** bytes into pBuf. Return the number of bytes actually read.
29770**
29771** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
29772** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
29773** one system to another.  Since SQLite does not define USE_PREAD
29774** in any form by default, we will not attempt to define _XOPEN_SOURCE.
29775** See tickets #2741 and #2681.
29776**
29777** To avoid stomping the errno value on a failed read the lastErrno value
29778** is set before returning.
29779*/
29780static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
29781  int got;
29782  int prior = 0;
29783#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
29784  i64 newOffset;
29785#endif
29786  TIMER_START;
29787  assert( cnt==(cnt&0x1ffff) );
29788  assert( id->h>2 );
29789  do{
29790#if defined(USE_PREAD)
29791    got = osPread(id->h, pBuf, cnt, offset);
29792    SimulateIOError( got = -1 );
29793#elif defined(USE_PREAD64)
29794    got = osPread64(id->h, pBuf, cnt, offset);
29795    SimulateIOError( got = -1 );
29796#else
29797    newOffset = lseek(id->h, offset, SEEK_SET);
29798    SimulateIOError( newOffset-- );
29799    if( newOffset!=offset ){
29800      if( newOffset == -1 ){
29801        storeLastErrno((unixFile*)id, errno);
29802      }else{
29803        storeLastErrno((unixFile*)id, 0);
29804      }
29805      return -1;
29806    }
29807    got = osRead(id->h, pBuf, cnt);
29808#endif
29809    if( got==cnt ) break;
29810    if( got<0 ){
29811      if( errno==EINTR ){ got = 1; continue; }
29812      prior = 0;
29813      storeLastErrno((unixFile*)id,  errno);
29814      break;
29815    }else if( got>0 ){
29816      cnt -= got;
29817      offset += got;
29818      prior += got;
29819      pBuf = (void*)(got + (char*)pBuf);
29820    }
29821  }while( got>0 );
29822  TIMER_END;
29823  OSTRACE(("READ    %-3d %5d %7lld %llu\n",
29824            id->h, got+prior, offset-prior, TIMER_ELAPSED));
29825  return got+prior;
29826}
29827
29828/*
29829** Read data from a file into a buffer.  Return SQLITE_OK if all
29830** bytes were read successfully and SQLITE_IOERR if anything goes
29831** wrong.
29832*/
29833static int unixRead(
29834  sqlite3_file *id,
29835  void *pBuf,
29836  int amt,
29837  sqlite3_int64 offset
29838){
29839  unixFile *pFile = (unixFile *)id;
29840  int got;
29841  assert( id );
29842  assert( offset>=0 );
29843  assert( amt>0 );
29844
29845  /* If this is a database file (not a journal, master-journal or temp
29846  ** file), the bytes in the locking range should never be read or written. */
29847#if 0
29848  assert( pFile->pUnused==0
29849       || offset>=PENDING_BYTE+512
29850       || offset+amt<=PENDING_BYTE
29851  );
29852#endif
29853
29854#if SQLITE_MAX_MMAP_SIZE>0
29855  /* Deal with as much of this read request as possible by transfering
29856  ** data from the memory mapping using memcpy().  */
29857  if( offset<pFile->mmapSize ){
29858    if( offset+amt <= pFile->mmapSize ){
29859      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
29860      return SQLITE_OK;
29861    }else{
29862      int nCopy = pFile->mmapSize - offset;
29863      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
29864      pBuf = &((u8 *)pBuf)[nCopy];
29865      amt -= nCopy;
29866      offset += nCopy;
29867    }
29868  }
29869#endif
29870
29871  got = seekAndRead(pFile, offset, pBuf, amt);
29872  if( got==amt ){
29873    return SQLITE_OK;
29874  }else if( got<0 ){
29875    /* lastErrno set by seekAndRead */
29876    return SQLITE_IOERR_READ;
29877  }else{
29878    storeLastErrno(pFile, 0);   /* not a system error */
29879    /* Unread parts of the buffer must be zero-filled */
29880    memset(&((char*)pBuf)[got], 0, amt-got);
29881    return SQLITE_IOERR_SHORT_READ;
29882  }
29883}
29884
29885/*
29886** Attempt to seek the file-descriptor passed as the first argument to
29887** absolute offset iOff, then attempt to write nBuf bytes of data from
29888** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
29889** return the actual number of bytes written (which may be less than
29890** nBuf).
29891*/
29892static int seekAndWriteFd(
29893  int fd,                         /* File descriptor to write to */
29894  i64 iOff,                       /* File offset to begin writing at */
29895  const void *pBuf,               /* Copy data from this buffer to the file */
29896  int nBuf,                       /* Size of buffer pBuf in bytes */
29897  int *piErrno                    /* OUT: Error number if error occurs */
29898){
29899  int rc = 0;                     /* Value returned by system call */
29900
29901  assert( nBuf==(nBuf&0x1ffff) );
29902  assert( fd>2 );
29903  nBuf &= 0x1ffff;
29904  TIMER_START;
29905
29906#if defined(USE_PREAD)
29907  do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
29908#elif defined(USE_PREAD64)
29909  do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
29910#else
29911  do{
29912    i64 iSeek = lseek(fd, iOff, SEEK_SET);
29913    SimulateIOError( iSeek-- );
29914
29915    if( iSeek!=iOff ){
29916      if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
29917      return -1;
29918    }
29919    rc = osWrite(fd, pBuf, nBuf);
29920  }while( rc<0 && errno==EINTR );
29921#endif
29922
29923  TIMER_END;
29924  OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
29925
29926  if( rc<0 && piErrno ) *piErrno = errno;
29927  return rc;
29928}
29929
29930
29931/*
29932** Seek to the offset in id->offset then read cnt bytes into pBuf.
29933** Return the number of bytes actually read.  Update the offset.
29934**
29935** To avoid stomping the errno value on a failed write the lastErrno value
29936** is set before returning.
29937*/
29938static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
29939  return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
29940}
29941
29942
29943/*
29944** Write data from a buffer into a file.  Return SQLITE_OK on success
29945** or some other error code on failure.
29946*/
29947static int unixWrite(
29948  sqlite3_file *id,
29949  const void *pBuf,
29950  int amt,
29951  sqlite3_int64 offset
29952){
29953  unixFile *pFile = (unixFile*)id;
29954  int wrote = 0;
29955  assert( id );
29956  assert( amt>0 );
29957
29958  /* If this is a database file (not a journal, master-journal or temp
29959  ** file), the bytes in the locking range should never be read or written. */
29960#if 0
29961  assert( pFile->pUnused==0
29962       || offset>=PENDING_BYTE+512
29963       || offset+amt<=PENDING_BYTE
29964  );
29965#endif
29966
29967#ifdef SQLITE_DEBUG
29968  /* If we are doing a normal write to a database file (as opposed to
29969  ** doing a hot-journal rollback or a write to some file other than a
29970  ** normal database file) then record the fact that the database
29971  ** has changed.  If the transaction counter is modified, record that
29972  ** fact too.
29973  */
29974  if( pFile->inNormalWrite ){
29975    pFile->dbUpdate = 1;  /* The database has been modified */
29976    if( offset<=24 && offset+amt>=27 ){
29977      int rc;
29978      char oldCntr[4];
29979      SimulateIOErrorBenign(1);
29980      rc = seekAndRead(pFile, 24, oldCntr, 4);
29981      SimulateIOErrorBenign(0);
29982      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
29983        pFile->transCntrChng = 1;  /* The transaction counter has changed */
29984      }
29985    }
29986  }
29987#endif
29988
29989#if SQLITE_MAX_MMAP_SIZE>0
29990  /* Deal with as much of this write request as possible by transfering
29991  ** data from the memory mapping using memcpy().  */
29992  if( offset<pFile->mmapSize ){
29993    if( offset+amt <= pFile->mmapSize ){
29994      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
29995      return SQLITE_OK;
29996    }else{
29997      int nCopy = pFile->mmapSize - offset;
29998      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
29999      pBuf = &((u8 *)pBuf)[nCopy];
30000      amt -= nCopy;
30001      offset += nCopy;
30002    }
30003  }
30004#endif
30005
30006  while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
30007    amt -= wrote;
30008    offset += wrote;
30009    pBuf = &((char*)pBuf)[wrote];
30010  }
30011  SimulateIOError(( wrote=(-1), amt=1 ));
30012  SimulateDiskfullError(( wrote=0, amt=1 ));
30013
30014  if( amt>wrote ){
30015    if( wrote<0 && pFile->lastErrno!=ENOSPC ){
30016      /* lastErrno set by seekAndWrite */
30017      return SQLITE_IOERR_WRITE;
30018    }else{
30019      storeLastErrno(pFile, 0); /* not a system error */
30020      return SQLITE_FULL;
30021    }
30022  }
30023
30024  return SQLITE_OK;
30025}
30026
30027#ifdef SQLITE_TEST
30028/*
30029** Count the number of fullsyncs and normal syncs.  This is used to test
30030** that syncs and fullsyncs are occurring at the right times.
30031*/
30032SQLITE_API int sqlite3_sync_count = 0;
30033SQLITE_API int sqlite3_fullsync_count = 0;
30034#endif
30035
30036/*
30037** We do not trust systems to provide a working fdatasync().  Some do.
30038** Others do no.  To be safe, we will stick with the (slightly slower)
30039** fsync(). If you know that your system does support fdatasync() correctly,
30040** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
30041*/
30042#if !defined(fdatasync) && !HAVE_FDATASYNC
30043# define fdatasync fsync
30044#endif
30045
30046/*
30047** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
30048** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
30049** only available on Mac OS X.  But that could change.
30050*/
30051#ifdef F_FULLFSYNC
30052# define HAVE_FULLFSYNC 1
30053#else
30054# define HAVE_FULLFSYNC 0
30055#endif
30056
30057
30058/*
30059** The fsync() system call does not work as advertised on many
30060** unix systems.  The following procedure is an attempt to make
30061** it work better.
30062**
30063** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
30064** for testing when we want to run through the test suite quickly.
30065** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
30066** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
30067** or power failure will likely corrupt the database file.
30068**
30069** SQLite sets the dataOnly flag if the size of the file is unchanged.
30070** The idea behind dataOnly is that it should only write the file content
30071** to disk, not the inode.  We only set dataOnly if the file size is
30072** unchanged since the file size is part of the inode.  However,
30073** Ted Ts'o tells us that fdatasync() will also write the inode if the
30074** file size has changed.  The only real difference between fdatasync()
30075** and fsync(), Ted tells us, is that fdatasync() will not flush the
30076** inode if the mtime or owner or other inode attributes have changed.
30077** We only care about the file size, not the other file attributes, so
30078** as far as SQLite is concerned, an fdatasync() is always adequate.
30079** So, we always use fdatasync() if it is available, regardless of
30080** the value of the dataOnly flag.
30081*/
30082static int full_fsync(int fd, int fullSync, int dataOnly){
30083  int rc;
30084
30085  /* The following "ifdef/elif/else/" block has the same structure as
30086  ** the one below. It is replicated here solely to avoid cluttering
30087  ** up the real code with the UNUSED_PARAMETER() macros.
30088  */
30089#ifdef SQLITE_NO_SYNC
30090  UNUSED_PARAMETER(fd);
30091  UNUSED_PARAMETER(fullSync);
30092  UNUSED_PARAMETER(dataOnly);
30093#elif HAVE_FULLFSYNC
30094  UNUSED_PARAMETER(dataOnly);
30095#else
30096  UNUSED_PARAMETER(fullSync);
30097  UNUSED_PARAMETER(dataOnly);
30098#endif
30099
30100  /* Record the number of times that we do a normal fsync() and
30101  ** FULLSYNC.  This is used during testing to verify that this procedure
30102  ** gets called with the correct arguments.
30103  */
30104#ifdef SQLITE_TEST
30105  if( fullSync ) sqlite3_fullsync_count++;
30106  sqlite3_sync_count++;
30107#endif
30108
30109  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
30110  ** no-op
30111  */
30112#ifdef SQLITE_NO_SYNC
30113  rc = SQLITE_OK;
30114#elif HAVE_FULLFSYNC
30115  if( fullSync ){
30116    rc = osFcntl(fd, F_FULLFSYNC, 0);
30117  }else{
30118    rc = 1;
30119  }
30120  /* If the FULLFSYNC failed, fall back to attempting an fsync().
30121  ** It shouldn't be possible for fullfsync to fail on the local
30122  ** file system (on OSX), so failure indicates that FULLFSYNC
30123  ** isn't supported for this file system. So, attempt an fsync
30124  ** and (for now) ignore the overhead of a superfluous fcntl call.
30125  ** It'd be better to detect fullfsync support once and avoid
30126  ** the fcntl call every time sync is called.
30127  */
30128  if( rc ) rc = fsync(fd);
30129
30130#elif defined(__APPLE__)
30131  /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
30132  ** so currently we default to the macro that redefines fdatasync to fsync
30133  */
30134  rc = fsync(fd);
30135#else
30136  rc = fdatasync(fd);
30137#if OS_VXWORKS
30138  if( rc==-1 && errno==ENOTSUP ){
30139    rc = fsync(fd);
30140  }
30141#endif /* OS_VXWORKS */
30142#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
30143
30144  if( OS_VXWORKS && rc!= -1 ){
30145    rc = 0;
30146  }
30147  return rc;
30148}
30149
30150/*
30151** Open a file descriptor to the directory containing file zFilename.
30152** If successful, *pFd is set to the opened file descriptor and
30153** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
30154** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
30155** value.
30156**
30157** The directory file descriptor is used for only one thing - to
30158** fsync() a directory to make sure file creation and deletion events
30159** are flushed to disk.  Such fsyncs are not needed on newer
30160** journaling filesystems, but are required on older filesystems.
30161**
30162** This routine can be overridden using the xSetSysCall interface.
30163** The ability to override this routine was added in support of the
30164** chromium sandbox.  Opening a directory is a security risk (we are
30165** told) so making it overrideable allows the chromium sandbox to
30166** replace this routine with a harmless no-op.  To make this routine
30167** a no-op, replace it with a stub that returns SQLITE_OK but leaves
30168** *pFd set to a negative number.
30169**
30170** If SQLITE_OK is returned, the caller is responsible for closing
30171** the file descriptor *pFd using close().
30172*/
30173static int openDirectory(const char *zFilename, int *pFd){
30174  int ii;
30175  int fd = -1;
30176  char zDirname[MAX_PATHNAME+1];
30177
30178  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
30179  for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
30180  if( ii>0 ){
30181    zDirname[ii] = '\0';
30182    fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
30183    if( fd>=0 ){
30184      OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
30185    }
30186  }
30187  *pFd = fd;
30188  return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
30189}
30190
30191/*
30192** Make sure all writes to a particular file are committed to disk.
30193**
30194** If dataOnly==0 then both the file itself and its metadata (file
30195** size, access time, etc) are synced.  If dataOnly!=0 then only the
30196** file data is synced.
30197**
30198** Under Unix, also make sure that the directory entry for the file
30199** has been created by fsync-ing the directory that contains the file.
30200** If we do not do this and we encounter a power failure, the directory
30201** entry for the journal might not exist after we reboot.  The next
30202** SQLite to access the file will not know that the journal exists (because
30203** the directory entry for the journal was never created) and the transaction
30204** will not roll back - possibly leading to database corruption.
30205*/
30206static int unixSync(sqlite3_file *id, int flags){
30207  int rc;
30208  unixFile *pFile = (unixFile*)id;
30209
30210  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
30211  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
30212
30213  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
30214  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
30215      || (flags&0x0F)==SQLITE_SYNC_FULL
30216  );
30217
30218  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
30219  ** line is to test that doing so does not cause any problems.
30220  */
30221  SimulateDiskfullError( return SQLITE_FULL );
30222
30223  assert( pFile );
30224  OSTRACE(("SYNC    %-3d\n", pFile->h));
30225  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
30226  SimulateIOError( rc=1 );
30227  if( rc ){
30228    storeLastErrno(pFile, errno);
30229    return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
30230  }
30231
30232  /* Also fsync the directory containing the file if the DIRSYNC flag
30233  ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
30234  ** are unable to fsync a directory, so ignore errors on the fsync.
30235  */
30236  if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
30237    int dirfd;
30238    OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
30239            HAVE_FULLFSYNC, isFullsync));
30240    rc = osOpenDirectory(pFile->zPath, &dirfd);
30241    if( rc==SQLITE_OK && dirfd>=0 ){
30242      full_fsync(dirfd, 0, 0);
30243      robust_close(pFile, dirfd, __LINE__);
30244    }else if( rc==SQLITE_CANTOPEN ){
30245      rc = SQLITE_OK;
30246    }
30247    pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
30248  }
30249  return rc;
30250}
30251
30252/*
30253** Truncate an open file to a specified size
30254*/
30255static int unixTruncate(sqlite3_file *id, i64 nByte){
30256  unixFile *pFile = (unixFile *)id;
30257  int rc;
30258  assert( pFile );
30259  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
30260
30261  /* If the user has configured a chunk-size for this file, truncate the
30262  ** file so that it consists of an integer number of chunks (i.e. the
30263  ** actual file size after the operation may be larger than the requested
30264  ** size).
30265  */
30266  if( pFile->szChunk>0 ){
30267    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
30268  }
30269
30270  rc = robust_ftruncate(pFile->h, nByte);
30271  if( rc ){
30272    storeLastErrno(pFile, errno);
30273    return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
30274  }else{
30275#ifdef SQLITE_DEBUG
30276    /* If we are doing a normal write to a database file (as opposed to
30277    ** doing a hot-journal rollback or a write to some file other than a
30278    ** normal database file) and we truncate the file to zero length,
30279    ** that effectively updates the change counter.  This might happen
30280    ** when restoring a database using the backup API from a zero-length
30281    ** source.
30282    */
30283    if( pFile->inNormalWrite && nByte==0 ){
30284      pFile->transCntrChng = 1;
30285    }
30286#endif
30287
30288#if SQLITE_MAX_MMAP_SIZE>0
30289    /* If the file was just truncated to a size smaller than the currently
30290    ** mapped region, reduce the effective mapping size as well. SQLite will
30291    ** use read() and write() to access data beyond this point from now on.
30292    */
30293    if( nByte<pFile->mmapSize ){
30294      pFile->mmapSize = nByte;
30295    }
30296#endif
30297
30298    return SQLITE_OK;
30299  }
30300}
30301
30302/*
30303** Determine the current size of a file in bytes
30304*/
30305static int unixFileSize(sqlite3_file *id, i64 *pSize){
30306  int rc;
30307  struct stat buf;
30308  assert( id );
30309  rc = osFstat(((unixFile*)id)->h, &buf);
30310  SimulateIOError( rc=1 );
30311  if( rc!=0 ){
30312    storeLastErrno((unixFile*)id, errno);
30313    return unixLogError(SQLITE_IOERR_FSTAT, "fstat", ((unixFile*)id)->zPath);
30314  }
30315  *pSize = buf.st_size;
30316
30317  /* When opening a zero-size database, the findInodeInfo() procedure
30318  ** writes a single byte into that file in order to work around a bug
30319  ** in the OS-X msdos filesystem.  In order to avoid problems with upper
30320  ** layers, we need to report this file size as zero even though it is
30321  ** really 1.   Ticket #3260.
30322  */
30323  if( *pSize==1 ) *pSize = 0;
30324
30325
30326  return SQLITE_OK;
30327}
30328
30329#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30330/*
30331** Handler for proxy-locking file-control verbs.  Defined below in the
30332** proxying locking division.
30333*/
30334static int proxyFileControl(sqlite3_file*,int,void*);
30335#endif
30336
30337/*
30338** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
30339** file-control operation.  Enlarge the database to nBytes in size
30340** (rounded up to the next chunk-size).  If the database is already
30341** nBytes or larger, this routine is a no-op.
30342*/
30343static int fcntlSizeHint(unixFile *pFile, i64 nByte){
30344  if( pFile->szChunk>0 ){
30345    i64 nSize;                    /* Required file size */
30346    struct stat buf;              /* Used to hold return values of fstat() */
30347
30348    if( osFstat(pFile->h, &buf) ){
30349      return unixLogError(SQLITE_IOERR_FSTAT, "fstat", pFile->zPath);
30350    }
30351
30352    nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
30353    if( nSize>(i64)buf.st_size ){
30354
30355#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
30356      /* The code below is handling the return value of osFallocate()
30357      ** correctly. posix_fallocate() is defined to "returns zero on success,
30358      ** or an error number on  failure". See the manpage for details. */
30359      int err;
30360      do{
30361        err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
30362      }while( err==EINTR );
30363      if( err ) return SQLITE_IOERR_WRITE;
30364#else
30365      /* If the OS does not have posix_fallocate(), fake it. Write a
30366      ** single byte to the last byte in each block that falls entirely
30367      ** within the extended region. Then, if required, a single byte
30368      ** at offset (nSize-1), to set the size of the file correctly.
30369      ** This is a similar technique to that used by glibc on systems
30370      ** that do not have a real fallocate() call.
30371      */
30372      int nBlk = buf.st_blksize;  /* File-system block size */
30373      int nWrite = 0;             /* Number of bytes written by seekAndWrite */
30374      i64 iWrite;                 /* Next offset to write to */
30375
30376      iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
30377      assert( iWrite>=buf.st_size );
30378      assert( (iWrite/nBlk)==((buf.st_size+nBlk-1)/nBlk) );
30379      assert( ((iWrite+1)%nBlk)==0 );
30380      for(/*no-op*/; iWrite<nSize; iWrite+=nBlk ){
30381        nWrite = seekAndWrite(pFile, iWrite, "", 1);
30382        if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
30383      }
30384      if( nWrite==0 || (nSize%nBlk) ){
30385        nWrite = seekAndWrite(pFile, nSize-1, "", 1);
30386        if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
30387      }
30388#endif
30389    }
30390  }
30391
30392#if SQLITE_MAX_MMAP_SIZE>0
30393  if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
30394    int rc;
30395    if( pFile->szChunk<=0 ){
30396      if( robust_ftruncate(pFile->h, nByte) ){
30397        storeLastErrno(pFile, errno);
30398        return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
30399      }
30400    }
30401
30402    rc = unixMapfile(pFile, nByte);
30403    return rc;
30404  }
30405#endif
30406
30407  return SQLITE_OK;
30408}
30409
30410/*
30411** If *pArg is initially negative then this is a query.  Set *pArg to
30412** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
30413**
30414** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
30415*/
30416static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
30417  if( *pArg<0 ){
30418    *pArg = (pFile->ctrlFlags & mask)!=0;
30419  }else if( (*pArg)==0 ){
30420    pFile->ctrlFlags &= ~mask;
30421  }else{
30422    pFile->ctrlFlags |= mask;
30423  }
30424}
30425
30426/* Forward declaration */
30427static int unixGetTempname(int nBuf, char *zBuf);
30428
30429/*
30430** Information and control of an open file handle.
30431*/
30432static int unixFileControl(sqlite3_file *id, int op, void *pArg){
30433  unixFile *pFile = (unixFile*)id;
30434  switch( op ){
30435    case SQLITE_FCNTL_WAL_BLOCK: {
30436      /* pFile->ctrlFlags |= UNIXFILE_BLOCK; // Deferred feature */
30437      return SQLITE_OK;
30438    }
30439    case SQLITE_FCNTL_LOCKSTATE: {
30440      *(int*)pArg = pFile->eFileLock;
30441      return SQLITE_OK;
30442    }
30443    case SQLITE_FCNTL_LAST_ERRNO: {
30444      *(int*)pArg = pFile->lastErrno;
30445      return SQLITE_OK;
30446    }
30447    case SQLITE_FCNTL_CHUNK_SIZE: {
30448      pFile->szChunk = *(int *)pArg;
30449      return SQLITE_OK;
30450    }
30451    case SQLITE_FCNTL_SIZE_HINT: {
30452      int rc;
30453      SimulateIOErrorBenign(1);
30454      rc = fcntlSizeHint(pFile, *(i64 *)pArg);
30455      SimulateIOErrorBenign(0);
30456      return rc;
30457    }
30458    case SQLITE_FCNTL_PERSIST_WAL: {
30459      unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
30460      return SQLITE_OK;
30461    }
30462    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
30463      unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
30464      return SQLITE_OK;
30465    }
30466    case SQLITE_FCNTL_VFSNAME: {
30467      *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
30468      return SQLITE_OK;
30469    }
30470    case SQLITE_FCNTL_TEMPFILENAME: {
30471      char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
30472      if( zTFile ){
30473        unixGetTempname(pFile->pVfs->mxPathname, zTFile);
30474        *(char**)pArg = zTFile;
30475      }
30476      return SQLITE_OK;
30477    }
30478    case SQLITE_FCNTL_HAS_MOVED: {
30479      *(int*)pArg = fileHasMoved(pFile);
30480      return SQLITE_OK;
30481    }
30482#if SQLITE_MAX_MMAP_SIZE>0
30483    case SQLITE_FCNTL_MMAP_SIZE: {
30484      i64 newLimit = *(i64*)pArg;
30485      int rc = SQLITE_OK;
30486      if( newLimit>sqlite3GlobalConfig.mxMmap ){
30487        newLimit = sqlite3GlobalConfig.mxMmap;
30488      }
30489      *(i64*)pArg = pFile->mmapSizeMax;
30490      if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
30491        pFile->mmapSizeMax = newLimit;
30492        if( pFile->mmapSize>0 ){
30493          unixUnmapfile(pFile);
30494          rc = unixMapfile(pFile, -1);
30495        }
30496      }
30497      return rc;
30498    }
30499#endif
30500#ifdef SQLITE_DEBUG
30501    /* The pager calls this method to signal that it has done
30502    ** a rollback and that the database is therefore unchanged and
30503    ** it hence it is OK for the transaction change counter to be
30504    ** unchanged.
30505    */
30506    case SQLITE_FCNTL_DB_UNCHANGED: {
30507      ((unixFile*)id)->dbUpdate = 0;
30508      return SQLITE_OK;
30509    }
30510#endif
30511#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30512    case SQLITE_FCNTL_SET_LOCKPROXYFILE:
30513    case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
30514      return proxyFileControl(id,op,pArg);
30515    }
30516#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
30517  }
30518  return SQLITE_NOTFOUND;
30519}
30520
30521/*
30522** Return the sector size in bytes of the underlying block device for
30523** the specified file. This is almost always 512 bytes, but may be
30524** larger for some devices.
30525**
30526** SQLite code assumes this function cannot fail. It also assumes that
30527** if two files are created in the same file-system directory (i.e.
30528** a database and its journal file) that the sector size will be the
30529** same for both.
30530*/
30531#ifndef __QNXNTO__
30532static int unixSectorSize(sqlite3_file *NotUsed){
30533  UNUSED_PARAMETER(NotUsed);
30534  return SQLITE_DEFAULT_SECTOR_SIZE;
30535}
30536#endif
30537
30538/*
30539** The following version of unixSectorSize() is optimized for QNX.
30540*/
30541#ifdef __QNXNTO__
30542#include <sys/dcmd_blk.h>
30543#include <sys/statvfs.h>
30544static int unixSectorSize(sqlite3_file *id){
30545  unixFile *pFile = (unixFile*)id;
30546  if( pFile->sectorSize == 0 ){
30547    struct statvfs fsInfo;
30548
30549    /* Set defaults for non-supported filesystems */
30550    pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
30551    pFile->deviceCharacteristics = 0;
30552    if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
30553      return pFile->sectorSize;
30554    }
30555
30556    if( !strcmp(fsInfo.f_basetype, "tmp") ) {
30557      pFile->sectorSize = fsInfo.f_bsize;
30558      pFile->deviceCharacteristics =
30559        SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
30560        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
30561                                      ** the write succeeds */
30562        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
30563                                      ** so it is ordered */
30564        0;
30565    }else if( strstr(fsInfo.f_basetype, "etfs") ){
30566      pFile->sectorSize = fsInfo.f_bsize;
30567      pFile->deviceCharacteristics =
30568        /* etfs cluster size writes are atomic */
30569        (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
30570        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
30571                                      ** the write succeeds */
30572        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
30573                                      ** so it is ordered */
30574        0;
30575    }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
30576      pFile->sectorSize = fsInfo.f_bsize;
30577      pFile->deviceCharacteristics =
30578        SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
30579        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
30580                                      ** the write succeeds */
30581        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
30582                                      ** so it is ordered */
30583        0;
30584    }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
30585      pFile->sectorSize = fsInfo.f_bsize;
30586      pFile->deviceCharacteristics =
30587        /* full bitset of atomics from max sector size and smaller */
30588        ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
30589        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
30590                                      ** so it is ordered */
30591        0;
30592    }else if( strstr(fsInfo.f_basetype, "dos") ){
30593      pFile->sectorSize = fsInfo.f_bsize;
30594      pFile->deviceCharacteristics =
30595        /* full bitset of atomics from max sector size and smaller */
30596        ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
30597        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
30598                                      ** so it is ordered */
30599        0;
30600    }else{
30601      pFile->deviceCharacteristics =
30602        SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
30603        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
30604                                      ** the write succeeds */
30605        0;
30606    }
30607  }
30608  /* Last chance verification.  If the sector size isn't a multiple of 512
30609  ** then it isn't valid.*/
30610  if( pFile->sectorSize % 512 != 0 ){
30611    pFile->deviceCharacteristics = 0;
30612    pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
30613  }
30614  return pFile->sectorSize;
30615}
30616#endif /* __QNXNTO__ */
30617
30618/*
30619** Return the device characteristics for the file.
30620**
30621** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
30622** However, that choice is controversial since technically the underlying
30623** file system does not always provide powersafe overwrites.  (In other
30624** words, after a power-loss event, parts of the file that were never
30625** written might end up being altered.)  However, non-PSOW behavior is very,
30626** very rare.  And asserting PSOW makes a large reduction in the amount
30627** of required I/O for journaling, since a lot of padding is eliminated.
30628**  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
30629** available to turn it off and URI query parameter available to turn it off.
30630*/
30631static int unixDeviceCharacteristics(sqlite3_file *id){
30632  unixFile *p = (unixFile*)id;
30633  int rc = 0;
30634#ifdef __QNXNTO__
30635  if( p->sectorSize==0 ) unixSectorSize(id);
30636  rc = p->deviceCharacteristics;
30637#endif
30638  if( p->ctrlFlags & UNIXFILE_PSOW ){
30639    rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
30640  }
30641  return rc;
30642}
30643
30644#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
30645
30646/*
30647** Return the system page size.
30648**
30649** This function should not be called directly by other code in this file.
30650** Instead, it should be called via macro osGetpagesize().
30651*/
30652static int unixGetpagesize(void){
30653#if OS_VXWORKS
30654  return 1024;
30655#elif defined(_BSD_SOURCE)
30656  return getpagesize();
30657#else
30658  return (int)sysconf(_SC_PAGESIZE);
30659#endif
30660}
30661
30662#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
30663
30664#ifndef SQLITE_OMIT_WAL
30665
30666/*
30667** Object used to represent an shared memory buffer.
30668**
30669** When multiple threads all reference the same wal-index, each thread
30670** has its own unixShm object, but they all point to a single instance
30671** of this unixShmNode object.  In other words, each wal-index is opened
30672** only once per process.
30673**
30674** Each unixShmNode object is connected to a single unixInodeInfo object.
30675** We could coalesce this object into unixInodeInfo, but that would mean
30676** every open file that does not use shared memory (in other words, most
30677** open files) would have to carry around this extra information.  So
30678** the unixInodeInfo object contains a pointer to this unixShmNode object
30679** and the unixShmNode object is created only when needed.
30680**
30681** unixMutexHeld() must be true when creating or destroying
30682** this object or while reading or writing the following fields:
30683**
30684**      nRef
30685**
30686** The following fields are read-only after the object is created:
30687**
30688**      fid
30689**      zFilename
30690**
30691** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
30692** unixMutexHeld() is true when reading or writing any other field
30693** in this structure.
30694*/
30695struct unixShmNode {
30696  unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
30697  sqlite3_mutex *mutex;      /* Mutex to access this object */
30698  char *zFilename;           /* Name of the mmapped file */
30699  int h;                     /* Open file descriptor */
30700  int szRegion;              /* Size of shared-memory regions */
30701  u16 nRegion;               /* Size of array apRegion */
30702  u8 isReadonly;             /* True if read-only */
30703  char **apRegion;           /* Array of mapped shared-memory regions */
30704  int nRef;                  /* Number of unixShm objects pointing to this */
30705  unixShm *pFirst;           /* All unixShm objects pointing to this */
30706#ifdef SQLITE_DEBUG
30707  u8 exclMask;               /* Mask of exclusive locks held */
30708  u8 sharedMask;             /* Mask of shared locks held */
30709  u8 nextShmId;              /* Next available unixShm.id value */
30710#endif
30711};
30712
30713/*
30714** Structure used internally by this VFS to record the state of an
30715** open shared memory connection.
30716**
30717** The following fields are initialized when this object is created and
30718** are read-only thereafter:
30719**
30720**    unixShm.pFile
30721**    unixShm.id
30722**
30723** All other fields are read/write.  The unixShm.pFile->mutex must be held
30724** while accessing any read/write fields.
30725*/
30726struct unixShm {
30727  unixShmNode *pShmNode;     /* The underlying unixShmNode object */
30728  unixShm *pNext;            /* Next unixShm with the same unixShmNode */
30729  u8 hasMutex;               /* True if holding the unixShmNode mutex */
30730  u8 id;                     /* Id of this connection within its unixShmNode */
30731  u16 sharedMask;            /* Mask of shared locks held */
30732  u16 exclMask;              /* Mask of exclusive locks held */
30733};
30734
30735/*
30736** Constants used for locking
30737*/
30738#define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
30739#define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
30740
30741/*
30742** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
30743**
30744** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
30745** otherwise.
30746*/
30747static int unixShmSystemLock(
30748  unixFile *pFile,       /* Open connection to the WAL file */
30749  int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
30750  int ofst,              /* First byte of the locking range */
30751  int n                  /* Number of bytes to lock */
30752){
30753  unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
30754  struct flock f;        /* The posix advisory locking structure */
30755  int rc = SQLITE_OK;    /* Result code form fcntl() */
30756
30757  /* Access to the unixShmNode object is serialized by the caller */
30758  pShmNode = pFile->pInode->pShmNode;
30759  assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
30760
30761  /* Shared locks never span more than one byte */
30762  assert( n==1 || lockType!=F_RDLCK );
30763
30764  /* Locks are within range */
30765  assert( n>=1 && n<SQLITE_SHM_NLOCK );
30766
30767  if( pShmNode->h>=0 ){
30768    int lkType;
30769    /* Initialize the locking parameters */
30770    memset(&f, 0, sizeof(f));
30771    f.l_type = lockType;
30772    f.l_whence = SEEK_SET;
30773    f.l_start = ofst;
30774    f.l_len = n;
30775
30776    lkType = (pFile->ctrlFlags & UNIXFILE_BLOCK)!=0 ? F_SETLKW : F_SETLK;
30777    rc = osFcntl(pShmNode->h, lkType, &f);
30778    rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
30779    pFile->ctrlFlags &= ~UNIXFILE_BLOCK;
30780  }
30781
30782  /* Update the global lock state and do debug tracing */
30783#ifdef SQLITE_DEBUG
30784  { u16 mask;
30785  OSTRACE(("SHM-LOCK "));
30786  mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
30787  if( rc==SQLITE_OK ){
30788    if( lockType==F_UNLCK ){
30789      OSTRACE(("unlock %d ok", ofst));
30790      pShmNode->exclMask &= ~mask;
30791      pShmNode->sharedMask &= ~mask;
30792    }else if( lockType==F_RDLCK ){
30793      OSTRACE(("read-lock %d ok", ofst));
30794      pShmNode->exclMask &= ~mask;
30795      pShmNode->sharedMask |= mask;
30796    }else{
30797      assert( lockType==F_WRLCK );
30798      OSTRACE(("write-lock %d ok", ofst));
30799      pShmNode->exclMask |= mask;
30800      pShmNode->sharedMask &= ~mask;
30801    }
30802  }else{
30803    if( lockType==F_UNLCK ){
30804      OSTRACE(("unlock %d failed", ofst));
30805    }else if( lockType==F_RDLCK ){
30806      OSTRACE(("read-lock failed"));
30807    }else{
30808      assert( lockType==F_WRLCK );
30809      OSTRACE(("write-lock %d failed", ofst));
30810    }
30811  }
30812  OSTRACE((" - afterwards %03x,%03x\n",
30813           pShmNode->sharedMask, pShmNode->exclMask));
30814  }
30815#endif
30816
30817  return rc;
30818}
30819
30820/*
30821** Return the minimum number of 32KB shm regions that should be mapped at
30822** a time, assuming that each mapping must be an integer multiple of the
30823** current system page-size.
30824**
30825** Usually, this is 1. The exception seems to be systems that are configured
30826** to use 64KB pages - in this case each mapping must cover at least two
30827** shm regions.
30828*/
30829static int unixShmRegionPerMap(void){
30830  int shmsz = 32*1024;            /* SHM region size */
30831  int pgsz = osGetpagesize();   /* System page size */
30832  assert( ((pgsz-1)&pgsz)==0 );   /* Page size must be a power of 2 */
30833  if( pgsz<shmsz ) return 1;
30834  return pgsz/shmsz;
30835}
30836
30837/*
30838** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
30839**
30840** This is not a VFS shared-memory method; it is a utility function called
30841** by VFS shared-memory methods.
30842*/
30843static void unixShmPurge(unixFile *pFd){
30844  unixShmNode *p = pFd->pInode->pShmNode;
30845  assert( unixMutexHeld() );
30846  if( p && p->nRef==0 ){
30847    int nShmPerMap = unixShmRegionPerMap();
30848    int i;
30849    assert( p->pInode==pFd->pInode );
30850    sqlite3_mutex_free(p->mutex);
30851    for(i=0; i<p->nRegion; i+=nShmPerMap){
30852      if( p->h>=0 ){
30853        osMunmap(p->apRegion[i], p->szRegion);
30854      }else{
30855        sqlite3_free(p->apRegion[i]);
30856      }
30857    }
30858    sqlite3_free(p->apRegion);
30859    if( p->h>=0 ){
30860      robust_close(pFd, p->h, __LINE__);
30861      p->h = -1;
30862    }
30863    p->pInode->pShmNode = 0;
30864    sqlite3_free(p);
30865  }
30866}
30867
30868/*
30869** Open a shared-memory area associated with open database file pDbFd.
30870** This particular implementation uses mmapped files.
30871**
30872** The file used to implement shared-memory is in the same directory
30873** as the open database file and has the same name as the open database
30874** file with the "-shm" suffix added.  For example, if the database file
30875** is "/home/user1/config.db" then the file that is created and mmapped
30876** for shared memory will be called "/home/user1/config.db-shm".
30877**
30878** Another approach to is to use files in /dev/shm or /dev/tmp or an
30879** some other tmpfs mount. But if a file in a different directory
30880** from the database file is used, then differing access permissions
30881** or a chroot() might cause two different processes on the same
30882** database to end up using different files for shared memory -
30883** meaning that their memory would not really be shared - resulting
30884** in database corruption.  Nevertheless, this tmpfs file usage
30885** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
30886** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
30887** option results in an incompatible build of SQLite;  builds of SQLite
30888** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
30889** same database file at the same time, database corruption will likely
30890** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
30891** "unsupported" and may go away in a future SQLite release.
30892**
30893** When opening a new shared-memory file, if no other instances of that
30894** file are currently open, in this process or in other processes, then
30895** the file must be truncated to zero length or have its header cleared.
30896**
30897** If the original database file (pDbFd) is using the "unix-excl" VFS
30898** that means that an exclusive lock is held on the database file and
30899** that no other processes are able to read or write the database.  In
30900** that case, we do not really need shared memory.  No shared memory
30901** file is created.  The shared memory will be simulated with heap memory.
30902*/
30903static int unixOpenSharedMemory(unixFile *pDbFd){
30904  struct unixShm *p = 0;          /* The connection to be opened */
30905  struct unixShmNode *pShmNode;   /* The underlying mmapped file */
30906  int rc;                         /* Result code */
30907  unixInodeInfo *pInode;          /* The inode of fd */
30908  char *zShmFilename;             /* Name of the file used for SHM */
30909  int nShmFilename;               /* Size of the SHM filename in bytes */
30910
30911  /* Allocate space for the new unixShm object. */
30912  p = sqlite3_malloc64( sizeof(*p) );
30913  if( p==0 ) return SQLITE_NOMEM;
30914  memset(p, 0, sizeof(*p));
30915  assert( pDbFd->pShm==0 );
30916
30917  /* Check to see if a unixShmNode object already exists. Reuse an existing
30918  ** one if present. Create a new one if necessary.
30919  */
30920  unixEnterMutex();
30921  pInode = pDbFd->pInode;
30922  pShmNode = pInode->pShmNode;
30923  if( pShmNode==0 ){
30924    struct stat sStat;                 /* fstat() info for database file */
30925#ifndef SQLITE_SHM_DIRECTORY
30926    const char *zBasePath = pDbFd->zPath;
30927#endif
30928
30929    /* Call fstat() to figure out the permissions on the database file. If
30930    ** a new *-shm file is created, an attempt will be made to create it
30931    ** with the same permissions.
30932    */
30933    if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
30934      rc = unixLogError(SQLITE_IOERR_FSTAT, "fstat", pDbFd->zPath);
30935      goto shm_open_err;
30936    }
30937
30938#ifdef SQLITE_SHM_DIRECTORY
30939    nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
30940#else
30941    nShmFilename = 6 + (int)strlen(zBasePath);
30942#endif
30943    pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
30944    if( pShmNode==0 ){
30945      rc = SQLITE_NOMEM;
30946      goto shm_open_err;
30947    }
30948    memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
30949    zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
30950#ifdef SQLITE_SHM_DIRECTORY
30951    sqlite3_snprintf(nShmFilename, zShmFilename,
30952                     SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
30953                     (u32)sStat.st_ino, (u32)sStat.st_dev);
30954#else
30955    sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
30956    sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
30957#endif
30958    pShmNode->h = -1;
30959    pDbFd->pInode->pShmNode = pShmNode;
30960    pShmNode->pInode = pDbFd->pInode;
30961    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
30962    if( pShmNode->mutex==0 ){
30963      rc = SQLITE_NOMEM;
30964      goto shm_open_err;
30965    }
30966
30967    if( pInode->bProcessLock==0 ){
30968      int openFlags = O_RDWR | O_CREAT;
30969      if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
30970        openFlags = O_RDONLY;
30971        pShmNode->isReadonly = 1;
30972      }
30973      pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
30974      if( pShmNode->h<0 ){
30975        rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
30976        goto shm_open_err;
30977      }
30978
30979      /* If this process is running as root, make sure that the SHM file
30980      ** is owned by the same user that owns the original database.  Otherwise,
30981      ** the original owner will not be able to connect.
30982      */
30983      osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
30984
30985      /* Check to see if another process is holding the dead-man switch.
30986      ** If not, truncate the file to zero length.
30987      */
30988      rc = SQLITE_OK;
30989      if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
30990        if( robust_ftruncate(pShmNode->h, 0) ){
30991          rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
30992        }
30993      }
30994      if( rc==SQLITE_OK ){
30995        rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
30996      }
30997      if( rc ) goto shm_open_err;
30998    }
30999  }
31000
31001  /* Make the new connection a child of the unixShmNode */
31002  p->pShmNode = pShmNode;
31003#ifdef SQLITE_DEBUG
31004  p->id = pShmNode->nextShmId++;
31005#endif
31006  pShmNode->nRef++;
31007  pDbFd->pShm = p;
31008  unixLeaveMutex();
31009
31010  /* The reference count on pShmNode has already been incremented under
31011  ** the cover of the unixEnterMutex() mutex and the pointer from the
31012  ** new (struct unixShm) object to the pShmNode has been set. All that is
31013  ** left to do is to link the new object into the linked list starting
31014  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
31015  ** mutex.
31016  */
31017  sqlite3_mutex_enter(pShmNode->mutex);
31018  p->pNext = pShmNode->pFirst;
31019  pShmNode->pFirst = p;
31020  sqlite3_mutex_leave(pShmNode->mutex);
31021  return SQLITE_OK;
31022
31023  /* Jump here on any error */
31024shm_open_err:
31025  unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
31026  sqlite3_free(p);
31027  unixLeaveMutex();
31028  return rc;
31029}
31030
31031/*
31032** This function is called to obtain a pointer to region iRegion of the
31033** shared-memory associated with the database file fd. Shared-memory regions
31034** are numbered starting from zero. Each shared-memory region is szRegion
31035** bytes in size.
31036**
31037** If an error occurs, an error code is returned and *pp is set to NULL.
31038**
31039** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
31040** region has not been allocated (by any client, including one running in a
31041** separate process), then *pp is set to NULL and SQLITE_OK returned. If
31042** bExtend is non-zero and the requested shared-memory region has not yet
31043** been allocated, it is allocated by this function.
31044**
31045** If the shared-memory region has already been allocated or is allocated by
31046** this call as described above, then it is mapped into this processes
31047** address space (if it is not already), *pp is set to point to the mapped
31048** memory and SQLITE_OK returned.
31049*/
31050static int unixShmMap(
31051  sqlite3_file *fd,               /* Handle open on database file */
31052  int iRegion,                    /* Region to retrieve */
31053  int szRegion,                   /* Size of regions */
31054  int bExtend,                    /* True to extend file if necessary */
31055  void volatile **pp              /* OUT: Mapped memory */
31056){
31057  unixFile *pDbFd = (unixFile*)fd;
31058  unixShm *p;
31059  unixShmNode *pShmNode;
31060  int rc = SQLITE_OK;
31061  int nShmPerMap = unixShmRegionPerMap();
31062  int nReqRegion;
31063
31064  /* If the shared-memory file has not yet been opened, open it now. */
31065  if( pDbFd->pShm==0 ){
31066    rc = unixOpenSharedMemory(pDbFd);
31067    if( rc!=SQLITE_OK ) return rc;
31068  }
31069
31070  p = pDbFd->pShm;
31071  pShmNode = p->pShmNode;
31072  sqlite3_mutex_enter(pShmNode->mutex);
31073  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
31074  assert( pShmNode->pInode==pDbFd->pInode );
31075  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
31076  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
31077
31078  /* Minimum number of regions required to be mapped. */
31079  nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
31080
31081  if( pShmNode->nRegion<nReqRegion ){
31082    char **apNew;                      /* New apRegion[] array */
31083    int nByte = nReqRegion*szRegion;   /* Minimum required file size */
31084    struct stat sStat;                 /* Used by fstat() */
31085
31086    pShmNode->szRegion = szRegion;
31087
31088    if( pShmNode->h>=0 ){
31089      /* The requested region is not mapped into this processes address space.
31090      ** Check to see if it has been allocated (i.e. if the wal-index file is
31091      ** large enough to contain the requested region).
31092      */
31093      if( osFstat(pShmNode->h, &sStat) ){
31094        rc = SQLITE_IOERR_SHMSIZE;
31095        goto shmpage_out;
31096      }
31097
31098      if( sStat.st_size<nByte ){
31099        /* The requested memory region does not exist. If bExtend is set to
31100        ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
31101        */
31102        if( !bExtend ){
31103          goto shmpage_out;
31104        }
31105
31106        /* Alternatively, if bExtend is true, extend the file. Do this by
31107        ** writing a single byte to the end of each (OS) page being
31108        ** allocated or extended. Technically, we need only write to the
31109        ** last page in order to extend the file. But writing to all new
31110        ** pages forces the OS to allocate them immediately, which reduces
31111        ** the chances of SIGBUS while accessing the mapped region later on.
31112        */
31113        else{
31114          static const int pgsz = 4096;
31115          int iPg;
31116
31117          /* Write to the last byte of each newly allocated or extended page */
31118          assert( (nByte % pgsz)==0 );
31119          for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
31120            if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
31121              const char *zFile = pShmNode->zFilename;
31122              rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
31123              goto shmpage_out;
31124            }
31125          }
31126        }
31127      }
31128    }
31129
31130    /* Map the requested memory region into this processes address space. */
31131    apNew = (char **)sqlite3_realloc(
31132        pShmNode->apRegion, nReqRegion*sizeof(char *)
31133    );
31134    if( !apNew ){
31135      rc = SQLITE_IOERR_NOMEM;
31136      goto shmpage_out;
31137    }
31138    pShmNode->apRegion = apNew;
31139    while( pShmNode->nRegion<nReqRegion ){
31140      int nMap = szRegion*nShmPerMap;
31141      int i;
31142      void *pMem;
31143      if( pShmNode->h>=0 ){
31144        pMem = osMmap(0, nMap,
31145            pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
31146            MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
31147        );
31148        if( pMem==MAP_FAILED ){
31149          rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
31150          goto shmpage_out;
31151        }
31152      }else{
31153        pMem = sqlite3_malloc64(szRegion);
31154        if( pMem==0 ){
31155          rc = SQLITE_NOMEM;
31156          goto shmpage_out;
31157        }
31158        memset(pMem, 0, szRegion);
31159      }
31160
31161      for(i=0; i<nShmPerMap; i++){
31162        pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
31163      }
31164      pShmNode->nRegion += nShmPerMap;
31165    }
31166  }
31167
31168shmpage_out:
31169  if( pShmNode->nRegion>iRegion ){
31170    *pp = pShmNode->apRegion[iRegion];
31171  }else{
31172    *pp = 0;
31173  }
31174  if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
31175  sqlite3_mutex_leave(pShmNode->mutex);
31176  return rc;
31177}
31178
31179/*
31180** Change the lock state for a shared-memory segment.
31181**
31182** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
31183** different here than in posix.  In xShmLock(), one can go from unlocked
31184** to shared and back or from unlocked to exclusive and back.  But one may
31185** not go from shared to exclusive or from exclusive to shared.
31186*/
31187static int unixShmLock(
31188  sqlite3_file *fd,          /* Database file holding the shared memory */
31189  int ofst,                  /* First lock to acquire or release */
31190  int n,                     /* Number of locks to acquire or release */
31191  int flags                  /* What to do with the lock */
31192){
31193  unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
31194  unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
31195  unixShm *pX;                          /* For looping over all siblings */
31196  unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
31197  int rc = SQLITE_OK;                   /* Result code */
31198  u16 mask;                             /* Mask of locks to take or release */
31199
31200  assert( pShmNode==pDbFd->pInode->pShmNode );
31201  assert( pShmNode->pInode==pDbFd->pInode );
31202  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
31203  assert( n>=1 );
31204  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
31205       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
31206       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
31207       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
31208  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
31209  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
31210  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
31211
31212  mask = (1<<(ofst+n)) - (1<<ofst);
31213  assert( n>1 || mask==(1<<ofst) );
31214  sqlite3_mutex_enter(pShmNode->mutex);
31215  if( flags & SQLITE_SHM_UNLOCK ){
31216    u16 allMask = 0; /* Mask of locks held by siblings */
31217
31218    /* See if any siblings hold this same lock */
31219    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
31220      if( pX==p ) continue;
31221      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
31222      allMask |= pX->sharedMask;
31223    }
31224
31225    /* Unlock the system-level locks */
31226    if( (mask & allMask)==0 ){
31227      rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
31228    }else{
31229      rc = SQLITE_OK;
31230    }
31231
31232    /* Undo the local locks */
31233    if( rc==SQLITE_OK ){
31234      p->exclMask &= ~mask;
31235      p->sharedMask &= ~mask;
31236    }
31237  }else if( flags & SQLITE_SHM_SHARED ){
31238    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
31239
31240    /* Find out which shared locks are already held by sibling connections.
31241    ** If any sibling already holds an exclusive lock, go ahead and return
31242    ** SQLITE_BUSY.
31243    */
31244    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
31245      if( (pX->exclMask & mask)!=0 ){
31246        rc = SQLITE_BUSY;
31247        break;
31248      }
31249      allShared |= pX->sharedMask;
31250    }
31251
31252    /* Get shared locks at the system level, if necessary */
31253    if( rc==SQLITE_OK ){
31254      if( (allShared & mask)==0 ){
31255        rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
31256      }else{
31257        rc = SQLITE_OK;
31258      }
31259    }
31260
31261    /* Get the local shared locks */
31262    if( rc==SQLITE_OK ){
31263      p->sharedMask |= mask;
31264    }
31265  }else{
31266    /* Make sure no sibling connections hold locks that will block this
31267    ** lock.  If any do, return SQLITE_BUSY right away.
31268    */
31269    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
31270      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
31271        rc = SQLITE_BUSY;
31272        break;
31273      }
31274    }
31275
31276    /* Get the exclusive locks at the system level.  Then if successful
31277    ** also mark the local connection as being locked.
31278    */
31279    if( rc==SQLITE_OK ){
31280      rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
31281      if( rc==SQLITE_OK ){
31282        assert( (p->sharedMask & mask)==0 );
31283        p->exclMask |= mask;
31284      }
31285    }
31286  }
31287  sqlite3_mutex_leave(pShmNode->mutex);
31288  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
31289           p->id, osGetpid(0), p->sharedMask, p->exclMask));
31290  return rc;
31291}
31292
31293/*
31294** Implement a memory barrier or memory fence on shared memory.
31295**
31296** All loads and stores begun before the barrier must complete before
31297** any load or store begun after the barrier.
31298*/
31299static void unixShmBarrier(
31300  sqlite3_file *fd                /* Database file holding the shared memory */
31301){
31302  UNUSED_PARAMETER(fd);
31303  sqlite3MemoryBarrier();         /* compiler-defined memory barrier */
31304  unixEnterMutex();               /* Also mutex, for redundancy */
31305  unixLeaveMutex();
31306}
31307
31308/*
31309** Close a connection to shared-memory.  Delete the underlying
31310** storage if deleteFlag is true.
31311**
31312** If there is no shared memory associated with the connection then this
31313** routine is a harmless no-op.
31314*/
31315static int unixShmUnmap(
31316  sqlite3_file *fd,               /* The underlying database file */
31317  int deleteFlag                  /* Delete shared-memory if true */
31318){
31319  unixShm *p;                     /* The connection to be closed */
31320  unixShmNode *pShmNode;          /* The underlying shared-memory file */
31321  unixShm **pp;                   /* For looping over sibling connections */
31322  unixFile *pDbFd;                /* The underlying database file */
31323
31324  pDbFd = (unixFile*)fd;
31325  p = pDbFd->pShm;
31326  if( p==0 ) return SQLITE_OK;
31327  pShmNode = p->pShmNode;
31328
31329  assert( pShmNode==pDbFd->pInode->pShmNode );
31330  assert( pShmNode->pInode==pDbFd->pInode );
31331
31332  /* Remove connection p from the set of connections associated
31333  ** with pShmNode */
31334  sqlite3_mutex_enter(pShmNode->mutex);
31335  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
31336  *pp = p->pNext;
31337
31338  /* Free the connection p */
31339  sqlite3_free(p);
31340  pDbFd->pShm = 0;
31341  sqlite3_mutex_leave(pShmNode->mutex);
31342
31343  /* If pShmNode->nRef has reached 0, then close the underlying
31344  ** shared-memory file, too */
31345  unixEnterMutex();
31346  assert( pShmNode->nRef>0 );
31347  pShmNode->nRef--;
31348  if( pShmNode->nRef==0 ){
31349    if( deleteFlag && pShmNode->h>=0 ){
31350      osUnlink(pShmNode->zFilename);
31351    }
31352    unixShmPurge(pDbFd);
31353  }
31354  unixLeaveMutex();
31355
31356  return SQLITE_OK;
31357}
31358
31359
31360#else
31361# define unixShmMap     0
31362# define unixShmLock    0
31363# define unixShmBarrier 0
31364# define unixShmUnmap   0
31365#endif /* #ifndef SQLITE_OMIT_WAL */
31366
31367#if SQLITE_MAX_MMAP_SIZE>0
31368/*
31369** If it is currently memory mapped, unmap file pFd.
31370*/
31371static void unixUnmapfile(unixFile *pFd){
31372  assert( pFd->nFetchOut==0 );
31373  if( pFd->pMapRegion ){
31374    osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
31375    pFd->pMapRegion = 0;
31376    pFd->mmapSize = 0;
31377    pFd->mmapSizeActual = 0;
31378  }
31379}
31380
31381/*
31382** Attempt to set the size of the memory mapping maintained by file
31383** descriptor pFd to nNew bytes. Any existing mapping is discarded.
31384**
31385** If successful, this function sets the following variables:
31386**
31387**       unixFile.pMapRegion
31388**       unixFile.mmapSize
31389**       unixFile.mmapSizeActual
31390**
31391** If unsuccessful, an error message is logged via sqlite3_log() and
31392** the three variables above are zeroed. In this case SQLite should
31393** continue accessing the database using the xRead() and xWrite()
31394** methods.
31395*/
31396static void unixRemapfile(
31397  unixFile *pFd,                  /* File descriptor object */
31398  i64 nNew                        /* Required mapping size */
31399){
31400  const char *zErr = "mmap";
31401  int h = pFd->h;                      /* File descriptor open on db file */
31402  u8 *pOrig = (u8 *)pFd->pMapRegion;   /* Pointer to current file mapping */
31403  i64 nOrig = pFd->mmapSizeActual;     /* Size of pOrig region in bytes */
31404  u8 *pNew = 0;                        /* Location of new mapping */
31405  int flags = PROT_READ;               /* Flags to pass to mmap() */
31406
31407  assert( pFd->nFetchOut==0 );
31408  assert( nNew>pFd->mmapSize );
31409  assert( nNew<=pFd->mmapSizeMax );
31410  assert( nNew>0 );
31411  assert( pFd->mmapSizeActual>=pFd->mmapSize );
31412  assert( MAP_FAILED!=0 );
31413
31414  if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
31415
31416  if( pOrig ){
31417#if HAVE_MREMAP
31418    i64 nReuse = pFd->mmapSize;
31419#else
31420    const int szSyspage = osGetpagesize();
31421    i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
31422#endif
31423    u8 *pReq = &pOrig[nReuse];
31424
31425    /* Unmap any pages of the existing mapping that cannot be reused. */
31426    if( nReuse!=nOrig ){
31427      osMunmap(pReq, nOrig-nReuse);
31428    }
31429
31430#if HAVE_MREMAP
31431    pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
31432    zErr = "mremap";
31433#else
31434    pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
31435    if( pNew!=MAP_FAILED ){
31436      if( pNew!=pReq ){
31437        osMunmap(pNew, nNew - nReuse);
31438        pNew = 0;
31439      }else{
31440        pNew = pOrig;
31441      }
31442    }
31443#endif
31444
31445    /* The attempt to extend the existing mapping failed. Free it. */
31446    if( pNew==MAP_FAILED || pNew==0 ){
31447      osMunmap(pOrig, nReuse);
31448    }
31449  }
31450
31451  /* If pNew is still NULL, try to create an entirely new mapping. */
31452  if( pNew==0 ){
31453    pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
31454  }
31455
31456  if( pNew==MAP_FAILED ){
31457    pNew = 0;
31458    nNew = 0;
31459    unixLogError(SQLITE_OK, zErr, pFd->zPath);
31460
31461    /* If the mmap() above failed, assume that all subsequent mmap() calls
31462    ** will probably fail too. Fall back to using xRead/xWrite exclusively
31463    ** in this case.  */
31464    pFd->mmapSizeMax = 0;
31465  }
31466  pFd->pMapRegion = (void *)pNew;
31467  pFd->mmapSize = pFd->mmapSizeActual = nNew;
31468}
31469
31470/*
31471** Memory map or remap the file opened by file-descriptor pFd (if the file
31472** is already mapped, the existing mapping is replaced by the new). Or, if
31473** there already exists a mapping for this file, and there are still
31474** outstanding xFetch() references to it, this function is a no-op.
31475**
31476** If parameter nByte is non-negative, then it is the requested size of
31477** the mapping to create. Otherwise, if nByte is less than zero, then the
31478** requested size is the size of the file on disk. The actual size of the
31479** created mapping is either the requested size or the value configured
31480** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
31481**
31482** SQLITE_OK is returned if no error occurs (even if the mapping is not
31483** recreated as a result of outstanding references) or an SQLite error
31484** code otherwise.
31485*/
31486static int unixMapfile(unixFile *pFd, i64 nByte){
31487  i64 nMap = nByte;
31488  int rc;
31489
31490  assert( nMap>=0 || pFd->nFetchOut==0 );
31491  if( pFd->nFetchOut>0 ) return SQLITE_OK;
31492
31493  if( nMap<0 ){
31494    struct stat statbuf;          /* Low-level file information */
31495    rc = osFstat(pFd->h, &statbuf);
31496    if( rc!=SQLITE_OK ){
31497      return SQLITE_IOERR_FSTAT;
31498    }
31499    nMap = statbuf.st_size;
31500  }
31501  if( nMap>pFd->mmapSizeMax ){
31502    nMap = pFd->mmapSizeMax;
31503  }
31504
31505  if( nMap!=pFd->mmapSize ){
31506    if( nMap>0 ){
31507      unixRemapfile(pFd, nMap);
31508    }else{
31509      unixUnmapfile(pFd);
31510    }
31511  }
31512
31513  return SQLITE_OK;
31514}
31515#endif /* SQLITE_MAX_MMAP_SIZE>0 */
31516
31517/*
31518** If possible, return a pointer to a mapping of file fd starting at offset
31519** iOff. The mapping must be valid for at least nAmt bytes.
31520**
31521** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
31522** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
31523** Finally, if an error does occur, return an SQLite error code. The final
31524** value of *pp is undefined in this case.
31525**
31526** If this function does return a pointer, the caller must eventually
31527** release the reference by calling unixUnfetch().
31528*/
31529static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
31530#if SQLITE_MAX_MMAP_SIZE>0
31531  unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
31532#endif
31533  *pp = 0;
31534
31535#if SQLITE_MAX_MMAP_SIZE>0
31536  if( pFd->mmapSizeMax>0 ){
31537    if( pFd->pMapRegion==0 ){
31538      int rc = unixMapfile(pFd, -1);
31539      if( rc!=SQLITE_OK ) return rc;
31540    }
31541    if( pFd->mmapSize >= iOff+nAmt ){
31542      *pp = &((u8 *)pFd->pMapRegion)[iOff];
31543      pFd->nFetchOut++;
31544    }
31545  }
31546#endif
31547  return SQLITE_OK;
31548}
31549
31550/*
31551** If the third argument is non-NULL, then this function releases a
31552** reference obtained by an earlier call to unixFetch(). The second
31553** argument passed to this function must be the same as the corresponding
31554** argument that was passed to the unixFetch() invocation.
31555**
31556** Or, if the third argument is NULL, then this function is being called
31557** to inform the VFS layer that, according to POSIX, any existing mapping
31558** may now be invalid and should be unmapped.
31559*/
31560static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
31561#if SQLITE_MAX_MMAP_SIZE>0
31562  unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
31563  UNUSED_PARAMETER(iOff);
31564
31565  /* If p==0 (unmap the entire file) then there must be no outstanding
31566  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
31567  ** then there must be at least one outstanding.  */
31568  assert( (p==0)==(pFd->nFetchOut==0) );
31569
31570  /* If p!=0, it must match the iOff value. */
31571  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
31572
31573  if( p ){
31574    pFd->nFetchOut--;
31575  }else{
31576    unixUnmapfile(pFd);
31577  }
31578
31579  assert( pFd->nFetchOut>=0 );
31580#else
31581  UNUSED_PARAMETER(fd);
31582  UNUSED_PARAMETER(p);
31583  UNUSED_PARAMETER(iOff);
31584#endif
31585  return SQLITE_OK;
31586}
31587
31588/*
31589** Here ends the implementation of all sqlite3_file methods.
31590**
31591********************** End sqlite3_file Methods *******************************
31592******************************************************************************/
31593
31594/*
31595** This division contains definitions of sqlite3_io_methods objects that
31596** implement various file locking strategies.  It also contains definitions
31597** of "finder" functions.  A finder-function is used to locate the appropriate
31598** sqlite3_io_methods object for a particular database file.  The pAppData
31599** field of the sqlite3_vfs VFS objects are initialized to be pointers to
31600** the correct finder-function for that VFS.
31601**
31602** Most finder functions return a pointer to a fixed sqlite3_io_methods
31603** object.  The only interesting finder-function is autolockIoFinder, which
31604** looks at the filesystem type and tries to guess the best locking
31605** strategy from that.
31606**
31607** For finder-function F, two objects are created:
31608**
31609**    (1) The real finder-function named "FImpt()".
31610**
31611**    (2) A constant pointer to this function named just "F".
31612**
31613**
31614** A pointer to the F pointer is used as the pAppData value for VFS
31615** objects.  We have to do this instead of letting pAppData point
31616** directly at the finder-function since C90 rules prevent a void*
31617** from be cast into a function pointer.
31618**
31619**
31620** Each instance of this macro generates two objects:
31621**
31622**   *  A constant sqlite3_io_methods object call METHOD that has locking
31623**      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
31624**
31625**   *  An I/O method finder function called FINDER that returns a pointer
31626**      to the METHOD object in the previous bullet.
31627*/
31628#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP)     \
31629static const sqlite3_io_methods METHOD = {                                   \
31630   VERSION,                    /* iVersion */                                \
31631   CLOSE,                      /* xClose */                                  \
31632   unixRead,                   /* xRead */                                   \
31633   unixWrite,                  /* xWrite */                                  \
31634   unixTruncate,               /* xTruncate */                               \
31635   unixSync,                   /* xSync */                                   \
31636   unixFileSize,               /* xFileSize */                               \
31637   LOCK,                       /* xLock */                                   \
31638   UNLOCK,                     /* xUnlock */                                 \
31639   CKLOCK,                     /* xCheckReservedLock */                      \
31640   unixFileControl,            /* xFileControl */                            \
31641   unixSectorSize,             /* xSectorSize */                             \
31642   unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
31643   SHMMAP,                     /* xShmMap */                                 \
31644   unixShmLock,                /* xShmLock */                                \
31645   unixShmBarrier,             /* xShmBarrier */                             \
31646   unixShmUnmap,               /* xShmUnmap */                               \
31647   unixFetch,                  /* xFetch */                                  \
31648   unixUnfetch,                /* xUnfetch */                                \
31649};                                                                           \
31650static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
31651  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
31652  return &METHOD;                                                            \
31653}                                                                            \
31654static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
31655    = FINDER##Impl;
31656
31657/*
31658** Here are all of the sqlite3_io_methods objects for each of the
31659** locking strategies.  Functions that return pointers to these methods
31660** are also created.
31661*/
31662IOMETHODS(
31663  posixIoFinder,            /* Finder function name */
31664  posixIoMethods,           /* sqlite3_io_methods object name */
31665  3,                        /* shared memory and mmap are enabled */
31666  unixClose,                /* xClose method */
31667  unixLock,                 /* xLock method */
31668  unixUnlock,               /* xUnlock method */
31669  unixCheckReservedLock,    /* xCheckReservedLock method */
31670  unixShmMap                /* xShmMap method */
31671)
31672IOMETHODS(
31673  nolockIoFinder,           /* Finder function name */
31674  nolockIoMethods,          /* sqlite3_io_methods object name */
31675  3,                        /* shared memory is disabled */
31676  nolockClose,              /* xClose method */
31677  nolockLock,               /* xLock method */
31678  nolockUnlock,             /* xUnlock method */
31679  nolockCheckReservedLock,  /* xCheckReservedLock method */
31680  0                         /* xShmMap method */
31681)
31682IOMETHODS(
31683  dotlockIoFinder,          /* Finder function name */
31684  dotlockIoMethods,         /* sqlite3_io_methods object name */
31685  1,                        /* shared memory is disabled */
31686  dotlockClose,             /* xClose method */
31687  dotlockLock,              /* xLock method */
31688  dotlockUnlock,            /* xUnlock method */
31689  dotlockCheckReservedLock, /* xCheckReservedLock method */
31690  0                         /* xShmMap method */
31691)
31692
31693#if SQLITE_ENABLE_LOCKING_STYLE
31694IOMETHODS(
31695  flockIoFinder,            /* Finder function name */
31696  flockIoMethods,           /* sqlite3_io_methods object name */
31697  1,                        /* shared memory is disabled */
31698  flockClose,               /* xClose method */
31699  flockLock,                /* xLock method */
31700  flockUnlock,              /* xUnlock method */
31701  flockCheckReservedLock,   /* xCheckReservedLock method */
31702  0                         /* xShmMap method */
31703)
31704#endif
31705
31706#if OS_VXWORKS
31707IOMETHODS(
31708  semIoFinder,              /* Finder function name */
31709  semIoMethods,             /* sqlite3_io_methods object name */
31710  1,                        /* shared memory is disabled */
31711  semXClose,                /* xClose method */
31712  semXLock,                 /* xLock method */
31713  semXUnlock,               /* xUnlock method */
31714  semXCheckReservedLock,    /* xCheckReservedLock method */
31715  0                         /* xShmMap method */
31716)
31717#endif
31718
31719#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31720IOMETHODS(
31721  afpIoFinder,              /* Finder function name */
31722  afpIoMethods,             /* sqlite3_io_methods object name */
31723  1,                        /* shared memory is disabled */
31724  afpClose,                 /* xClose method */
31725  afpLock,                  /* xLock method */
31726  afpUnlock,                /* xUnlock method */
31727  afpCheckReservedLock,     /* xCheckReservedLock method */
31728  0                         /* xShmMap method */
31729)
31730#endif
31731
31732/*
31733** The proxy locking method is a "super-method" in the sense that it
31734** opens secondary file descriptors for the conch and lock files and
31735** it uses proxy, dot-file, AFP, and flock() locking methods on those
31736** secondary files.  For this reason, the division that implements
31737** proxy locking is located much further down in the file.  But we need
31738** to go ahead and define the sqlite3_io_methods and finder function
31739** for proxy locking here.  So we forward declare the I/O methods.
31740*/
31741#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31742static int proxyClose(sqlite3_file*);
31743static int proxyLock(sqlite3_file*, int);
31744static int proxyUnlock(sqlite3_file*, int);
31745static int proxyCheckReservedLock(sqlite3_file*, int*);
31746IOMETHODS(
31747  proxyIoFinder,            /* Finder function name */
31748  proxyIoMethods,           /* sqlite3_io_methods object name */
31749  1,                        /* shared memory is disabled */
31750  proxyClose,               /* xClose method */
31751  proxyLock,                /* xLock method */
31752  proxyUnlock,              /* xUnlock method */
31753  proxyCheckReservedLock,   /* xCheckReservedLock method */
31754  0                         /* xShmMap method */
31755)
31756#endif
31757
31758/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
31759#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31760IOMETHODS(
31761  nfsIoFinder,               /* Finder function name */
31762  nfsIoMethods,              /* sqlite3_io_methods object name */
31763  1,                         /* shared memory is disabled */
31764  unixClose,                 /* xClose method */
31765  unixLock,                  /* xLock method */
31766  nfsUnlock,                 /* xUnlock method */
31767  unixCheckReservedLock,     /* xCheckReservedLock method */
31768  0                          /* xShmMap method */
31769)
31770#endif
31771
31772#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31773/*
31774** This "finder" function attempts to determine the best locking strategy
31775** for the database file "filePath".  It then returns the sqlite3_io_methods
31776** object that implements that strategy.
31777**
31778** This is for MacOSX only.
31779*/
31780static const sqlite3_io_methods *autolockIoFinderImpl(
31781  const char *filePath,    /* name of the database file */
31782  unixFile *pNew           /* open file object for the database file */
31783){
31784  static const struct Mapping {
31785    const char *zFilesystem;              /* Filesystem type name */
31786    const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
31787  } aMap[] = {
31788    { "hfs",    &posixIoMethods },
31789    { "ufs",    &posixIoMethods },
31790    { "afpfs",  &afpIoMethods },
31791    { "smbfs",  &afpIoMethods },
31792    { "webdav", &nolockIoMethods },
31793    { 0, 0 }
31794  };
31795  int i;
31796  struct statfs fsInfo;
31797  struct flock lockInfo;
31798
31799  if( !filePath ){
31800    /* If filePath==NULL that means we are dealing with a transient file
31801    ** that does not need to be locked. */
31802    return &nolockIoMethods;
31803  }
31804  if( statfs(filePath, &fsInfo) != -1 ){
31805    if( fsInfo.f_flags & MNT_RDONLY ){
31806      return &nolockIoMethods;
31807    }
31808    for(i=0; aMap[i].zFilesystem; i++){
31809      if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
31810        return aMap[i].pMethods;
31811      }
31812    }
31813  }
31814
31815  /* Default case. Handles, amongst others, "nfs".
31816  ** Test byte-range lock using fcntl(). If the call succeeds,
31817  ** assume that the file-system supports POSIX style locks.
31818  */
31819  lockInfo.l_len = 1;
31820  lockInfo.l_start = 0;
31821  lockInfo.l_whence = SEEK_SET;
31822  lockInfo.l_type = F_RDLCK;
31823  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
31824    if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
31825      return &nfsIoMethods;
31826    } else {
31827      return &posixIoMethods;
31828    }
31829  }else{
31830    return &dotlockIoMethods;
31831  }
31832}
31833static const sqlite3_io_methods
31834  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
31835
31836#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
31837
31838#if OS_VXWORKS
31839/*
31840** This "finder" function for VxWorks checks to see if posix advisory
31841** locking works.  If it does, then that is what is used.  If it does not
31842** work, then fallback to named semaphore locking.
31843*/
31844static const sqlite3_io_methods *vxworksIoFinderImpl(
31845  const char *filePath,    /* name of the database file */
31846  unixFile *pNew           /* the open file object */
31847){
31848  struct flock lockInfo;
31849
31850  if( !filePath ){
31851    /* If filePath==NULL that means we are dealing with a transient file
31852    ** that does not need to be locked. */
31853    return &nolockIoMethods;
31854  }
31855
31856  /* Test if fcntl() is supported and use POSIX style locks.
31857  ** Otherwise fall back to the named semaphore method.
31858  */
31859  lockInfo.l_len = 1;
31860  lockInfo.l_start = 0;
31861  lockInfo.l_whence = SEEK_SET;
31862  lockInfo.l_type = F_RDLCK;
31863  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
31864    return &posixIoMethods;
31865  }else{
31866    return &semIoMethods;
31867  }
31868}
31869static const sqlite3_io_methods
31870  *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
31871
31872#endif /* OS_VXWORKS */
31873
31874/*
31875** An abstract type for a pointer to an IO method finder function:
31876*/
31877typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
31878
31879
31880/****************************************************************************
31881**************************** sqlite3_vfs methods ****************************
31882**
31883** This division contains the implementation of methods on the
31884** sqlite3_vfs object.
31885*/
31886
31887/*
31888** Initialize the contents of the unixFile structure pointed to by pId.
31889*/
31890static int fillInUnixFile(
31891  sqlite3_vfs *pVfs,      /* Pointer to vfs object */
31892  int h,                  /* Open file descriptor of file being opened */
31893  sqlite3_file *pId,      /* Write to the unixFile structure here */
31894  const char *zFilename,  /* Name of the file being opened */
31895  int ctrlFlags           /* Zero or more UNIXFILE_* values */
31896){
31897  const sqlite3_io_methods *pLockingStyle;
31898  unixFile *pNew = (unixFile *)pId;
31899  int rc = SQLITE_OK;
31900
31901  assert( pNew->pInode==NULL );
31902
31903  /* Usually the path zFilename should not be a relative pathname. The
31904  ** exception is when opening the proxy "conch" file in builds that
31905  ** include the special Apple locking styles.
31906  */
31907#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31908  assert( zFilename==0 || zFilename[0]=='/'
31909    || pVfs->pAppData==(void*)&autolockIoFinder );
31910#else
31911  assert( zFilename==0 || zFilename[0]=='/' );
31912#endif
31913
31914  /* No locking occurs in temporary files */
31915  assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
31916
31917  OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
31918  pNew->h = h;
31919  pNew->pVfs = pVfs;
31920  pNew->zPath = zFilename;
31921  pNew->ctrlFlags = (u8)ctrlFlags;
31922#if SQLITE_MAX_MMAP_SIZE>0
31923  pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
31924#endif
31925  if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
31926                           "psow", SQLITE_POWERSAFE_OVERWRITE) ){
31927    pNew->ctrlFlags |= UNIXFILE_PSOW;
31928  }
31929  if( strcmp(pVfs->zName,"unix-excl")==0 ){
31930    pNew->ctrlFlags |= UNIXFILE_EXCL;
31931  }
31932
31933#if OS_VXWORKS
31934  pNew->pId = vxworksFindFileId(zFilename);
31935  if( pNew->pId==0 ){
31936    ctrlFlags |= UNIXFILE_NOLOCK;
31937    rc = SQLITE_NOMEM;
31938  }
31939#endif
31940
31941  if( ctrlFlags & UNIXFILE_NOLOCK ){
31942    pLockingStyle = &nolockIoMethods;
31943  }else{
31944    pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
31945#if SQLITE_ENABLE_LOCKING_STYLE
31946    /* Cache zFilename in the locking context (AFP and dotlock override) for
31947    ** proxyLock activation is possible (remote proxy is based on db name)
31948    ** zFilename remains valid until file is closed, to support */
31949    pNew->lockingContext = (void*)zFilename;
31950#endif
31951  }
31952
31953  if( pLockingStyle == &posixIoMethods
31954#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31955    || pLockingStyle == &nfsIoMethods
31956#endif
31957  ){
31958    unixEnterMutex();
31959    rc = findInodeInfo(pNew, &pNew->pInode);
31960    if( rc!=SQLITE_OK ){
31961      /* If an error occurred in findInodeInfo(), close the file descriptor
31962      ** immediately, before releasing the mutex. findInodeInfo() may fail
31963      ** in two scenarios:
31964      **
31965      **   (a) A call to fstat() failed.
31966      **   (b) A malloc failed.
31967      **
31968      ** Scenario (b) may only occur if the process is holding no other
31969      ** file descriptors open on the same file. If there were other file
31970      ** descriptors on this file, then no malloc would be required by
31971      ** findInodeInfo(). If this is the case, it is quite safe to close
31972      ** handle h - as it is guaranteed that no posix locks will be released
31973      ** by doing so.
31974      **
31975      ** If scenario (a) caused the error then things are not so safe. The
31976      ** implicit assumption here is that if fstat() fails, things are in
31977      ** such bad shape that dropping a lock or two doesn't matter much.
31978      */
31979      robust_close(pNew, h, __LINE__);
31980      h = -1;
31981    }
31982    unixLeaveMutex();
31983  }
31984
31985#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
31986  else if( pLockingStyle == &afpIoMethods ){
31987    /* AFP locking uses the file path so it needs to be included in
31988    ** the afpLockingContext.
31989    */
31990    afpLockingContext *pCtx;
31991    pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
31992    if( pCtx==0 ){
31993      rc = SQLITE_NOMEM;
31994    }else{
31995      /* NB: zFilename exists and remains valid until the file is closed
31996      ** according to requirement F11141.  So we do not need to make a
31997      ** copy of the filename. */
31998      pCtx->dbPath = zFilename;
31999      pCtx->reserved = 0;
32000      srandomdev();
32001      unixEnterMutex();
32002      rc = findInodeInfo(pNew, &pNew->pInode);
32003      if( rc!=SQLITE_OK ){
32004        sqlite3_free(pNew->lockingContext);
32005        robust_close(pNew, h, __LINE__);
32006        h = -1;
32007      }
32008      unixLeaveMutex();
32009    }
32010  }
32011#endif
32012
32013  else if( pLockingStyle == &dotlockIoMethods ){
32014    /* Dotfile locking uses the file path so it needs to be included in
32015    ** the dotlockLockingContext
32016    */
32017    char *zLockFile;
32018    int nFilename;
32019    assert( zFilename!=0 );
32020    nFilename = (int)strlen(zFilename) + 6;
32021    zLockFile = (char *)sqlite3_malloc64(nFilename);
32022    if( zLockFile==0 ){
32023      rc = SQLITE_NOMEM;
32024    }else{
32025      sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
32026    }
32027    pNew->lockingContext = zLockFile;
32028  }
32029
32030#if OS_VXWORKS
32031  else if( pLockingStyle == &semIoMethods ){
32032    /* Named semaphore locking uses the file path so it needs to be
32033    ** included in the semLockingContext
32034    */
32035    unixEnterMutex();
32036    rc = findInodeInfo(pNew, &pNew->pInode);
32037    if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
32038      char *zSemName = pNew->pInode->aSemName;
32039      int n;
32040      sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
32041                       pNew->pId->zCanonicalName);
32042      for( n=1; zSemName[n]; n++ )
32043        if( zSemName[n]=='/' ) zSemName[n] = '_';
32044      pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
32045      if( pNew->pInode->pSem == SEM_FAILED ){
32046        rc = SQLITE_NOMEM;
32047        pNew->pInode->aSemName[0] = '\0';
32048      }
32049    }
32050    unixLeaveMutex();
32051  }
32052#endif
32053
32054  storeLastErrno(pNew, 0);
32055#if OS_VXWORKS
32056  if( rc!=SQLITE_OK ){
32057    if( h>=0 ) robust_close(pNew, h, __LINE__);
32058    h = -1;
32059    osUnlink(zFilename);
32060    pNew->ctrlFlags |= UNIXFILE_DELETE;
32061  }
32062#endif
32063  if( rc!=SQLITE_OK ){
32064    if( h>=0 ) robust_close(pNew, h, __LINE__);
32065  }else{
32066    pNew->pMethod = pLockingStyle;
32067    OpenCounter(+1);
32068    verifyDbFile(pNew);
32069  }
32070  return rc;
32071}
32072
32073/*
32074** Return the name of a directory in which to put temporary files.
32075** If no suitable temporary file directory can be found, return NULL.
32076*/
32077static const char *unixTempFileDir(void){
32078  static const char *azDirs[] = {
32079     0,
32080     0,
32081     0,
32082     "/var/tmp",
32083     "/usr/tmp",
32084     "/tmp",
32085     0        /* List terminator */
32086  };
32087  unsigned int i;
32088  struct stat buf;
32089  const char *zDir = 0;
32090
32091  azDirs[0] = sqlite3_temp_directory;
32092  if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
32093  if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
32094  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
32095    if( zDir==0 ) continue;
32096    if( osStat(zDir, &buf) ) continue;
32097    if( !S_ISDIR(buf.st_mode) ) continue;
32098    if( osAccess(zDir, 07) ) continue;
32099    break;
32100  }
32101  return zDir;
32102}
32103
32104/*
32105** Create a temporary file name in zBuf.  zBuf must be allocated
32106** by the calling process and must be big enough to hold at least
32107** pVfs->mxPathname bytes.
32108*/
32109static int unixGetTempname(int nBuf, char *zBuf){
32110  static const unsigned char zChars[] =
32111    "abcdefghijklmnopqrstuvwxyz"
32112    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
32113    "0123456789";
32114  unsigned int i, j;
32115  const char *zDir;
32116
32117  /* It's odd to simulate an io-error here, but really this is just
32118  ** using the io-error infrastructure to test that SQLite handles this
32119  ** function failing.
32120  */
32121  SimulateIOError( return SQLITE_IOERR );
32122
32123  zDir = unixTempFileDir();
32124  if( zDir==0 ) zDir = ".";
32125
32126  /* Check that the output buffer is large enough for the temporary file
32127  ** name. If it is not, return SQLITE_ERROR.
32128  */
32129  if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
32130    return SQLITE_ERROR;
32131  }
32132
32133  do{
32134    sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
32135    j = (int)strlen(zBuf);
32136    sqlite3_randomness(15, &zBuf[j]);
32137    for(i=0; i<15; i++, j++){
32138      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
32139    }
32140    zBuf[j] = 0;
32141    zBuf[j+1] = 0;
32142  }while( osAccess(zBuf,0)==0 );
32143  return SQLITE_OK;
32144}
32145
32146#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
32147/*
32148** Routine to transform a unixFile into a proxy-locking unixFile.
32149** Implementation in the proxy-lock division, but used by unixOpen()
32150** if SQLITE_PREFER_PROXY_LOCKING is defined.
32151*/
32152static int proxyTransformUnixFile(unixFile*, const char*);
32153#endif
32154
32155/*
32156** Search for an unused file descriptor that was opened on the database
32157** file (not a journal or master-journal file) identified by pathname
32158** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
32159** argument to this function.
32160**
32161** Such a file descriptor may exist if a database connection was closed
32162** but the associated file descriptor could not be closed because some
32163** other file descriptor open on the same file is holding a file-lock.
32164** Refer to comments in the unixClose() function and the lengthy comment
32165** describing "Posix Advisory Locking" at the start of this file for
32166** further details. Also, ticket #4018.
32167**
32168** If a suitable file descriptor is found, then it is returned. If no
32169** such file descriptor is located, -1 is returned.
32170*/
32171static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
32172  UnixUnusedFd *pUnused = 0;
32173
32174  /* Do not search for an unused file descriptor on vxworks. Not because
32175  ** vxworks would not benefit from the change (it might, we're not sure),
32176  ** but because no way to test it is currently available. It is better
32177  ** not to risk breaking vxworks support for the sake of such an obscure
32178  ** feature.  */
32179#if !OS_VXWORKS
32180  struct stat sStat;                   /* Results of stat() call */
32181
32182  /* A stat() call may fail for various reasons. If this happens, it is
32183  ** almost certain that an open() call on the same path will also fail.
32184  ** For this reason, if an error occurs in the stat() call here, it is
32185  ** ignored and -1 is returned. The caller will try to open a new file
32186  ** descriptor on the same path, fail, and return an error to SQLite.
32187  **
32188  ** Even if a subsequent open() call does succeed, the consequences of
32189  ** not searching for a reusable file descriptor are not dire.  */
32190  if( 0==osStat(zPath, &sStat) ){
32191    unixInodeInfo *pInode;
32192
32193    unixEnterMutex();
32194    pInode = inodeList;
32195    while( pInode && (pInode->fileId.dev!=sStat.st_dev
32196                     || pInode->fileId.ino!=sStat.st_ino) ){
32197       pInode = pInode->pNext;
32198    }
32199    if( pInode ){
32200      UnixUnusedFd **pp;
32201      for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
32202      pUnused = *pp;
32203      if( pUnused ){
32204        *pp = pUnused->pNext;
32205      }
32206    }
32207    unixLeaveMutex();
32208  }
32209#endif    /* if !OS_VXWORKS */
32210  return pUnused;
32211}
32212
32213/*
32214** This function is called by unixOpen() to determine the unix permissions
32215** to create new files with. If no error occurs, then SQLITE_OK is returned
32216** and a value suitable for passing as the third argument to open(2) is
32217** written to *pMode. If an IO error occurs, an SQLite error code is
32218** returned and the value of *pMode is not modified.
32219**
32220** In most cases, this routine sets *pMode to 0, which will become
32221** an indication to robust_open() to create the file using
32222** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
32223** But if the file being opened is a WAL or regular journal file, then
32224** this function queries the file-system for the permissions on the
32225** corresponding database file and sets *pMode to this value. Whenever
32226** possible, WAL and journal files are created using the same permissions
32227** as the associated database file.
32228**
32229** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
32230** original filename is unavailable.  But 8_3_NAMES is only used for
32231** FAT filesystems and permissions do not matter there, so just use
32232** the default permissions.
32233*/
32234static int findCreateFileMode(
32235  const char *zPath,              /* Path of file (possibly) being created */
32236  int flags,                      /* Flags passed as 4th argument to xOpen() */
32237  mode_t *pMode,                  /* OUT: Permissions to open file with */
32238  uid_t *pUid,                    /* OUT: uid to set on the file */
32239  gid_t *pGid                     /* OUT: gid to set on the file */
32240){
32241  int rc = SQLITE_OK;             /* Return Code */
32242  *pMode = 0;
32243  *pUid = 0;
32244  *pGid = 0;
32245  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
32246    char zDb[MAX_PATHNAME+1];     /* Database file path */
32247    int nDb;                      /* Number of valid bytes in zDb */
32248    struct stat sStat;            /* Output of stat() on database file */
32249
32250    /* zPath is a path to a WAL or journal file. The following block derives
32251    ** the path to the associated database file from zPath. This block handles
32252    ** the following naming conventions:
32253    **
32254    **   "<path to db>-journal"
32255    **   "<path to db>-wal"
32256    **   "<path to db>-journalNN"
32257    **   "<path to db>-walNN"
32258    **
32259    ** where NN is a decimal number. The NN naming schemes are
32260    ** used by the test_multiplex.c module.
32261    */
32262    nDb = sqlite3Strlen30(zPath) - 1;
32263#ifdef SQLITE_ENABLE_8_3_NAMES
32264    while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
32265    if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
32266#else
32267    while( zPath[nDb]!='-' ){
32268      assert( nDb>0 );
32269      assert( zPath[nDb]!='\n' );
32270      nDb--;
32271    }
32272#endif
32273    memcpy(zDb, zPath, nDb);
32274    zDb[nDb] = '\0';
32275
32276    if( 0==osStat(zDb, &sStat) ){
32277      *pMode = sStat.st_mode & 0777;
32278      *pUid = sStat.st_uid;
32279      *pGid = sStat.st_gid;
32280    }else{
32281      rc = unixLogError(SQLITE_IOERR_FSTAT, "stat", zDb);
32282    }
32283  }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
32284    *pMode = 0600;
32285  }
32286  return rc;
32287}
32288
32289/*
32290** Open the file zPath.
32291**
32292** Previously, the SQLite OS layer used three functions in place of this
32293** one:
32294**
32295**     sqlite3OsOpenReadWrite();
32296**     sqlite3OsOpenReadOnly();
32297**     sqlite3OsOpenExclusive();
32298**
32299** These calls correspond to the following combinations of flags:
32300**
32301**     ReadWrite() ->     (READWRITE | CREATE)
32302**     ReadOnly()  ->     (READONLY)
32303**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
32304**
32305** The old OpenExclusive() accepted a boolean argument - "delFlag". If
32306** true, the file was configured to be automatically deleted when the
32307** file handle closed. To achieve the same effect using this new
32308** interface, add the DELETEONCLOSE flag to those specified above for
32309** OpenExclusive().
32310*/
32311static int unixOpen(
32312  sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
32313  const char *zPath,           /* Pathname of file to be opened */
32314  sqlite3_file *pFile,         /* The file descriptor to be filled in */
32315  int flags,                   /* Input flags to control the opening */
32316  int *pOutFlags               /* Output flags returned to SQLite core */
32317){
32318  unixFile *p = (unixFile *)pFile;
32319  int fd = -1;                   /* File descriptor returned by open() */
32320  int openFlags = 0;             /* Flags to pass to open() */
32321  int eType = flags&0xFFFFFF00;  /* Type of file to open */
32322  int noLock;                    /* True to omit locking primitives */
32323  int rc = SQLITE_OK;            /* Function Return Code */
32324  int ctrlFlags = 0;             /* UNIXFILE_* flags */
32325
32326  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
32327  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
32328  int isCreate     = (flags & SQLITE_OPEN_CREATE);
32329  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
32330  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
32331#if SQLITE_ENABLE_LOCKING_STYLE
32332  int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
32333#endif
32334#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
32335  struct statfs fsInfo;
32336#endif
32337
32338  /* If creating a master or main-file journal, this function will open
32339  ** a file-descriptor on the directory too. The first time unixSync()
32340  ** is called the directory file descriptor will be fsync()ed and close()d.
32341  */
32342  int syncDir = (isCreate && (
32343        eType==SQLITE_OPEN_MASTER_JOURNAL
32344     || eType==SQLITE_OPEN_MAIN_JOURNAL
32345     || eType==SQLITE_OPEN_WAL
32346  ));
32347
32348  /* If argument zPath is a NULL pointer, this function is required to open
32349  ** a temporary file. Use this buffer to store the file name in.
32350  */
32351  char zTmpname[MAX_PATHNAME+2];
32352  const char *zName = zPath;
32353
32354  /* Check the following statements are true:
32355  **
32356  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
32357  **   (b) if CREATE is set, then READWRITE must also be set, and
32358  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
32359  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
32360  */
32361  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
32362  assert(isCreate==0 || isReadWrite);
32363  assert(isExclusive==0 || isCreate);
32364  assert(isDelete==0 || isCreate);
32365
32366  /* The main DB, main journal, WAL file and master journal are never
32367  ** automatically deleted. Nor are they ever temporary files.  */
32368  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
32369  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
32370  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
32371  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
32372
32373  /* Assert that the upper layer has set one of the "file-type" flags. */
32374  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
32375       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
32376       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
32377       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
32378  );
32379
32380  /* Detect a pid change and reset the PRNG.  There is a race condition
32381  ** here such that two or more threads all trying to open databases at
32382  ** the same instant might all reset the PRNG.  But multiple resets
32383  ** are harmless.
32384  */
32385  if( randomnessPid!=osGetpid(0) ){
32386    randomnessPid = osGetpid(0);
32387    sqlite3_randomness(0,0);
32388  }
32389
32390  memset(p, 0, sizeof(unixFile));
32391
32392  if( eType==SQLITE_OPEN_MAIN_DB ){
32393    UnixUnusedFd *pUnused;
32394    pUnused = findReusableFd(zName, flags);
32395    if( pUnused ){
32396      fd = pUnused->fd;
32397    }else{
32398      pUnused = sqlite3_malloc64(sizeof(*pUnused));
32399      if( !pUnused ){
32400        return SQLITE_NOMEM;
32401      }
32402    }
32403    p->pUnused = pUnused;
32404
32405    /* Database filenames are double-zero terminated if they are not
32406    ** URIs with parameters.  Hence, they can always be passed into
32407    ** sqlite3_uri_parameter(). */
32408    assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
32409
32410  }else if( !zName ){
32411    /* If zName is NULL, the upper layer is requesting a temp file. */
32412    assert(isDelete && !syncDir);
32413    rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
32414    if( rc!=SQLITE_OK ){
32415      return rc;
32416    }
32417    zName = zTmpname;
32418
32419    /* Generated temporary filenames are always double-zero terminated
32420    ** for use by sqlite3_uri_parameter(). */
32421    assert( zName[strlen(zName)+1]==0 );
32422  }
32423
32424  /* Determine the value of the flags parameter passed to POSIX function
32425  ** open(). These must be calculated even if open() is not called, as
32426  ** they may be stored as part of the file handle and used by the
32427  ** 'conch file' locking functions later on.  */
32428  if( isReadonly )  openFlags |= O_RDONLY;
32429  if( isReadWrite ) openFlags |= O_RDWR;
32430  if( isCreate )    openFlags |= O_CREAT;
32431  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
32432  openFlags |= (O_LARGEFILE|O_BINARY);
32433
32434  if( fd<0 ){
32435    mode_t openMode;              /* Permissions to create file with */
32436    uid_t uid;                    /* Userid for the file */
32437    gid_t gid;                    /* Groupid for the file */
32438    rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
32439    if( rc!=SQLITE_OK ){
32440      assert( !p->pUnused );
32441      assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
32442      return rc;
32443    }
32444    fd = robust_open(zName, openFlags, openMode);
32445    OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
32446    if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
32447      /* Failed to open the file for read/write access. Try read-only. */
32448      flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
32449      openFlags &= ~(O_RDWR|O_CREAT);
32450      flags |= SQLITE_OPEN_READONLY;
32451      openFlags |= O_RDONLY;
32452      isReadonly = 1;
32453      fd = robust_open(zName, openFlags, openMode);
32454    }
32455    if( fd<0 ){
32456      rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
32457      goto open_finished;
32458    }
32459
32460    /* If this process is running as root and if creating a new rollback
32461    ** journal or WAL file, set the ownership of the journal or WAL to be
32462    ** the same as the original database.
32463    */
32464    if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
32465      osFchown(fd, uid, gid);
32466    }
32467  }
32468  assert( fd>=0 );
32469  if( pOutFlags ){
32470    *pOutFlags = flags;
32471  }
32472
32473  if( p->pUnused ){
32474    p->pUnused->fd = fd;
32475    p->pUnused->flags = flags;
32476  }
32477
32478  if( isDelete ){
32479#if OS_VXWORKS
32480    zPath = zName;
32481#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
32482    zPath = sqlite3_mprintf("%s", zName);
32483    if( zPath==0 ){
32484      robust_close(p, fd, __LINE__);
32485      return SQLITE_NOMEM;
32486    }
32487#else
32488    osUnlink(zName);
32489#endif
32490  }
32491#if SQLITE_ENABLE_LOCKING_STYLE
32492  else{
32493    p->openFlags = openFlags;
32494  }
32495#endif
32496
32497  noLock = eType!=SQLITE_OPEN_MAIN_DB;
32498
32499
32500#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
32501  if( fstatfs(fd, &fsInfo) == -1 ){
32502    storeLastErrno(p, errno);
32503    robust_close(p, fd, __LINE__);
32504    return SQLITE_IOERR_ACCESS;
32505  }
32506  if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
32507    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
32508  }
32509  if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
32510    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
32511  }
32512#endif
32513
32514  /* Set up appropriate ctrlFlags */
32515  if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
32516  if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
32517  if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
32518  if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
32519  if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
32520
32521#if SQLITE_ENABLE_LOCKING_STYLE
32522#if SQLITE_PREFER_PROXY_LOCKING
32523  isAutoProxy = 1;
32524#endif
32525  if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
32526    char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
32527    int useProxy = 0;
32528
32529    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
32530    ** never use proxy, NULL means use proxy for non-local files only.  */
32531    if( envforce!=NULL ){
32532      useProxy = atoi(envforce)>0;
32533    }else{
32534      useProxy = !(fsInfo.f_flags&MNT_LOCAL);
32535    }
32536    if( useProxy ){
32537      rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
32538      if( rc==SQLITE_OK ){
32539        rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
32540        if( rc!=SQLITE_OK ){
32541          /* Use unixClose to clean up the resources added in fillInUnixFile
32542          ** and clear all the structure's references.  Specifically,
32543          ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
32544          */
32545          unixClose(pFile);
32546          return rc;
32547        }
32548      }
32549      goto open_finished;
32550    }
32551  }
32552#endif
32553
32554  rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
32555
32556open_finished:
32557  if( rc!=SQLITE_OK ){
32558    sqlite3_free(p->pUnused);
32559  }
32560  return rc;
32561}
32562
32563
32564/*
32565** Delete the file at zPath. If the dirSync argument is true, fsync()
32566** the directory after deleting the file.
32567*/
32568static int unixDelete(
32569  sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
32570  const char *zPath,        /* Name of file to be deleted */
32571  int dirSync               /* If true, fsync() directory after deleting file */
32572){
32573  int rc = SQLITE_OK;
32574  UNUSED_PARAMETER(NotUsed);
32575  SimulateIOError(return SQLITE_IOERR_DELETE);
32576  if( osUnlink(zPath)==(-1) ){
32577    if( errno==ENOENT
32578#if OS_VXWORKS
32579        || osAccess(zPath,0)!=0
32580#endif
32581    ){
32582      rc = SQLITE_IOERR_DELETE_NOENT;
32583    }else{
32584      rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
32585    }
32586    return rc;
32587  }
32588#ifndef SQLITE_DISABLE_DIRSYNC
32589  if( (dirSync & 1)!=0 ){
32590    int fd;
32591    rc = osOpenDirectory(zPath, &fd);
32592    if( rc==SQLITE_OK ){
32593#if OS_VXWORKS
32594      if( fsync(fd)==-1 )
32595#else
32596      if( fsync(fd) )
32597#endif
32598      {
32599        rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
32600      }
32601      robust_close(0, fd, __LINE__);
32602    }else if( rc==SQLITE_CANTOPEN ){
32603      rc = SQLITE_OK;
32604    }
32605  }
32606#endif
32607  return rc;
32608}
32609
32610/*
32611** Test the existence of or access permissions of file zPath. The
32612** test performed depends on the value of flags:
32613**
32614**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
32615**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
32616**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
32617**
32618** Otherwise return 0.
32619*/
32620static int unixAccess(
32621  sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
32622  const char *zPath,      /* Path of the file to examine */
32623  int flags,              /* What do we want to learn about the zPath file? */
32624  int *pResOut            /* Write result boolean here */
32625){
32626  int amode = 0;
32627  UNUSED_PARAMETER(NotUsed);
32628  SimulateIOError( return SQLITE_IOERR_ACCESS; );
32629  switch( flags ){
32630    case SQLITE_ACCESS_EXISTS:
32631      amode = F_OK;
32632      break;
32633    case SQLITE_ACCESS_READWRITE:
32634      amode = W_OK|R_OK;
32635      break;
32636    case SQLITE_ACCESS_READ:
32637      amode = R_OK;
32638      break;
32639
32640    default:
32641      assert(!"Invalid flags argument");
32642  }
32643  *pResOut = (osAccess(zPath, amode)==0);
32644  if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
32645    struct stat buf;
32646    if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
32647      *pResOut = 0;
32648    }
32649  }
32650  return SQLITE_OK;
32651}
32652
32653
32654/*
32655** Turn a relative pathname into a full pathname. The relative path
32656** is stored as a nul-terminated string in the buffer pointed to by
32657** zPath.
32658**
32659** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
32660** (in this case, MAX_PATHNAME bytes). The full-path is written to
32661** this buffer before returning.
32662*/
32663static int unixFullPathname(
32664  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
32665  const char *zPath,            /* Possibly relative input path */
32666  int nOut,                     /* Size of output buffer in bytes */
32667  char *zOut                    /* Output buffer */
32668){
32669
32670  /* It's odd to simulate an io-error here, but really this is just
32671  ** using the io-error infrastructure to test that SQLite handles this
32672  ** function failing. This function could fail if, for example, the
32673  ** current working directory has been unlinked.
32674  */
32675  SimulateIOError( return SQLITE_ERROR );
32676
32677  assert( pVfs->mxPathname==MAX_PATHNAME );
32678  UNUSED_PARAMETER(pVfs);
32679
32680  zOut[nOut-1] = '\0';
32681  if( zPath[0]=='/' ){
32682    sqlite3_snprintf(nOut, zOut, "%s", zPath);
32683  }else{
32684    int nCwd;
32685    if( osGetcwd(zOut, nOut-1)==0 ){
32686      return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
32687    }
32688    nCwd = (int)strlen(zOut);
32689    sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
32690  }
32691  return SQLITE_OK;
32692}
32693
32694
32695#ifndef SQLITE_OMIT_LOAD_EXTENSION
32696/*
32697** Interfaces for opening a shared library, finding entry points
32698** within the shared library, and closing the shared library.
32699*/
32700#include <dlfcn.h>
32701static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
32702  UNUSED_PARAMETER(NotUsed);
32703  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
32704}
32705
32706/*
32707** SQLite calls this function immediately after a call to unixDlSym() or
32708** unixDlOpen() fails (returns a null pointer). If a more detailed error
32709** message is available, it is written to zBufOut. If no error message
32710** is available, zBufOut is left unmodified and SQLite uses a default
32711** error message.
32712*/
32713static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
32714  const char *zErr;
32715  UNUSED_PARAMETER(NotUsed);
32716  unixEnterMutex();
32717  zErr = dlerror();
32718  if( zErr ){
32719    sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
32720  }
32721  unixLeaveMutex();
32722}
32723static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
32724  /*
32725  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
32726  ** cast into a pointer to a function.  And yet the library dlsym() routine
32727  ** returns a void* which is really a pointer to a function.  So how do we
32728  ** use dlsym() with -pedantic-errors?
32729  **
32730  ** Variable x below is defined to be a pointer to a function taking
32731  ** parameters void* and const char* and returning a pointer to a function.
32732  ** We initialize x by assigning it a pointer to the dlsym() function.
32733  ** (That assignment requires a cast.)  Then we call the function that
32734  ** x points to.
32735  **
32736  ** This work-around is unlikely to work correctly on any system where
32737  ** you really cannot cast a function pointer into void*.  But then, on the
32738  ** other hand, dlsym() will not work on such a system either, so we have
32739  ** not really lost anything.
32740  */
32741  void (*(*x)(void*,const char*))(void);
32742  UNUSED_PARAMETER(NotUsed);
32743  x = (void(*(*)(void*,const char*))(void))dlsym;
32744  return (*x)(p, zSym);
32745}
32746static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
32747  UNUSED_PARAMETER(NotUsed);
32748  dlclose(pHandle);
32749}
32750#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
32751  #define unixDlOpen  0
32752  #define unixDlError 0
32753  #define unixDlSym   0
32754  #define unixDlClose 0
32755#endif
32756
32757/*
32758** Write nBuf bytes of random data to the supplied buffer zBuf.
32759*/
32760static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
32761  UNUSED_PARAMETER(NotUsed);
32762  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
32763
32764  /* We have to initialize zBuf to prevent valgrind from reporting
32765  ** errors.  The reports issued by valgrind are incorrect - we would
32766  ** prefer that the randomness be increased by making use of the
32767  ** uninitialized space in zBuf - but valgrind errors tend to worry
32768  ** some users.  Rather than argue, it seems easier just to initialize
32769  ** the whole array and silence valgrind, even if that means less randomness
32770  ** in the random seed.
32771  **
32772  ** When testing, initializing zBuf[] to zero is all we do.  That means
32773  ** that we always use the same random number sequence.  This makes the
32774  ** tests repeatable.
32775  */
32776  memset(zBuf, 0, nBuf);
32777  randomnessPid = osGetpid(0);
32778#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
32779  {
32780    int fd, got;
32781    fd = robust_open("/dev/urandom", O_RDONLY, 0);
32782    if( fd<0 ){
32783      time_t t;
32784      time(&t);
32785      memcpy(zBuf, &t, sizeof(t));
32786      memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
32787      assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
32788      nBuf = sizeof(t) + sizeof(randomnessPid);
32789    }else{
32790      do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
32791      robust_close(0, fd, __LINE__);
32792    }
32793  }
32794#endif
32795  return nBuf;
32796}
32797
32798
32799/*
32800** Sleep for a little while.  Return the amount of time slept.
32801** The argument is the number of microseconds we want to sleep.
32802** The return value is the number of microseconds of sleep actually
32803** requested from the underlying operating system, a number which
32804** might be greater than or equal to the argument, but not less
32805** than the argument.
32806*/
32807static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
32808#if OS_VXWORKS
32809  struct timespec sp;
32810
32811  sp.tv_sec = microseconds / 1000000;
32812  sp.tv_nsec = (microseconds % 1000000) * 1000;
32813  nanosleep(&sp, NULL);
32814  UNUSED_PARAMETER(NotUsed);
32815  return microseconds;
32816#elif defined(HAVE_USLEEP) && HAVE_USLEEP
32817  usleep(microseconds);
32818  UNUSED_PARAMETER(NotUsed);
32819  return microseconds;
32820#else
32821  int seconds = (microseconds+999999)/1000000;
32822  sleep(seconds);
32823  UNUSED_PARAMETER(NotUsed);
32824  return seconds*1000000;
32825#endif
32826}
32827
32828/*
32829** The following variable, if set to a non-zero value, is interpreted as
32830** the number of seconds since 1970 and is used to set the result of
32831** sqlite3OsCurrentTime() during testing.
32832*/
32833#ifdef SQLITE_TEST
32834SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
32835#endif
32836
32837/*
32838** Find the current time (in Universal Coordinated Time).  Write into *piNow
32839** the current time and date as a Julian Day number times 86_400_000.  In
32840** other words, write into *piNow the number of milliseconds since the Julian
32841** epoch of noon in Greenwich on November 24, 4714 B.C according to the
32842** proleptic Gregorian calendar.
32843**
32844** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
32845** cannot be found.
32846*/
32847static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
32848  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
32849  int rc = SQLITE_OK;
32850#if defined(NO_GETTOD)
32851  time_t t;
32852  time(&t);
32853  *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
32854#elif OS_VXWORKS
32855  struct timespec sNow;
32856  clock_gettime(CLOCK_REALTIME, &sNow);
32857  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
32858#else
32859  struct timeval sNow;
32860  if( gettimeofday(&sNow, 0)==0 ){
32861    *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
32862  }else{
32863    rc = SQLITE_ERROR;
32864  }
32865#endif
32866
32867#ifdef SQLITE_TEST
32868  if( sqlite3_current_time ){
32869    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
32870  }
32871#endif
32872  UNUSED_PARAMETER(NotUsed);
32873  return rc;
32874}
32875
32876/*
32877** Find the current time (in Universal Coordinated Time).  Write the
32878** current time and date as a Julian Day number into *prNow and
32879** return 0.  Return 1 if the time and date cannot be found.
32880*/
32881static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
32882  sqlite3_int64 i = 0;
32883  int rc;
32884  UNUSED_PARAMETER(NotUsed);
32885  rc = unixCurrentTimeInt64(0, &i);
32886  *prNow = i/86400000.0;
32887  return rc;
32888}
32889
32890/*
32891** We added the xGetLastError() method with the intention of providing
32892** better low-level error messages when operating-system problems come up
32893** during SQLite operation.  But so far, none of that has been implemented
32894** in the core.  So this routine is never called.  For now, it is merely
32895** a place-holder.
32896*/
32897static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
32898  UNUSED_PARAMETER(NotUsed);
32899  UNUSED_PARAMETER(NotUsed2);
32900  UNUSED_PARAMETER(NotUsed3);
32901  return 0;
32902}
32903
32904
32905/*
32906************************ End of sqlite3_vfs methods ***************************
32907******************************************************************************/
32908
32909/******************************************************************************
32910************************** Begin Proxy Locking ********************************
32911**
32912** Proxy locking is a "uber-locking-method" in this sense:  It uses the
32913** other locking methods on secondary lock files.  Proxy locking is a
32914** meta-layer over top of the primitive locking implemented above.  For
32915** this reason, the division that implements of proxy locking is deferred
32916** until late in the file (here) after all of the other I/O methods have
32917** been defined - so that the primitive locking methods are available
32918** as services to help with the implementation of proxy locking.
32919**
32920****
32921**
32922** The default locking schemes in SQLite use byte-range locks on the
32923** database file to coordinate safe, concurrent access by multiple readers
32924** and writers [http://sqlite.org/lockingv3.html].  The five file locking
32925** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
32926** as POSIX read & write locks over fixed set of locations (via fsctl),
32927** on AFP and SMB only exclusive byte-range locks are available via fsctl
32928** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
32929** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
32930** address in the shared range is taken for a SHARED lock, the entire
32931** shared range is taken for an EXCLUSIVE lock):
32932**
32933**      PENDING_BYTE        0x40000000
32934**      RESERVED_BYTE       0x40000001
32935**      SHARED_RANGE        0x40000002 -> 0x40000200
32936**
32937** This works well on the local file system, but shows a nearly 100x
32938** slowdown in read performance on AFP because the AFP client disables
32939** the read cache when byte-range locks are present.  Enabling the read
32940** cache exposes a cache coherency problem that is present on all OS X
32941** supported network file systems.  NFS and AFP both observe the
32942** close-to-open semantics for ensuring cache coherency
32943** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
32944** address the requirements for concurrent database access by multiple
32945** readers and writers
32946** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
32947**
32948** To address the performance and cache coherency issues, proxy file locking
32949** changes the way database access is controlled by limiting access to a
32950** single host at a time and moving file locks off of the database file
32951** and onto a proxy file on the local file system.
32952**
32953**
32954** Using proxy locks
32955** -----------------
32956**
32957** C APIs
32958**
32959**  sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
32960**                       <proxy_path> | ":auto:");
32961**  sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
32962**                       &<proxy_path>);
32963**
32964**
32965** SQL pragmas
32966**
32967**  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
32968**  PRAGMA [database.]lock_proxy_file
32969**
32970** Specifying ":auto:" means that if there is a conch file with a matching
32971** host ID in it, the proxy path in the conch file will be used, otherwise
32972** a proxy path based on the user's temp dir
32973** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
32974** actual proxy file name is generated from the name and path of the
32975** database file.  For example:
32976**
32977**       For database path "/Users/me/foo.db"
32978**       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
32979**
32980** Once a lock proxy is configured for a database connection, it can not
32981** be removed, however it may be switched to a different proxy path via
32982** the above APIs (assuming the conch file is not being held by another
32983** connection or process).
32984**
32985**
32986** How proxy locking works
32987** -----------------------
32988**
32989** Proxy file locking relies primarily on two new supporting files:
32990**
32991**   *  conch file to limit access to the database file to a single host
32992**      at a time
32993**
32994**   *  proxy file to act as a proxy for the advisory locks normally
32995**      taken on the database
32996**
32997** The conch file - to use a proxy file, sqlite must first "hold the conch"
32998** by taking an sqlite-style shared lock on the conch file, reading the
32999** contents and comparing the host's unique host ID (see below) and lock
33000** proxy path against the values stored in the conch.  The conch file is
33001** stored in the same directory as the database file and the file name
33002** is patterned after the database file name as ".<databasename>-conch".
33003** If the conch file does not exist, or its contents do not match the
33004** host ID and/or proxy path, then the lock is escalated to an exclusive
33005** lock and the conch file contents is updated with the host ID and proxy
33006** path and the lock is downgraded to a shared lock again.  If the conch
33007** is held by another process (with a shared lock), the exclusive lock
33008** will fail and SQLITE_BUSY is returned.
33009**
33010** The proxy file - a single-byte file used for all advisory file locks
33011** normally taken on the database file.   This allows for safe sharing
33012** of the database file for multiple readers and writers on the same
33013** host (the conch ensures that they all use the same local lock file).
33014**
33015** Requesting the lock proxy does not immediately take the conch, it is
33016** only taken when the first request to lock database file is made.
33017** This matches the semantics of the traditional locking behavior, where
33018** opening a connection to a database file does not take a lock on it.
33019** The shared lock and an open file descriptor are maintained until
33020** the connection to the database is closed.
33021**
33022** The proxy file and the lock file are never deleted so they only need
33023** to be created the first time they are used.
33024**
33025** Configuration options
33026** ---------------------
33027**
33028**  SQLITE_PREFER_PROXY_LOCKING
33029**
33030**       Database files accessed on non-local file systems are
33031**       automatically configured for proxy locking, lock files are
33032**       named automatically using the same logic as
33033**       PRAGMA lock_proxy_file=":auto:"
33034**
33035**  SQLITE_PROXY_DEBUG
33036**
33037**       Enables the logging of error messages during host id file
33038**       retrieval and creation
33039**
33040**  LOCKPROXYDIR
33041**
33042**       Overrides the default directory used for lock proxy files that
33043**       are named automatically via the ":auto:" setting
33044**
33045**  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
33046**
33047**       Permissions to use when creating a directory for storing the
33048**       lock proxy files, only used when LOCKPROXYDIR is not set.
33049**
33050**
33051** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
33052** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
33053** force proxy locking to be used for every database file opened, and 0
33054** will force automatic proxy locking to be disabled for all database
33055** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
33056** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
33057*/
33058
33059/*
33060** Proxy locking is only available on MacOSX
33061*/
33062#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
33063
33064/*
33065** The proxyLockingContext has the path and file structures for the remote
33066** and local proxy files in it
33067*/
33068typedef struct proxyLockingContext proxyLockingContext;
33069struct proxyLockingContext {
33070  unixFile *conchFile;         /* Open conch file */
33071  char *conchFilePath;         /* Name of the conch file */
33072  unixFile *lockProxy;         /* Open proxy lock file */
33073  char *lockProxyPath;         /* Name of the proxy lock file */
33074  char *dbPath;                /* Name of the open file */
33075  int conchHeld;               /* 1 if the conch is held, -1 if lockless */
33076  int nFails;                  /* Number of conch taking failures */
33077  void *oldLockingContext;     /* Original lockingcontext to restore on close */
33078  sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
33079};
33080
33081/*
33082** The proxy lock file path for the database at dbPath is written into lPath,
33083** which must point to valid, writable memory large enough for a maxLen length
33084** file path.
33085*/
33086static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
33087  int len;
33088  int dbLen;
33089  int i;
33090
33091#ifdef LOCKPROXYDIR
33092  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
33093#else
33094# ifdef _CS_DARWIN_USER_TEMP_DIR
33095  {
33096    if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
33097      OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
33098               lPath, errno, osGetpid(0)));
33099      return SQLITE_IOERR_LOCK;
33100    }
33101    len = strlcat(lPath, "sqliteplocks", maxLen);
33102  }
33103# else
33104  len = strlcpy(lPath, "/tmp/", maxLen);
33105# endif
33106#endif
33107
33108  if( lPath[len-1]!='/' ){
33109    len = strlcat(lPath, "/", maxLen);
33110  }
33111
33112  /* transform the db path to a unique cache name */
33113  dbLen = (int)strlen(dbPath);
33114  for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
33115    char c = dbPath[i];
33116    lPath[i+len] = (c=='/')?'_':c;
33117  }
33118  lPath[i+len]='\0';
33119  strlcat(lPath, ":auto:", maxLen);
33120  OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
33121  return SQLITE_OK;
33122}
33123
33124/*
33125 ** Creates the lock file and any missing directories in lockPath
33126 */
33127static int proxyCreateLockPath(const char *lockPath){
33128  int i, len;
33129  char buf[MAXPATHLEN];
33130  int start = 0;
33131
33132  assert(lockPath!=NULL);
33133  /* try to create all the intermediate directories */
33134  len = (int)strlen(lockPath);
33135  buf[0] = lockPath[0];
33136  for( i=1; i<len; i++ ){
33137    if( lockPath[i] == '/' && (i - start > 0) ){
33138      /* only mkdir if leaf dir != "." or "/" or ".." */
33139      if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
33140         || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
33141        buf[i]='\0';
33142        if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
33143          int err=errno;
33144          if( err!=EEXIST ) {
33145            OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
33146                     "'%s' proxy lock path=%s pid=%d\n",
33147                     buf, strerror(err), lockPath, osGetpid(0)));
33148            return err;
33149          }
33150        }
33151      }
33152      start=i+1;
33153    }
33154    buf[i] = lockPath[i];
33155  }
33156  OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, osGetpid(0)));
33157  return 0;
33158}
33159
33160/*
33161** Create a new VFS file descriptor (stored in memory obtained from
33162** sqlite3_malloc) and open the file named "path" in the file descriptor.
33163**
33164** The caller is responsible not only for closing the file descriptor
33165** but also for freeing the memory associated with the file descriptor.
33166*/
33167static int proxyCreateUnixFile(
33168    const char *path,        /* path for the new unixFile */
33169    unixFile **ppFile,       /* unixFile created and returned by ref */
33170    int islockfile           /* if non zero missing dirs will be created */
33171) {
33172  int fd = -1;
33173  unixFile *pNew;
33174  int rc = SQLITE_OK;
33175  int openFlags = O_RDWR | O_CREAT;
33176  sqlite3_vfs dummyVfs;
33177  int terrno = 0;
33178  UnixUnusedFd *pUnused = NULL;
33179
33180  /* 1. first try to open/create the file
33181  ** 2. if that fails, and this is a lock file (not-conch), try creating
33182  ** the parent directories and then try again.
33183  ** 3. if that fails, try to open the file read-only
33184  ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
33185  */
33186  pUnused = findReusableFd(path, openFlags);
33187  if( pUnused ){
33188    fd = pUnused->fd;
33189  }else{
33190    pUnused = sqlite3_malloc64(sizeof(*pUnused));
33191    if( !pUnused ){
33192      return SQLITE_NOMEM;
33193    }
33194  }
33195  if( fd<0 ){
33196    fd = robust_open(path, openFlags, 0);
33197    terrno = errno;
33198    if( fd<0 && errno==ENOENT && islockfile ){
33199      if( proxyCreateLockPath(path) == SQLITE_OK ){
33200        fd = robust_open(path, openFlags, 0);
33201      }
33202    }
33203  }
33204  if( fd<0 ){
33205    openFlags = O_RDONLY;
33206    fd = robust_open(path, openFlags, 0);
33207    terrno = errno;
33208  }
33209  if( fd<0 ){
33210    if( islockfile ){
33211      return SQLITE_BUSY;
33212    }
33213    switch (terrno) {
33214      case EACCES:
33215        return SQLITE_PERM;
33216      case EIO:
33217        return SQLITE_IOERR_LOCK; /* even though it is the conch */
33218      default:
33219        return SQLITE_CANTOPEN_BKPT;
33220    }
33221  }
33222
33223  pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
33224  if( pNew==NULL ){
33225    rc = SQLITE_NOMEM;
33226    goto end_create_proxy;
33227  }
33228  memset(pNew, 0, sizeof(unixFile));
33229  pNew->openFlags = openFlags;
33230  memset(&dummyVfs, 0, sizeof(dummyVfs));
33231  dummyVfs.pAppData = (void*)&autolockIoFinder;
33232  dummyVfs.zName = "dummy";
33233  pUnused->fd = fd;
33234  pUnused->flags = openFlags;
33235  pNew->pUnused = pUnused;
33236
33237  rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
33238  if( rc==SQLITE_OK ){
33239    *ppFile = pNew;
33240    return SQLITE_OK;
33241  }
33242end_create_proxy:
33243  robust_close(pNew, fd, __LINE__);
33244  sqlite3_free(pNew);
33245  sqlite3_free(pUnused);
33246  return rc;
33247}
33248
33249#ifdef SQLITE_TEST
33250/* simulate multiple hosts by creating unique hostid file paths */
33251SQLITE_API int sqlite3_hostid_num = 0;
33252#endif
33253
33254#define PROXY_HOSTIDLEN    16  /* conch file host id length */
33255
33256#ifdef HAVE_GETHOSTUUID
33257/* Not always defined in the headers as it ought to be */
33258extern int gethostuuid(uuid_t id, const struct timespec *wait);
33259#endif
33260
33261/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
33262** bytes of writable memory.
33263*/
33264static int proxyGetHostID(unsigned char *pHostID, int *pError){
33265  assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
33266  memset(pHostID, 0, PROXY_HOSTIDLEN);
33267#ifdef HAVE_GETHOSTUUID
33268  {
33269    struct timespec timeout = {1, 0}; /* 1 sec timeout */
33270    if( gethostuuid(pHostID, &timeout) ){
33271      int err = errno;
33272      if( pError ){
33273        *pError = err;
33274      }
33275      return SQLITE_IOERR;
33276    }
33277  }
33278#else
33279  UNUSED_PARAMETER(pError);
33280#endif
33281#ifdef SQLITE_TEST
33282  /* simulate multiple hosts by creating unique hostid file paths */
33283  if( sqlite3_hostid_num != 0){
33284    pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
33285  }
33286#endif
33287
33288  return SQLITE_OK;
33289}
33290
33291/* The conch file contains the header, host id and lock file path
33292 */
33293#define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
33294#define PROXY_HEADERLEN    1   /* conch file header length */
33295#define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
33296#define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
33297
33298/*
33299** Takes an open conch file, copies the contents to a new path and then moves
33300** it back.  The newly created file's file descriptor is assigned to the
33301** conch file structure and finally the original conch file descriptor is
33302** closed.  Returns zero if successful.
33303*/
33304static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
33305  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
33306  unixFile *conchFile = pCtx->conchFile;
33307  char tPath[MAXPATHLEN];
33308  char buf[PROXY_MAXCONCHLEN];
33309  char *cPath = pCtx->conchFilePath;
33310  size_t readLen = 0;
33311  size_t pathLen = 0;
33312  char errmsg[64] = "";
33313  int fd = -1;
33314  int rc = -1;
33315  UNUSED_PARAMETER(myHostID);
33316
33317  /* create a new path by replace the trailing '-conch' with '-break' */
33318  pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
33319  if( pathLen>MAXPATHLEN || pathLen<6 ||
33320     (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
33321    sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
33322    goto end_breaklock;
33323  }
33324  /* read the conch content */
33325  readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
33326  if( readLen<PROXY_PATHINDEX ){
33327    sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
33328    goto end_breaklock;
33329  }
33330  /* write it out to the temporary break file */
33331  fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
33332  if( fd<0 ){
33333    sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
33334    goto end_breaklock;
33335  }
33336  if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
33337    sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
33338    goto end_breaklock;
33339  }
33340  if( rename(tPath, cPath) ){
33341    sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
33342    goto end_breaklock;
33343  }
33344  rc = 0;
33345  fprintf(stderr, "broke stale lock on %s\n", cPath);
33346  robust_close(pFile, conchFile->h, __LINE__);
33347  conchFile->h = fd;
33348  conchFile->openFlags = O_RDWR | O_CREAT;
33349
33350end_breaklock:
33351  if( rc ){
33352    if( fd>=0 ){
33353      osUnlink(tPath);
33354      robust_close(pFile, fd, __LINE__);
33355    }
33356    fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
33357  }
33358  return rc;
33359}
33360
33361/* Take the requested lock on the conch file and break a stale lock if the
33362** host id matches.
33363*/
33364static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
33365  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
33366  unixFile *conchFile = pCtx->conchFile;
33367  int rc = SQLITE_OK;
33368  int nTries = 0;
33369  struct timespec conchModTime;
33370
33371  memset(&conchModTime, 0, sizeof(conchModTime));
33372  do {
33373    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
33374    nTries ++;
33375    if( rc==SQLITE_BUSY ){
33376      /* If the lock failed (busy):
33377       * 1st try: get the mod time of the conch, wait 0.5s and try again.
33378       * 2nd try: fail if the mod time changed or host id is different, wait
33379       *           10 sec and try again
33380       * 3rd try: break the lock unless the mod time has changed.
33381       */
33382      struct stat buf;
33383      if( osFstat(conchFile->h, &buf) ){
33384        storeLastErrno(pFile, errno);
33385        return SQLITE_IOERR_LOCK;
33386      }
33387
33388      if( nTries==1 ){
33389        conchModTime = buf.st_mtimespec;
33390        usleep(500000); /* wait 0.5 sec and try the lock again*/
33391        continue;
33392      }
33393
33394      assert( nTries>1 );
33395      if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
33396         conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
33397        return SQLITE_BUSY;
33398      }
33399
33400      if( nTries==2 ){
33401        char tBuf[PROXY_MAXCONCHLEN];
33402        int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
33403        if( len<0 ){
33404          storeLastErrno(pFile, errno);
33405          return SQLITE_IOERR_LOCK;
33406        }
33407        if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
33408          /* don't break the lock if the host id doesn't match */
33409          if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
33410            return SQLITE_BUSY;
33411          }
33412        }else{
33413          /* don't break the lock on short read or a version mismatch */
33414          return SQLITE_BUSY;
33415        }
33416        usleep(10000000); /* wait 10 sec and try the lock again */
33417        continue;
33418      }
33419
33420      assert( nTries==3 );
33421      if( 0==proxyBreakConchLock(pFile, myHostID) ){
33422        rc = SQLITE_OK;
33423        if( lockType==EXCLUSIVE_LOCK ){
33424          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
33425        }
33426        if( !rc ){
33427          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
33428        }
33429      }
33430    }
33431  } while( rc==SQLITE_BUSY && nTries<3 );
33432
33433  return rc;
33434}
33435
33436/* Takes the conch by taking a shared lock and read the contents conch, if
33437** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
33438** lockPath means that the lockPath in the conch file will be used if the
33439** host IDs match, or a new lock path will be generated automatically
33440** and written to the conch file.
33441*/
33442static int proxyTakeConch(unixFile *pFile){
33443  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
33444
33445  if( pCtx->conchHeld!=0 ){
33446    return SQLITE_OK;
33447  }else{
33448    unixFile *conchFile = pCtx->conchFile;
33449    uuid_t myHostID;
33450    int pError = 0;
33451    char readBuf[PROXY_MAXCONCHLEN];
33452    char lockPath[MAXPATHLEN];
33453    char *tempLockPath = NULL;
33454    int rc = SQLITE_OK;
33455    int createConch = 0;
33456    int hostIdMatch = 0;
33457    int readLen = 0;
33458    int tryOldLockPath = 0;
33459    int forceNewLockPath = 0;
33460
33461    OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
33462             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
33463             osGetpid(0)));
33464
33465    rc = proxyGetHostID(myHostID, &pError);
33466    if( (rc&0xff)==SQLITE_IOERR ){
33467      storeLastErrno(pFile, pError);
33468      goto end_takeconch;
33469    }
33470    rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
33471    if( rc!=SQLITE_OK ){
33472      goto end_takeconch;
33473    }
33474    /* read the existing conch file */
33475    readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
33476    if( readLen<0 ){
33477      /* I/O error: lastErrno set by seekAndRead */
33478      storeLastErrno(pFile, conchFile->lastErrno);
33479      rc = SQLITE_IOERR_READ;
33480      goto end_takeconch;
33481    }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
33482             readBuf[0]!=(char)PROXY_CONCHVERSION ){
33483      /* a short read or version format mismatch means we need to create a new
33484      ** conch file.
33485      */
33486      createConch = 1;
33487    }
33488    /* if the host id matches and the lock path already exists in the conch
33489    ** we'll try to use the path there, if we can't open that path, we'll
33490    ** retry with a new auto-generated path
33491    */
33492    do { /* in case we need to try again for an :auto: named lock file */
33493
33494      if( !createConch && !forceNewLockPath ){
33495        hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
33496                                  PROXY_HOSTIDLEN);
33497        /* if the conch has data compare the contents */
33498        if( !pCtx->lockProxyPath ){
33499          /* for auto-named local lock file, just check the host ID and we'll
33500           ** use the local lock file path that's already in there
33501           */
33502          if( hostIdMatch ){
33503            size_t pathLen = (readLen - PROXY_PATHINDEX);
33504
33505            if( pathLen>=MAXPATHLEN ){
33506              pathLen=MAXPATHLEN-1;
33507            }
33508            memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
33509            lockPath[pathLen] = 0;
33510            tempLockPath = lockPath;
33511            tryOldLockPath = 1;
33512            /* create a copy of the lock path if the conch is taken */
33513            goto end_takeconch;
33514          }
33515        }else if( hostIdMatch
33516               && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
33517                           readLen-PROXY_PATHINDEX)
33518        ){
33519          /* conch host and lock path match */
33520          goto end_takeconch;
33521        }
33522      }
33523
33524      /* if the conch isn't writable and doesn't match, we can't take it */
33525      if( (conchFile->openFlags&O_RDWR) == 0 ){
33526        rc = SQLITE_BUSY;
33527        goto end_takeconch;
33528      }
33529
33530      /* either the conch didn't match or we need to create a new one */
33531      if( !pCtx->lockProxyPath ){
33532        proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
33533        tempLockPath = lockPath;
33534        /* create a copy of the lock path _only_ if the conch is taken */
33535      }
33536
33537      /* update conch with host and path (this will fail if other process
33538      ** has a shared lock already), if the host id matches, use the big
33539      ** stick.
33540      */
33541      futimes(conchFile->h, NULL);
33542      if( hostIdMatch && !createConch ){
33543        if( conchFile->pInode && conchFile->pInode->nShared>1 ){
33544          /* We are trying for an exclusive lock but another thread in this
33545           ** same process is still holding a shared lock. */
33546          rc = SQLITE_BUSY;
33547        } else {
33548          rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
33549        }
33550      }else{
33551        rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
33552      }
33553      if( rc==SQLITE_OK ){
33554        char writeBuffer[PROXY_MAXCONCHLEN];
33555        int writeSize = 0;
33556
33557        writeBuffer[0] = (char)PROXY_CONCHVERSION;
33558        memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
33559        if( pCtx->lockProxyPath!=NULL ){
33560          strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
33561                  MAXPATHLEN);
33562        }else{
33563          strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
33564        }
33565        writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
33566        robust_ftruncate(conchFile->h, writeSize);
33567        rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
33568        fsync(conchFile->h);
33569        /* If we created a new conch file (not just updated the contents of a
33570         ** valid conch file), try to match the permissions of the database
33571         */
33572        if( rc==SQLITE_OK && createConch ){
33573          struct stat buf;
33574          int err = osFstat(pFile->h, &buf);
33575          if( err==0 ){
33576            mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
33577                                        S_IROTH|S_IWOTH);
33578            /* try to match the database file R/W permissions, ignore failure */
33579#ifndef SQLITE_PROXY_DEBUG
33580            osFchmod(conchFile->h, cmode);
33581#else
33582            do{
33583              rc = osFchmod(conchFile->h, cmode);
33584            }while( rc==(-1) && errno==EINTR );
33585            if( rc!=0 ){
33586              int code = errno;
33587              fprintf(stderr, "fchmod %o FAILED with %d %s\n",
33588                      cmode, code, strerror(code));
33589            } else {
33590              fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
33591            }
33592          }else{
33593            int code = errno;
33594            fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
33595                    err, code, strerror(code));
33596#endif
33597          }
33598        }
33599      }
33600      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
33601
33602    end_takeconch:
33603      OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
33604      if( rc==SQLITE_OK && pFile->openFlags ){
33605        int fd;
33606        if( pFile->h>=0 ){
33607          robust_close(pFile, pFile->h, __LINE__);
33608        }
33609        pFile->h = -1;
33610        fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
33611        OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
33612        if( fd>=0 ){
33613          pFile->h = fd;
33614        }else{
33615          rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
33616           during locking */
33617        }
33618      }
33619      if( rc==SQLITE_OK && !pCtx->lockProxy ){
33620        char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
33621        rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
33622        if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
33623          /* we couldn't create the proxy lock file with the old lock file path
33624           ** so try again via auto-naming
33625           */
33626          forceNewLockPath = 1;
33627          tryOldLockPath = 0;
33628          continue; /* go back to the do {} while start point, try again */
33629        }
33630      }
33631      if( rc==SQLITE_OK ){
33632        /* Need to make a copy of path if we extracted the value
33633         ** from the conch file or the path was allocated on the stack
33634         */
33635        if( tempLockPath ){
33636          pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
33637          if( !pCtx->lockProxyPath ){
33638            rc = SQLITE_NOMEM;
33639          }
33640        }
33641      }
33642      if( rc==SQLITE_OK ){
33643        pCtx->conchHeld = 1;
33644
33645        if( pCtx->lockProxy->pMethod == &afpIoMethods ){
33646          afpLockingContext *afpCtx;
33647          afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
33648          afpCtx->dbPath = pCtx->lockProxyPath;
33649        }
33650      } else {
33651        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
33652      }
33653      OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
33654               rc==SQLITE_OK?"ok":"failed"));
33655      return rc;
33656    } while (1); /* in case we need to retry the :auto: lock file -
33657                 ** we should never get here except via the 'continue' call. */
33658  }
33659}
33660
33661/*
33662** If pFile holds a lock on a conch file, then release that lock.
33663*/
33664static int proxyReleaseConch(unixFile *pFile){
33665  int rc = SQLITE_OK;         /* Subroutine return code */
33666  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
33667  unixFile *conchFile;        /* Name of the conch file */
33668
33669  pCtx = (proxyLockingContext *)pFile->lockingContext;
33670  conchFile = pCtx->conchFile;
33671  OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
33672           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
33673           osGetpid(0)));
33674  if( pCtx->conchHeld>0 ){
33675    rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
33676  }
33677  pCtx->conchHeld = 0;
33678  OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
33679           (rc==SQLITE_OK ? "ok" : "failed")));
33680  return rc;
33681}
33682
33683/*
33684** Given the name of a database file, compute the name of its conch file.
33685** Store the conch filename in memory obtained from sqlite3_malloc64().
33686** Make *pConchPath point to the new name.  Return SQLITE_OK on success
33687** or SQLITE_NOMEM if unable to obtain memory.
33688**
33689** The caller is responsible for ensuring that the allocated memory
33690** space is eventually freed.
33691**
33692** *pConchPath is set to NULL if a memory allocation error occurs.
33693*/
33694static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
33695  int i;                        /* Loop counter */
33696  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
33697  char *conchPath;              /* buffer in which to construct conch name */
33698
33699  /* Allocate space for the conch filename and initialize the name to
33700  ** the name of the original database file. */
33701  *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
33702  if( conchPath==0 ){
33703    return SQLITE_NOMEM;
33704  }
33705  memcpy(conchPath, dbPath, len+1);
33706
33707  /* now insert a "." before the last / character */
33708  for( i=(len-1); i>=0; i-- ){
33709    if( conchPath[i]=='/' ){
33710      i++;
33711      break;
33712    }
33713  }
33714  conchPath[i]='.';
33715  while ( i<len ){
33716    conchPath[i+1]=dbPath[i];
33717    i++;
33718  }
33719
33720  /* append the "-conch" suffix to the file */
33721  memcpy(&conchPath[i+1], "-conch", 7);
33722  assert( (int)strlen(conchPath) == len+7 );
33723
33724  return SQLITE_OK;
33725}
33726
33727
33728/* Takes a fully configured proxy locking-style unix file and switches
33729** the local lock file path
33730*/
33731static int switchLockProxyPath(unixFile *pFile, const char *path) {
33732  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
33733  char *oldPath = pCtx->lockProxyPath;
33734  int rc = SQLITE_OK;
33735
33736  if( pFile->eFileLock!=NO_LOCK ){
33737    return SQLITE_BUSY;
33738  }
33739
33740  /* nothing to do if the path is NULL, :auto: or matches the existing path */
33741  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
33742    (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
33743    return SQLITE_OK;
33744  }else{
33745    unixFile *lockProxy = pCtx->lockProxy;
33746    pCtx->lockProxy=NULL;
33747    pCtx->conchHeld = 0;
33748    if( lockProxy!=NULL ){
33749      rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
33750      if( rc ) return rc;
33751      sqlite3_free(lockProxy);
33752    }
33753    sqlite3_free(oldPath);
33754    pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
33755  }
33756
33757  return rc;
33758}
33759
33760/*
33761** pFile is a file that has been opened by a prior xOpen call.  dbPath
33762** is a string buffer at least MAXPATHLEN+1 characters in size.
33763**
33764** This routine find the filename associated with pFile and writes it
33765** int dbPath.
33766*/
33767static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
33768#if defined(__APPLE__)
33769  if( pFile->pMethod == &afpIoMethods ){
33770    /* afp style keeps a reference to the db path in the filePath field
33771    ** of the struct */
33772    assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
33773    strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
33774            MAXPATHLEN);
33775  } else
33776#endif
33777  if( pFile->pMethod == &dotlockIoMethods ){
33778    /* dot lock style uses the locking context to store the dot lock
33779    ** file path */
33780    int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
33781    memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
33782  }else{
33783    /* all other styles use the locking context to store the db file path */
33784    assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
33785    strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
33786  }
33787  return SQLITE_OK;
33788}
33789
33790/*
33791** Takes an already filled in unix file and alters it so all file locking
33792** will be performed on the local proxy lock file.  The following fields
33793** are preserved in the locking context so that they can be restored and
33794** the unix structure properly cleaned up at close time:
33795**  ->lockingContext
33796**  ->pMethod
33797*/
33798static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
33799  proxyLockingContext *pCtx;
33800  char dbPath[MAXPATHLEN+1];       /* Name of the database file */
33801  char *lockPath=NULL;
33802  int rc = SQLITE_OK;
33803
33804  if( pFile->eFileLock!=NO_LOCK ){
33805    return SQLITE_BUSY;
33806  }
33807  proxyGetDbPathForUnixFile(pFile, dbPath);
33808  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
33809    lockPath=NULL;
33810  }else{
33811    lockPath=(char *)path;
33812  }
33813
33814  OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
33815           (lockPath ? lockPath : ":auto:"), osGetpid(0)));
33816
33817  pCtx = sqlite3_malloc64( sizeof(*pCtx) );
33818  if( pCtx==0 ){
33819    return SQLITE_NOMEM;
33820  }
33821  memset(pCtx, 0, sizeof(*pCtx));
33822
33823  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
33824  if( rc==SQLITE_OK ){
33825    rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
33826    if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
33827      /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
33828      ** (c) the file system is read-only, then enable no-locking access.
33829      ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
33830      ** that openFlags will have only one of O_RDONLY or O_RDWR.
33831      */
33832      struct statfs fsInfo;
33833      struct stat conchInfo;
33834      int goLockless = 0;
33835
33836      if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
33837        int err = errno;
33838        if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
33839          goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
33840        }
33841      }
33842      if( goLockless ){
33843        pCtx->conchHeld = -1; /* read only FS/ lockless */
33844        rc = SQLITE_OK;
33845      }
33846    }
33847  }
33848  if( rc==SQLITE_OK && lockPath ){
33849    pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
33850  }
33851
33852  if( rc==SQLITE_OK ){
33853    pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
33854    if( pCtx->dbPath==NULL ){
33855      rc = SQLITE_NOMEM;
33856    }
33857  }
33858  if( rc==SQLITE_OK ){
33859    /* all memory is allocated, proxys are created and assigned,
33860    ** switch the locking context and pMethod then return.
33861    */
33862    pCtx->oldLockingContext = pFile->lockingContext;
33863    pFile->lockingContext = pCtx;
33864    pCtx->pOldMethod = pFile->pMethod;
33865    pFile->pMethod = &proxyIoMethods;
33866  }else{
33867    if( pCtx->conchFile ){
33868      pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
33869      sqlite3_free(pCtx->conchFile);
33870    }
33871    sqlite3DbFree(0, pCtx->lockProxyPath);
33872    sqlite3_free(pCtx->conchFilePath);
33873    sqlite3_free(pCtx);
33874  }
33875  OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
33876           (rc==SQLITE_OK ? "ok" : "failed")));
33877  return rc;
33878}
33879
33880
33881/*
33882** This routine handles sqlite3_file_control() calls that are specific
33883** to proxy locking.
33884*/
33885static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
33886  switch( op ){
33887    case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
33888      unixFile *pFile = (unixFile*)id;
33889      if( pFile->pMethod == &proxyIoMethods ){
33890        proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
33891        proxyTakeConch(pFile);
33892        if( pCtx->lockProxyPath ){
33893          *(const char **)pArg = pCtx->lockProxyPath;
33894        }else{
33895          *(const char **)pArg = ":auto: (not held)";
33896        }
33897      } else {
33898        *(const char **)pArg = NULL;
33899      }
33900      return SQLITE_OK;
33901    }
33902    case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
33903      unixFile *pFile = (unixFile*)id;
33904      int rc = SQLITE_OK;
33905      int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
33906      if( pArg==NULL || (const char *)pArg==0 ){
33907        if( isProxyStyle ){
33908          /* turn off proxy locking - not supported.  If support is added for
33909          ** switching proxy locking mode off then it will need to fail if
33910          ** the journal mode is WAL mode.
33911          */
33912          rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
33913        }else{
33914          /* turn off proxy locking - already off - NOOP */
33915          rc = SQLITE_OK;
33916        }
33917      }else{
33918        const char *proxyPath = (const char *)pArg;
33919        if( isProxyStyle ){
33920          proxyLockingContext *pCtx =
33921            (proxyLockingContext*)pFile->lockingContext;
33922          if( !strcmp(pArg, ":auto:")
33923           || (pCtx->lockProxyPath &&
33924               !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
33925          ){
33926            rc = SQLITE_OK;
33927          }else{
33928            rc = switchLockProxyPath(pFile, proxyPath);
33929          }
33930        }else{
33931          /* turn on proxy file locking */
33932          rc = proxyTransformUnixFile(pFile, proxyPath);
33933        }
33934      }
33935      return rc;
33936    }
33937    default: {
33938      assert( 0 );  /* The call assures that only valid opcodes are sent */
33939    }
33940  }
33941  /*NOTREACHED*/
33942  return SQLITE_ERROR;
33943}
33944
33945/*
33946** Within this division (the proxying locking implementation) the procedures
33947** above this point are all utilities.  The lock-related methods of the
33948** proxy-locking sqlite3_io_method object follow.
33949*/
33950
33951
33952/*
33953** This routine checks if there is a RESERVED lock held on the specified
33954** file by this or any other process. If such a lock is held, set *pResOut
33955** to a non-zero value otherwise *pResOut is set to zero.  The return value
33956** is set to SQLITE_OK unless an I/O error occurs during lock checking.
33957*/
33958static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
33959  unixFile *pFile = (unixFile*)id;
33960  int rc = proxyTakeConch(pFile);
33961  if( rc==SQLITE_OK ){
33962    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
33963    if( pCtx->conchHeld>0 ){
33964      unixFile *proxy = pCtx->lockProxy;
33965      return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
33966    }else{ /* conchHeld < 0 is lockless */
33967      pResOut=0;
33968    }
33969  }
33970  return rc;
33971}
33972
33973/*
33974** Lock the file with the lock specified by parameter eFileLock - one
33975** of the following:
33976**
33977**     (1) SHARED_LOCK
33978**     (2) RESERVED_LOCK
33979**     (3) PENDING_LOCK
33980**     (4) EXCLUSIVE_LOCK
33981**
33982** Sometimes when requesting one lock state, additional lock states
33983** are inserted in between.  The locking might fail on one of the later
33984** transitions leaving the lock state different from what it started but
33985** still short of its goal.  The following chart shows the allowed
33986** transitions and the inserted intermediate states:
33987**
33988**    UNLOCKED -> SHARED
33989**    SHARED -> RESERVED
33990**    SHARED -> (PENDING) -> EXCLUSIVE
33991**    RESERVED -> (PENDING) -> EXCLUSIVE
33992**    PENDING -> EXCLUSIVE
33993**
33994** This routine will only increase a lock.  Use the sqlite3OsUnlock()
33995** routine to lower a locking level.
33996*/
33997static int proxyLock(sqlite3_file *id, int eFileLock) {
33998  unixFile *pFile = (unixFile*)id;
33999  int rc = proxyTakeConch(pFile);
34000  if( rc==SQLITE_OK ){
34001    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
34002    if( pCtx->conchHeld>0 ){
34003      unixFile *proxy = pCtx->lockProxy;
34004      rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
34005      pFile->eFileLock = proxy->eFileLock;
34006    }else{
34007      /* conchHeld < 0 is lockless */
34008    }
34009  }
34010  return rc;
34011}
34012
34013
34014/*
34015** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
34016** must be either NO_LOCK or SHARED_LOCK.
34017**
34018** If the locking level of the file descriptor is already at or below
34019** the requested locking level, this routine is a no-op.
34020*/
34021static int proxyUnlock(sqlite3_file *id, int eFileLock) {
34022  unixFile *pFile = (unixFile*)id;
34023  int rc = proxyTakeConch(pFile);
34024  if( rc==SQLITE_OK ){
34025    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
34026    if( pCtx->conchHeld>0 ){
34027      unixFile *proxy = pCtx->lockProxy;
34028      rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
34029      pFile->eFileLock = proxy->eFileLock;
34030    }else{
34031      /* conchHeld < 0 is lockless */
34032    }
34033  }
34034  return rc;
34035}
34036
34037/*
34038** Close a file that uses proxy locks.
34039*/
34040static int proxyClose(sqlite3_file *id) {
34041  if( id ){
34042    unixFile *pFile = (unixFile*)id;
34043    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
34044    unixFile *lockProxy = pCtx->lockProxy;
34045    unixFile *conchFile = pCtx->conchFile;
34046    int rc = SQLITE_OK;
34047
34048    if( lockProxy ){
34049      rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
34050      if( rc ) return rc;
34051      rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
34052      if( rc ) return rc;
34053      sqlite3_free(lockProxy);
34054      pCtx->lockProxy = 0;
34055    }
34056    if( conchFile ){
34057      if( pCtx->conchHeld ){
34058        rc = proxyReleaseConch(pFile);
34059        if( rc ) return rc;
34060      }
34061      rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
34062      if( rc ) return rc;
34063      sqlite3_free(conchFile);
34064    }
34065    sqlite3DbFree(0, pCtx->lockProxyPath);
34066    sqlite3_free(pCtx->conchFilePath);
34067    sqlite3DbFree(0, pCtx->dbPath);
34068    /* restore the original locking context and pMethod then close it */
34069    pFile->lockingContext = pCtx->oldLockingContext;
34070    pFile->pMethod = pCtx->pOldMethod;
34071    sqlite3_free(pCtx);
34072    return pFile->pMethod->xClose(id);
34073  }
34074  return SQLITE_OK;
34075}
34076
34077
34078
34079#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
34080/*
34081** The proxy locking style is intended for use with AFP filesystems.
34082** And since AFP is only supported on MacOSX, the proxy locking is also
34083** restricted to MacOSX.
34084**
34085**
34086******************* End of the proxy lock implementation **********************
34087******************************************************************************/
34088
34089/*
34090** Initialize the operating system interface.
34091**
34092** This routine registers all VFS implementations for unix-like operating
34093** systems.  This routine, and the sqlite3_os_end() routine that follows,
34094** should be the only routines in this file that are visible from other
34095** files.
34096**
34097** This routine is called once during SQLite initialization and by a
34098** single thread.  The memory allocation and mutex subsystems have not
34099** necessarily been initialized when this routine is called, and so they
34100** should not be used.
34101*/
34102SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void){
34103  /*
34104  ** The following macro defines an initializer for an sqlite3_vfs object.
34105  ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
34106  ** to the "finder" function.  (pAppData is a pointer to a pointer because
34107  ** silly C90 rules prohibit a void* from being cast to a function pointer
34108  ** and so we have to go through the intermediate pointer to avoid problems
34109  ** when compiling with -pedantic-errors on GCC.)
34110  **
34111  ** The FINDER parameter to this macro is the name of the pointer to the
34112  ** finder-function.  The finder-function returns a pointer to the
34113  ** sqlite_io_methods object that implements the desired locking
34114  ** behaviors.  See the division above that contains the IOMETHODS
34115  ** macro for addition information on finder-functions.
34116  **
34117  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
34118  ** object.  But the "autolockIoFinder" available on MacOSX does a little
34119  ** more than that; it looks at the filesystem type that hosts the
34120  ** database file and tries to choose an locking method appropriate for
34121  ** that filesystem time.
34122  */
34123  #define UNIXVFS(VFSNAME, FINDER) {                        \
34124    3,                    /* iVersion */                    \
34125    sizeof(unixFile),     /* szOsFile */                    \
34126    MAX_PATHNAME,         /* mxPathname */                  \
34127    0,                    /* pNext */                       \
34128    VFSNAME,              /* zName */                       \
34129    (void*)&FINDER,       /* pAppData */                    \
34130    unixOpen,             /* xOpen */                       \
34131    unixDelete,           /* xDelete */                     \
34132    unixAccess,           /* xAccess */                     \
34133    unixFullPathname,     /* xFullPathname */               \
34134    unixDlOpen,           /* xDlOpen */                     \
34135    unixDlError,          /* xDlError */                    \
34136    unixDlSym,            /* xDlSym */                      \
34137    unixDlClose,          /* xDlClose */                    \
34138    unixRandomness,       /* xRandomness */                 \
34139    unixSleep,            /* xSleep */                      \
34140    unixCurrentTime,      /* xCurrentTime */                \
34141    unixGetLastError,     /* xGetLastError */               \
34142    unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
34143    unixSetSystemCall,    /* xSetSystemCall */              \
34144    unixGetSystemCall,    /* xGetSystemCall */              \
34145    unixNextSystemCall,   /* xNextSystemCall */             \
34146  }
34147
34148  /*
34149  ** All default VFSes for unix are contained in the following array.
34150  **
34151  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
34152  ** by the SQLite core when the VFS is registered.  So the following
34153  ** array cannot be const.
34154  */
34155  static sqlite3_vfs aVfs[] = {
34156#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
34157    UNIXVFS("unix",          autolockIoFinder ),
34158#elif OS_VXWORKS
34159    UNIXVFS("unix",          vxworksIoFinder ),
34160#else
34161    UNIXVFS("unix",          posixIoFinder ),
34162#endif
34163    UNIXVFS("unix-none",     nolockIoFinder ),
34164    UNIXVFS("unix-dotfile",  dotlockIoFinder ),
34165    UNIXVFS("unix-excl",     posixIoFinder ),
34166#if OS_VXWORKS
34167    UNIXVFS("unix-namedsem", semIoFinder ),
34168#endif
34169#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
34170    UNIXVFS("unix-posix",    posixIoFinder ),
34171#endif
34172#if SQLITE_ENABLE_LOCKING_STYLE
34173    UNIXVFS("unix-flock",    flockIoFinder ),
34174#endif
34175#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
34176    UNIXVFS("unix-afp",      afpIoFinder ),
34177    UNIXVFS("unix-nfs",      nfsIoFinder ),
34178    UNIXVFS("unix-proxy",    proxyIoFinder ),
34179#endif
34180  };
34181  unsigned int i;          /* Loop counter */
34182
34183  /* Double-check that the aSyscall[] array has been constructed
34184  ** correctly.  See ticket [bb3a86e890c8e96ab] */
34185  assert( ArraySize(aSyscall)==25 );
34186
34187  /* Register all VFSes defined in the aVfs[] array */
34188  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
34189    sqlite3_vfs_register(&aVfs[i], i==0);
34190  }
34191  return SQLITE_OK;
34192}
34193
34194/*
34195** Shutdown the operating system interface.
34196**
34197** Some operating systems might need to do some cleanup in this routine,
34198** to release dynamically allocated objects.  But not on unix.
34199** This routine is a no-op for unix.
34200*/
34201SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void){
34202  return SQLITE_OK;
34203}
34204
34205#endif /* SQLITE_OS_UNIX */
34206
34207/************** End of os_unix.c *********************************************/
34208/************** Begin file os_win.c ******************************************/
34209/*
34210** 2004 May 22
34211**
34212** The author disclaims copyright to this source code.  In place of
34213** a legal notice, here is a blessing:
34214**
34215**    May you do good and not evil.
34216**    May you find forgiveness for yourself and forgive others.
34217**    May you share freely, never taking more than you give.
34218**
34219******************************************************************************
34220**
34221** This file contains code that is specific to Windows.
34222*/
34223/* #include "sqliteInt.h" */
34224#if SQLITE_OS_WIN               /* This file is used for Windows only */
34225
34226/*
34227** Include code that is common to all os_*.c files
34228*/
34229/************** Include os_common.h in the middle of os_win.c ****************/
34230/************** Begin file os_common.h ***************************************/
34231/*
34232** 2004 May 22
34233**
34234** The author disclaims copyright to this source code.  In place of
34235** a legal notice, here is a blessing:
34236**
34237**    May you do good and not evil.
34238**    May you find forgiveness for yourself and forgive others.
34239**    May you share freely, never taking more than you give.
34240**
34241******************************************************************************
34242**
34243** This file contains macros and a little bit of code that is common to
34244** all of the platform-specific files (os_*.c) and is #included into those
34245** files.
34246**
34247** This file should be #included by the os_*.c files only.  It is not a
34248** general purpose header file.
34249*/
34250#ifndef _OS_COMMON_H_
34251#define _OS_COMMON_H_
34252
34253/*
34254** At least two bugs have slipped in because we changed the MEMORY_DEBUG
34255** macro to SQLITE_DEBUG and some older makefiles have not yet made the
34256** switch.  The following code should catch this problem at compile-time.
34257*/
34258#ifdef MEMORY_DEBUG
34259# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
34260#endif
34261
34262/*
34263** Macros for performance tracing.  Normally turned off.  Only works
34264** on i486 hardware.
34265*/
34266#ifdef SQLITE_PERFORMANCE_TRACE
34267
34268/*
34269** hwtime.h contains inline assembler code for implementing
34270** high-performance timing routines.
34271*/
34272/************** Include hwtime.h in the middle of os_common.h ****************/
34273/************** Begin file hwtime.h ******************************************/
34274/*
34275** 2008 May 27
34276**
34277** The author disclaims copyright to this source code.  In place of
34278** a legal notice, here is a blessing:
34279**
34280**    May you do good and not evil.
34281**    May you find forgiveness for yourself and forgive others.
34282**    May you share freely, never taking more than you give.
34283**
34284******************************************************************************
34285**
34286** This file contains inline asm code for retrieving "high-performance"
34287** counters for x86 class CPUs.
34288*/
34289#ifndef _HWTIME_H_
34290#define _HWTIME_H_
34291
34292/*
34293** The following routine only works on pentium-class (or newer) processors.
34294** It uses the RDTSC opcode to read the cycle count value out of the
34295** processor and returns that value.  This can be used for high-res
34296** profiling.
34297*/
34298#if (defined(__GNUC__) || defined(_MSC_VER)) && \
34299      (defined(i386) || defined(__i386__) || defined(_M_IX86))
34300
34301  #if defined(__GNUC__)
34302
34303  __inline__ sqlite_uint64 sqlite3Hwtime(void){
34304     unsigned int lo, hi;
34305     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
34306     return (sqlite_uint64)hi << 32 | lo;
34307  }
34308
34309  #elif defined(_MSC_VER)
34310
34311  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
34312     __asm {
34313        rdtsc
34314        ret       ; return value at EDX:EAX
34315     }
34316  }
34317
34318  #endif
34319
34320#elif (defined(__GNUC__) && defined(__x86_64__))
34321
34322  __inline__ sqlite_uint64 sqlite3Hwtime(void){
34323      unsigned long val;
34324      __asm__ __volatile__ ("rdtsc" : "=A" (val));
34325      return val;
34326  }
34327
34328#elif (defined(__GNUC__) && defined(__ppc__))
34329
34330  __inline__ sqlite_uint64 sqlite3Hwtime(void){
34331      unsigned long long retval;
34332      unsigned long junk;
34333      __asm__ __volatile__ ("\n\
34334          1:      mftbu   %1\n\
34335                  mftb    %L0\n\
34336                  mftbu   %0\n\
34337                  cmpw    %0,%1\n\
34338                  bne     1b"
34339                  : "=r" (retval), "=r" (junk));
34340      return retval;
34341  }
34342
34343#else
34344
34345  #error Need implementation of sqlite3Hwtime() for your platform.
34346
34347  /*
34348  ** To compile without implementing sqlite3Hwtime() for your platform,
34349  ** you can remove the above #error and use the following
34350  ** stub function.  You will lose timing support for many
34351  ** of the debugging and testing utilities, but it should at
34352  ** least compile and run.
34353  */
34354SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
34355
34356#endif
34357
34358#endif /* !defined(_HWTIME_H_) */
34359
34360/************** End of hwtime.h **********************************************/
34361/************** Continuing where we left off in os_common.h ******************/
34362
34363static sqlite_uint64 g_start;
34364static sqlite_uint64 g_elapsed;
34365#define TIMER_START       g_start=sqlite3Hwtime()
34366#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
34367#define TIMER_ELAPSED     g_elapsed
34368#else
34369#define TIMER_START
34370#define TIMER_END
34371#define TIMER_ELAPSED     ((sqlite_uint64)0)
34372#endif
34373
34374/*
34375** If we compile with the SQLITE_TEST macro set, then the following block
34376** of code will give us the ability to simulate a disk I/O error.  This
34377** is used for testing the I/O recovery logic.
34378*/
34379#ifdef SQLITE_TEST
34380SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
34381SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
34382SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
34383SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
34384SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
34385SQLITE_API int sqlite3_diskfull_pending = 0;
34386SQLITE_API int sqlite3_diskfull = 0;
34387#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
34388#define SimulateIOError(CODE)  \
34389  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
34390       || sqlite3_io_error_pending-- == 1 )  \
34391              { local_ioerr(); CODE; }
34392static void local_ioerr(){
34393  IOTRACE(("IOERR\n"));
34394  sqlite3_io_error_hit++;
34395  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
34396}
34397#define SimulateDiskfullError(CODE) \
34398   if( sqlite3_diskfull_pending ){ \
34399     if( sqlite3_diskfull_pending == 1 ){ \
34400       local_ioerr(); \
34401       sqlite3_diskfull = 1; \
34402       sqlite3_io_error_hit = 1; \
34403       CODE; \
34404     }else{ \
34405       sqlite3_diskfull_pending--; \
34406     } \
34407   }
34408#else
34409#define SimulateIOErrorBenign(X)
34410#define SimulateIOError(A)
34411#define SimulateDiskfullError(A)
34412#endif
34413
34414/*
34415** When testing, keep a count of the number of open files.
34416*/
34417#ifdef SQLITE_TEST
34418SQLITE_API int sqlite3_open_file_count = 0;
34419#define OpenCounter(X)  sqlite3_open_file_count+=(X)
34420#else
34421#define OpenCounter(X)
34422#endif
34423
34424#endif /* !defined(_OS_COMMON_H_) */
34425
34426/************** End of os_common.h *******************************************/
34427/************** Continuing where we left off in os_win.c *********************/
34428
34429/*
34430** Include the header file for the Windows VFS.
34431*/
34432/* #include "os_win.h" */
34433
34434/*
34435** Compiling and using WAL mode requires several APIs that are only
34436** available in Windows platforms based on the NT kernel.
34437*/
34438#if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
34439#  error "WAL mode requires support from the Windows NT kernel, compile\
34440 with SQLITE_OMIT_WAL."
34441#endif
34442
34443#if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
34444#  error "Memory mapped files require support from the Windows NT kernel,\
34445 compile with SQLITE_MAX_MMAP_SIZE=0."
34446#endif
34447
34448/*
34449** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
34450** based on the sub-platform)?
34451*/
34452#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
34453#  define SQLITE_WIN32_HAS_ANSI
34454#endif
34455
34456/*
34457** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
34458** based on the sub-platform)?
34459*/
34460#if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
34461    !defined(SQLITE_WIN32_NO_WIDE)
34462#  define SQLITE_WIN32_HAS_WIDE
34463#endif
34464
34465/*
34466** Make sure at least one set of Win32 APIs is available.
34467*/
34468#if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
34469#  error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
34470 must be defined."
34471#endif
34472
34473/*
34474** Define the required Windows SDK version constants if they are not
34475** already available.
34476*/
34477#ifndef NTDDI_WIN8
34478#  define NTDDI_WIN8                        0x06020000
34479#endif
34480
34481#ifndef NTDDI_WINBLUE
34482#  define NTDDI_WINBLUE                     0x06030000
34483#endif
34484
34485/*
34486** Check to see if the GetVersionEx[AW] functions are deprecated on the
34487** target system.  GetVersionEx was first deprecated in Win8.1.
34488*/
34489#ifndef SQLITE_WIN32_GETVERSIONEX
34490#  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
34491#    define SQLITE_WIN32_GETVERSIONEX   0   /* GetVersionEx() is deprecated */
34492#  else
34493#    define SQLITE_WIN32_GETVERSIONEX   1   /* GetVersionEx() is current */
34494#  endif
34495#endif
34496
34497/*
34498** This constant should already be defined (in the "WinDef.h" SDK file).
34499*/
34500#ifndef MAX_PATH
34501#  define MAX_PATH                      (260)
34502#endif
34503
34504/*
34505** Maximum pathname length (in chars) for Win32.  This should normally be
34506** MAX_PATH.
34507*/
34508#ifndef SQLITE_WIN32_MAX_PATH_CHARS
34509#  define SQLITE_WIN32_MAX_PATH_CHARS   (MAX_PATH)
34510#endif
34511
34512/*
34513** This constant should already be defined (in the "WinNT.h" SDK file).
34514*/
34515#ifndef UNICODE_STRING_MAX_CHARS
34516#  define UNICODE_STRING_MAX_CHARS      (32767)
34517#endif
34518
34519/*
34520** Maximum pathname length (in chars) for WinNT.  This should normally be
34521** UNICODE_STRING_MAX_CHARS.
34522*/
34523#ifndef SQLITE_WINNT_MAX_PATH_CHARS
34524#  define SQLITE_WINNT_MAX_PATH_CHARS   (UNICODE_STRING_MAX_CHARS)
34525#endif
34526
34527/*
34528** Maximum pathname length (in bytes) for Win32.  The MAX_PATH macro is in
34529** characters, so we allocate 4 bytes per character assuming worst-case of
34530** 4-bytes-per-character for UTF8.
34531*/
34532#ifndef SQLITE_WIN32_MAX_PATH_BYTES
34533#  define SQLITE_WIN32_MAX_PATH_BYTES   (SQLITE_WIN32_MAX_PATH_CHARS*4)
34534#endif
34535
34536/*
34537** Maximum pathname length (in bytes) for WinNT.  This should normally be
34538** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
34539*/
34540#ifndef SQLITE_WINNT_MAX_PATH_BYTES
34541#  define SQLITE_WINNT_MAX_PATH_BYTES   \
34542                            (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
34543#endif
34544
34545/*
34546** Maximum error message length (in chars) for WinRT.
34547*/
34548#ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
34549#  define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
34550#endif
34551
34552/*
34553** Returns non-zero if the character should be treated as a directory
34554** separator.
34555*/
34556#ifndef winIsDirSep
34557#  define winIsDirSep(a)                (((a) == '/') || ((a) == '\\'))
34558#endif
34559
34560/*
34561** This macro is used when a local variable is set to a value that is
34562** [sometimes] not used by the code (e.g. via conditional compilation).
34563*/
34564#ifndef UNUSED_VARIABLE_VALUE
34565#  define UNUSED_VARIABLE_VALUE(x)      (void)(x)
34566#endif
34567
34568/*
34569** Returns the character that should be used as the directory separator.
34570*/
34571#ifndef winGetDirSep
34572#  define winGetDirSep()                '\\'
34573#endif
34574
34575/*
34576** Do we need to manually define the Win32 file mapping APIs for use with WAL
34577** mode or memory mapped files (e.g. these APIs are available in the Windows
34578** CE SDK; however, they are not present in the header file)?
34579*/
34580#if SQLITE_WIN32_FILEMAPPING_API && \
34581        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
34582/*
34583** Two of the file mapping APIs are different under WinRT.  Figure out which
34584** set we need.
34585*/
34586#if SQLITE_OS_WINRT
34587WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
34588        LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
34589
34590WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
34591#else
34592#if defined(SQLITE_WIN32_HAS_ANSI)
34593WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
34594        DWORD, DWORD, DWORD, LPCSTR);
34595#endif /* defined(SQLITE_WIN32_HAS_ANSI) */
34596
34597#if defined(SQLITE_WIN32_HAS_WIDE)
34598WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
34599        DWORD, DWORD, DWORD, LPCWSTR);
34600#endif /* defined(SQLITE_WIN32_HAS_WIDE) */
34601
34602WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
34603#endif /* SQLITE_OS_WINRT */
34604
34605/*
34606** These file mapping APIs are common to both Win32 and WinRT.
34607*/
34608
34609WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
34610WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
34611#endif /* SQLITE_WIN32_FILEMAPPING_API */
34612
34613/*
34614** Some Microsoft compilers lack this definition.
34615*/
34616#ifndef INVALID_FILE_ATTRIBUTES
34617# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
34618#endif
34619
34620#ifndef FILE_FLAG_MASK
34621# define FILE_FLAG_MASK          (0xFF3C0000)
34622#endif
34623
34624#ifndef FILE_ATTRIBUTE_MASK
34625# define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
34626#endif
34627
34628#ifndef SQLITE_OMIT_WAL
34629/* Forward references to structures used for WAL */
34630typedef struct winShm winShm;           /* A connection to shared-memory */
34631typedef struct winShmNode winShmNode;   /* A region of shared-memory */
34632#endif
34633
34634/*
34635** WinCE lacks native support for file locking so we have to fake it
34636** with some code of our own.
34637*/
34638#if SQLITE_OS_WINCE
34639typedef struct winceLock {
34640  int nReaders;       /* Number of reader locks obtained */
34641  BOOL bPending;      /* Indicates a pending lock has been obtained */
34642  BOOL bReserved;     /* Indicates a reserved lock has been obtained */
34643  BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
34644} winceLock;
34645#endif
34646
34647/*
34648** The winFile structure is a subclass of sqlite3_file* specific to the win32
34649** portability layer.
34650*/
34651typedef struct winFile winFile;
34652struct winFile {
34653  const sqlite3_io_methods *pMethod; /*** Must be first ***/
34654  sqlite3_vfs *pVfs;      /* The VFS used to open this file */
34655  HANDLE h;               /* Handle for accessing the file */
34656  u8 locktype;            /* Type of lock currently held on this file */
34657  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
34658  u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
34659  DWORD lastErrno;        /* The Windows errno from the last I/O error */
34660#ifndef SQLITE_OMIT_WAL
34661  winShm *pShm;           /* Instance of shared memory on this file */
34662#endif
34663  const char *zPath;      /* Full pathname of this file */
34664  int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
34665#if SQLITE_OS_WINCE
34666  LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
34667  HANDLE hMutex;          /* Mutex used to control access to shared lock */
34668  HANDLE hShared;         /* Shared memory segment used for locking */
34669  winceLock local;        /* Locks obtained by this instance of winFile */
34670  winceLock *shared;      /* Global shared lock memory for the file  */
34671#endif
34672#if SQLITE_MAX_MMAP_SIZE>0
34673  int nFetchOut;                /* Number of outstanding xFetch references */
34674  HANDLE hMap;                  /* Handle for accessing memory mapping */
34675  void *pMapRegion;             /* Area memory mapped */
34676  sqlite3_int64 mmapSize;       /* Usable size of mapped region */
34677  sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
34678  sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
34679#endif
34680};
34681
34682/*
34683** Allowed values for winFile.ctrlFlags
34684*/
34685#define WINFILE_RDONLY          0x02   /* Connection is read only */
34686#define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
34687#define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
34688
34689/*
34690 * The size of the buffer used by sqlite3_win32_write_debug().
34691 */
34692#ifndef SQLITE_WIN32_DBG_BUF_SIZE
34693#  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
34694#endif
34695
34696/*
34697 * The value used with sqlite3_win32_set_directory() to specify that
34698 * the data directory should be changed.
34699 */
34700#ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
34701#  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
34702#endif
34703
34704/*
34705 * The value used with sqlite3_win32_set_directory() to specify that
34706 * the temporary directory should be changed.
34707 */
34708#ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
34709#  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
34710#endif
34711
34712/*
34713 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
34714 * various Win32 API heap functions instead of our own.
34715 */
34716#ifdef SQLITE_WIN32_MALLOC
34717
34718/*
34719 * If this is non-zero, an isolated heap will be created by the native Win32
34720 * allocator subsystem; otherwise, the default process heap will be used.  This
34721 * setting has no effect when compiling for WinRT.  By default, this is enabled
34722 * and an isolated heap will be created to store all allocated data.
34723 *
34724 ******************************************************************************
34725 * WARNING: It is important to note that when this setting is non-zero and the
34726 *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
34727 *          function), all data that was allocated using the isolated heap will
34728 *          be freed immediately and any attempt to access any of that freed
34729 *          data will almost certainly result in an immediate access violation.
34730 ******************************************************************************
34731 */
34732#ifndef SQLITE_WIN32_HEAP_CREATE
34733#  define SQLITE_WIN32_HEAP_CREATE    (TRUE)
34734#endif
34735
34736/*
34737 * The initial size of the Win32-specific heap.  This value may be zero.
34738 */
34739#ifndef SQLITE_WIN32_HEAP_INIT_SIZE
34740#  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
34741                                       (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
34742#endif
34743
34744/*
34745 * The maximum size of the Win32-specific heap.  This value may be zero.
34746 */
34747#ifndef SQLITE_WIN32_HEAP_MAX_SIZE
34748#  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
34749#endif
34750
34751/*
34752 * The extra flags to use in calls to the Win32 heap APIs.  This value may be
34753 * zero for the default behavior.
34754 */
34755#ifndef SQLITE_WIN32_HEAP_FLAGS
34756#  define SQLITE_WIN32_HEAP_FLAGS     (0)
34757#endif
34758
34759
34760/*
34761** The winMemData structure stores information required by the Win32-specific
34762** sqlite3_mem_methods implementation.
34763*/
34764typedef struct winMemData winMemData;
34765struct winMemData {
34766#ifndef NDEBUG
34767  u32 magic1;   /* Magic number to detect structure corruption. */
34768#endif
34769  HANDLE hHeap; /* The handle to our heap. */
34770  BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
34771#ifndef NDEBUG
34772  u32 magic2;   /* Magic number to detect structure corruption. */
34773#endif
34774};
34775
34776#ifndef NDEBUG
34777#define WINMEM_MAGIC1     0x42b2830b
34778#define WINMEM_MAGIC2     0xbd4d7cf4
34779#endif
34780
34781static struct winMemData win_mem_data = {
34782#ifndef NDEBUG
34783  WINMEM_MAGIC1,
34784#endif
34785  NULL, FALSE
34786#ifndef NDEBUG
34787  ,WINMEM_MAGIC2
34788#endif
34789};
34790
34791#ifndef NDEBUG
34792#define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
34793#define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
34794#define winMemAssertMagic()  winMemAssertMagic1(); winMemAssertMagic2();
34795#else
34796#define winMemAssertMagic()
34797#endif
34798
34799#define winMemGetDataPtr()  &win_mem_data
34800#define winMemGetHeap()     win_mem_data.hHeap
34801#define winMemGetOwned()    win_mem_data.bOwned
34802
34803static void *winMemMalloc(int nBytes);
34804static void winMemFree(void *pPrior);
34805static void *winMemRealloc(void *pPrior, int nBytes);
34806static int winMemSize(void *p);
34807static int winMemRoundup(int n);
34808static int winMemInit(void *pAppData);
34809static void winMemShutdown(void *pAppData);
34810
34811SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
34812#endif /* SQLITE_WIN32_MALLOC */
34813
34814/*
34815** The following variable is (normally) set once and never changes
34816** thereafter.  It records whether the operating system is Win9x
34817** or WinNT.
34818**
34819** 0:   Operating system unknown.
34820** 1:   Operating system is Win9x.
34821** 2:   Operating system is WinNT.
34822**
34823** In order to facilitate testing on a WinNT system, the test fixture
34824** can manually set this value to 1 to emulate Win98 behavior.
34825*/
34826#ifdef SQLITE_TEST
34827SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
34828#else
34829static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
34830#endif
34831
34832#ifndef SYSCALL
34833#  define SYSCALL sqlite3_syscall_ptr
34834#endif
34835
34836/*
34837** This function is not available on Windows CE or WinRT.
34838 */
34839
34840#if SQLITE_OS_WINCE || SQLITE_OS_WINRT
34841#  define osAreFileApisANSI()       1
34842#endif
34843
34844/*
34845** Many system calls are accessed through pointer-to-functions so that
34846** they may be overridden at runtime to facilitate fault injection during
34847** testing and sandboxing.  The following array holds the names and pointers
34848** to all overrideable system calls.
34849*/
34850static struct win_syscall {
34851  const char *zName;            /* Name of the system call */
34852  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
34853  sqlite3_syscall_ptr pDefault; /* Default value */
34854} aSyscall[] = {
34855#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
34856  { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
34857#else
34858  { "AreFileApisANSI",         (SYSCALL)0,                       0 },
34859#endif
34860
34861#ifndef osAreFileApisANSI
34862#define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
34863#endif
34864
34865#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
34866  { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
34867#else
34868  { "CharLowerW",              (SYSCALL)0,                       0 },
34869#endif
34870
34871#define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
34872
34873#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
34874  { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
34875#else
34876  { "CharUpperW",              (SYSCALL)0,                       0 },
34877#endif
34878
34879#define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
34880
34881  { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
34882
34883#define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
34884
34885#if defined(SQLITE_WIN32_HAS_ANSI)
34886  { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
34887#else
34888  { "CreateFileA",             (SYSCALL)0,                       0 },
34889#endif
34890
34891#define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
34892        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
34893
34894#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
34895  { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
34896#else
34897  { "CreateFileW",             (SYSCALL)0,                       0 },
34898#endif
34899
34900#define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
34901        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
34902
34903#if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
34904        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
34905  { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
34906#else
34907  { "CreateFileMappingA",      (SYSCALL)0,                       0 },
34908#endif
34909
34910#define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
34911        DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
34912
34913#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
34914        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
34915  { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
34916#else
34917  { "CreateFileMappingW",      (SYSCALL)0,                       0 },
34918#endif
34919
34920#define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
34921        DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
34922
34923#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
34924  { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
34925#else
34926  { "CreateMutexW",            (SYSCALL)0,                       0 },
34927#endif
34928
34929#define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
34930        LPCWSTR))aSyscall[8].pCurrent)
34931
34932#if defined(SQLITE_WIN32_HAS_ANSI)
34933  { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
34934#else
34935  { "DeleteFileA",             (SYSCALL)0,                       0 },
34936#endif
34937
34938#define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
34939
34940#if defined(SQLITE_WIN32_HAS_WIDE)
34941  { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
34942#else
34943  { "DeleteFileW",             (SYSCALL)0,                       0 },
34944#endif
34945
34946#define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
34947
34948#if SQLITE_OS_WINCE
34949  { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
34950#else
34951  { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
34952#endif
34953
34954#define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
34955        LPFILETIME))aSyscall[11].pCurrent)
34956
34957#if SQLITE_OS_WINCE
34958  { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
34959#else
34960  { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
34961#endif
34962
34963#define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
34964        LPSYSTEMTIME))aSyscall[12].pCurrent)
34965
34966  { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
34967
34968#define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
34969
34970#if defined(SQLITE_WIN32_HAS_ANSI)
34971  { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
34972#else
34973  { "FormatMessageA",          (SYSCALL)0,                       0 },
34974#endif
34975
34976#define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
34977        DWORD,va_list*))aSyscall[14].pCurrent)
34978
34979#if defined(SQLITE_WIN32_HAS_WIDE)
34980  { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
34981#else
34982  { "FormatMessageW",          (SYSCALL)0,                       0 },
34983#endif
34984
34985#define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
34986        DWORD,va_list*))aSyscall[15].pCurrent)
34987
34988#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
34989  { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
34990#else
34991  { "FreeLibrary",             (SYSCALL)0,                       0 },
34992#endif
34993
34994#define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
34995
34996  { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
34997
34998#define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
34999
35000#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
35001  { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
35002#else
35003  { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
35004#endif
35005
35006#define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
35007        LPDWORD))aSyscall[18].pCurrent)
35008
35009#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
35010  { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
35011#else
35012  { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
35013#endif
35014
35015#define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
35016        LPDWORD))aSyscall[19].pCurrent)
35017
35018#if defined(SQLITE_WIN32_HAS_ANSI)
35019  { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
35020#else
35021  { "GetFileAttributesA",      (SYSCALL)0,                       0 },
35022#endif
35023
35024#define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
35025
35026#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
35027  { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
35028#else
35029  { "GetFileAttributesW",      (SYSCALL)0,                       0 },
35030#endif
35031
35032#define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
35033
35034#if defined(SQLITE_WIN32_HAS_WIDE)
35035  { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
35036#else
35037  { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
35038#endif
35039
35040#define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
35041        LPVOID))aSyscall[22].pCurrent)
35042
35043#if !SQLITE_OS_WINRT
35044  { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
35045#else
35046  { "GetFileSize",             (SYSCALL)0,                       0 },
35047#endif
35048
35049#define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
35050
35051#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
35052  { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
35053#else
35054  { "GetFullPathNameA",        (SYSCALL)0,                       0 },
35055#endif
35056
35057#define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
35058        LPSTR*))aSyscall[24].pCurrent)
35059
35060#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
35061  { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
35062#else
35063  { "GetFullPathNameW",        (SYSCALL)0,                       0 },
35064#endif
35065
35066#define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
35067        LPWSTR*))aSyscall[25].pCurrent)
35068
35069  { "GetLastError",            (SYSCALL)GetLastError,            0 },
35070
35071#define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
35072
35073#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
35074#if SQLITE_OS_WINCE
35075  /* The GetProcAddressA() routine is only available on Windows CE. */
35076  { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
35077#else
35078  /* All other Windows platforms expect GetProcAddress() to take
35079  ** an ANSI string regardless of the _UNICODE setting */
35080  { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
35081#endif
35082#else
35083  { "GetProcAddressA",         (SYSCALL)0,                       0 },
35084#endif
35085
35086#define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
35087        LPCSTR))aSyscall[27].pCurrent)
35088
35089#if !SQLITE_OS_WINRT
35090  { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
35091#else
35092  { "GetSystemInfo",           (SYSCALL)0,                       0 },
35093#endif
35094
35095#define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
35096
35097  { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
35098
35099#define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
35100
35101#if !SQLITE_OS_WINCE
35102  { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
35103#else
35104  { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
35105#endif
35106
35107#define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
35108        LPFILETIME))aSyscall[30].pCurrent)
35109
35110#if defined(SQLITE_WIN32_HAS_ANSI)
35111  { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
35112#else
35113  { "GetTempPathA",            (SYSCALL)0,                       0 },
35114#endif
35115
35116#define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
35117
35118#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
35119  { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
35120#else
35121  { "GetTempPathW",            (SYSCALL)0,                       0 },
35122#endif
35123
35124#define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
35125
35126#if !SQLITE_OS_WINRT
35127  { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
35128#else
35129  { "GetTickCount",            (SYSCALL)0,                       0 },
35130#endif
35131
35132#define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
35133
35134#if defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_GETVERSIONEX) && \
35135        SQLITE_WIN32_GETVERSIONEX
35136  { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
35137#else
35138  { "GetVersionExA",           (SYSCALL)0,                       0 },
35139#endif
35140
35141#define osGetVersionExA ((BOOL(WINAPI*)( \
35142        LPOSVERSIONINFOA))aSyscall[34].pCurrent)
35143
35144#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
35145        defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
35146  { "GetVersionExW",           (SYSCALL)GetVersionExW,           0 },
35147#else
35148  { "GetVersionExW",           (SYSCALL)0,                       0 },
35149#endif
35150
35151#define osGetVersionExW ((BOOL(WINAPI*)( \
35152        LPOSVERSIONINFOW))aSyscall[35].pCurrent)
35153
35154  { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
35155
35156#define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
35157        SIZE_T))aSyscall[36].pCurrent)
35158
35159#if !SQLITE_OS_WINRT
35160  { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
35161#else
35162  { "HeapCreate",              (SYSCALL)0,                       0 },
35163#endif
35164
35165#define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
35166        SIZE_T))aSyscall[37].pCurrent)
35167
35168#if !SQLITE_OS_WINRT
35169  { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
35170#else
35171  { "HeapDestroy",             (SYSCALL)0,                       0 },
35172#endif
35173
35174#define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
35175
35176  { "HeapFree",                (SYSCALL)HeapFree,                0 },
35177
35178#define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
35179
35180  { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
35181
35182#define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
35183        SIZE_T))aSyscall[40].pCurrent)
35184
35185  { "HeapSize",                (SYSCALL)HeapSize,                0 },
35186
35187#define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
35188        LPCVOID))aSyscall[41].pCurrent)
35189
35190#if !SQLITE_OS_WINRT
35191  { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
35192#else
35193  { "HeapValidate",            (SYSCALL)0,                       0 },
35194#endif
35195
35196#define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
35197        LPCVOID))aSyscall[42].pCurrent)
35198
35199#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
35200  { "HeapCompact",             (SYSCALL)HeapCompact,             0 },
35201#else
35202  { "HeapCompact",             (SYSCALL)0,                       0 },
35203#endif
35204
35205#define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
35206
35207#if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
35208  { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
35209#else
35210  { "LoadLibraryA",            (SYSCALL)0,                       0 },
35211#endif
35212
35213#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
35214
35215#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
35216        !defined(SQLITE_OMIT_LOAD_EXTENSION)
35217  { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
35218#else
35219  { "LoadLibraryW",            (SYSCALL)0,                       0 },
35220#endif
35221
35222#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
35223
35224#if !SQLITE_OS_WINRT
35225  { "LocalFree",               (SYSCALL)LocalFree,               0 },
35226#else
35227  { "LocalFree",               (SYSCALL)0,                       0 },
35228#endif
35229
35230#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
35231
35232#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
35233  { "LockFile",                (SYSCALL)LockFile,                0 },
35234#else
35235  { "LockFile",                (SYSCALL)0,                       0 },
35236#endif
35237
35238#ifndef osLockFile
35239#define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
35240        DWORD))aSyscall[47].pCurrent)
35241#endif
35242
35243#if !SQLITE_OS_WINCE
35244  { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
35245#else
35246  { "LockFileEx",              (SYSCALL)0,                       0 },
35247#endif
35248
35249#ifndef osLockFileEx
35250#define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
35251        LPOVERLAPPED))aSyscall[48].pCurrent)
35252#endif
35253
35254#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
35255        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
35256  { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
35257#else
35258  { "MapViewOfFile",           (SYSCALL)0,                       0 },
35259#endif
35260
35261#define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
35262        SIZE_T))aSyscall[49].pCurrent)
35263
35264  { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
35265
35266#define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
35267        int))aSyscall[50].pCurrent)
35268
35269  { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
35270
35271#define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
35272        LARGE_INTEGER*))aSyscall[51].pCurrent)
35273
35274  { "ReadFile",                (SYSCALL)ReadFile,                0 },
35275
35276#define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
35277        LPOVERLAPPED))aSyscall[52].pCurrent)
35278
35279  { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
35280
35281#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
35282
35283#if !SQLITE_OS_WINRT
35284  { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
35285#else
35286  { "SetFilePointer",          (SYSCALL)0,                       0 },
35287#endif
35288
35289#define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
35290        DWORD))aSyscall[54].pCurrent)
35291
35292#if !SQLITE_OS_WINRT
35293  { "Sleep",                   (SYSCALL)Sleep,                   0 },
35294#else
35295  { "Sleep",                   (SYSCALL)0,                       0 },
35296#endif
35297
35298#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
35299
35300  { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
35301
35302#define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
35303        LPFILETIME))aSyscall[56].pCurrent)
35304
35305#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
35306  { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
35307#else
35308  { "UnlockFile",              (SYSCALL)0,                       0 },
35309#endif
35310
35311#ifndef osUnlockFile
35312#define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
35313        DWORD))aSyscall[57].pCurrent)
35314#endif
35315
35316#if !SQLITE_OS_WINCE
35317  { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
35318#else
35319  { "UnlockFileEx",            (SYSCALL)0,                       0 },
35320#endif
35321
35322#define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
35323        LPOVERLAPPED))aSyscall[58].pCurrent)
35324
35325#if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
35326  { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
35327#else
35328  { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
35329#endif
35330
35331#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
35332
35333  { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
35334
35335#define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
35336        LPCSTR,LPBOOL))aSyscall[60].pCurrent)
35337
35338  { "WriteFile",               (SYSCALL)WriteFile,               0 },
35339
35340#define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
35341        LPOVERLAPPED))aSyscall[61].pCurrent)
35342
35343#if SQLITE_OS_WINRT
35344  { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
35345#else
35346  { "CreateEventExW",          (SYSCALL)0,                       0 },
35347#endif
35348
35349#define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
35350        DWORD,DWORD))aSyscall[62].pCurrent)
35351
35352#if !SQLITE_OS_WINRT
35353  { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
35354#else
35355  { "WaitForSingleObject",     (SYSCALL)0,                       0 },
35356#endif
35357
35358#define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
35359        DWORD))aSyscall[63].pCurrent)
35360
35361#if !SQLITE_OS_WINCE
35362  { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
35363#else
35364  { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
35365#endif
35366
35367#define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
35368        BOOL))aSyscall[64].pCurrent)
35369
35370#if SQLITE_OS_WINRT
35371  { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
35372#else
35373  { "SetFilePointerEx",        (SYSCALL)0,                       0 },
35374#endif
35375
35376#define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
35377        PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
35378
35379#if SQLITE_OS_WINRT
35380  { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
35381#else
35382  { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
35383#endif
35384
35385#define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
35386        FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
35387
35388#if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
35389  { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
35390#else
35391  { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
35392#endif
35393
35394#define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
35395        SIZE_T))aSyscall[67].pCurrent)
35396
35397#if SQLITE_OS_WINRT
35398  { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
35399#else
35400  { "CreateFile2",             (SYSCALL)0,                       0 },
35401#endif
35402
35403#define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
35404        LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
35405
35406#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
35407  { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
35408#else
35409  { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
35410#endif
35411
35412#define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
35413        DWORD))aSyscall[69].pCurrent)
35414
35415#if SQLITE_OS_WINRT
35416  { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
35417#else
35418  { "GetTickCount64",          (SYSCALL)0,                       0 },
35419#endif
35420
35421#define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
35422
35423#if SQLITE_OS_WINRT
35424  { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
35425#else
35426  { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
35427#endif
35428
35429#define osGetNativeSystemInfo ((VOID(WINAPI*)( \
35430        LPSYSTEM_INFO))aSyscall[71].pCurrent)
35431
35432#if defined(SQLITE_WIN32_HAS_ANSI)
35433  { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
35434#else
35435  { "OutputDebugStringA",      (SYSCALL)0,                       0 },
35436#endif
35437
35438#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
35439
35440#if defined(SQLITE_WIN32_HAS_WIDE)
35441  { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
35442#else
35443  { "OutputDebugStringW",      (SYSCALL)0,                       0 },
35444#endif
35445
35446#define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
35447
35448  { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
35449
35450#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
35451
35452#if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
35453  { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
35454#else
35455  { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
35456#endif
35457
35458#define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
35459        LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
35460
35461/*
35462** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
35463**       is really just a macro that uses a compiler intrinsic (e.g. x64).
35464**       So do not try to make this is into a redefinable interface.
35465*/
35466#if defined(InterlockedCompareExchange)
35467  { "InterlockedCompareExchange", (SYSCALL)0,                    0 },
35468
35469#define osInterlockedCompareExchange InterlockedCompareExchange
35470#else
35471  { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
35472
35473#define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
35474        SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
35475#endif /* defined(InterlockedCompareExchange) */
35476
35477#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
35478  { "UuidCreate",               (SYSCALL)UuidCreate,             0 },
35479#else
35480  { "UuidCreate",               (SYSCALL)0,                      0 },
35481#endif
35482
35483#define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
35484
35485#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
35486  { "UuidCreateSequential",     (SYSCALL)UuidCreateSequential,   0 },
35487#else
35488  { "UuidCreateSequential",     (SYSCALL)0,                      0 },
35489#endif
35490
35491#define osUuidCreateSequential \
35492        ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
35493
35494#if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
35495  { "FlushViewOfFile",          (SYSCALL)FlushViewOfFile,        0 },
35496#else
35497  { "FlushViewOfFile",          (SYSCALL)0,                      0 },
35498#endif
35499
35500#define osFlushViewOfFile \
35501        ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
35502
35503}; /* End of the overrideable system calls */
35504
35505/*
35506** This is the xSetSystemCall() method of sqlite3_vfs for all of the
35507** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
35508** system call pointer, or SQLITE_NOTFOUND if there is no configurable
35509** system call named zName.
35510*/
35511static int winSetSystemCall(
35512  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
35513  const char *zName,            /* Name of system call to override */
35514  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
35515){
35516  unsigned int i;
35517  int rc = SQLITE_NOTFOUND;
35518
35519  UNUSED_PARAMETER(pNotUsed);
35520  if( zName==0 ){
35521    /* If no zName is given, restore all system calls to their default
35522    ** settings and return NULL
35523    */
35524    rc = SQLITE_OK;
35525    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
35526      if( aSyscall[i].pDefault ){
35527        aSyscall[i].pCurrent = aSyscall[i].pDefault;
35528      }
35529    }
35530  }else{
35531    /* If zName is specified, operate on only the one system call
35532    ** specified.
35533    */
35534    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
35535      if( strcmp(zName, aSyscall[i].zName)==0 ){
35536        if( aSyscall[i].pDefault==0 ){
35537          aSyscall[i].pDefault = aSyscall[i].pCurrent;
35538        }
35539        rc = SQLITE_OK;
35540        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
35541        aSyscall[i].pCurrent = pNewFunc;
35542        break;
35543      }
35544    }
35545  }
35546  return rc;
35547}
35548
35549/*
35550** Return the value of a system call.  Return NULL if zName is not a
35551** recognized system call name.  NULL is also returned if the system call
35552** is currently undefined.
35553*/
35554static sqlite3_syscall_ptr winGetSystemCall(
35555  sqlite3_vfs *pNotUsed,
35556  const char *zName
35557){
35558  unsigned int i;
35559
35560  UNUSED_PARAMETER(pNotUsed);
35561  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
35562    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
35563  }
35564  return 0;
35565}
35566
35567/*
35568** Return the name of the first system call after zName.  If zName==NULL
35569** then return the name of the first system call.  Return NULL if zName
35570** is the last system call or if zName is not the name of a valid
35571** system call.
35572*/
35573static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
35574  int i = -1;
35575
35576  UNUSED_PARAMETER(p);
35577  if( zName ){
35578    for(i=0; i<ArraySize(aSyscall)-1; i++){
35579      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
35580    }
35581  }
35582  for(i++; i<ArraySize(aSyscall); i++){
35583    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
35584  }
35585  return 0;
35586}
35587
35588#ifdef SQLITE_WIN32_MALLOC
35589/*
35590** If a Win32 native heap has been configured, this function will attempt to
35591** compact it.  Upon success, SQLITE_OK will be returned.  Upon failure, one
35592** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned.  The
35593** "pnLargest" argument, if non-zero, will be used to return the size of the
35594** largest committed free block in the heap, in bytes.
35595*/
35596SQLITE_API int SQLITE_STDCALL sqlite3_win32_compact_heap(LPUINT pnLargest){
35597  int rc = SQLITE_OK;
35598  UINT nLargest = 0;
35599  HANDLE hHeap;
35600
35601  winMemAssertMagic();
35602  hHeap = winMemGetHeap();
35603  assert( hHeap!=0 );
35604  assert( hHeap!=INVALID_HANDLE_VALUE );
35605#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
35606  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
35607#endif
35608#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
35609  if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
35610    DWORD lastErrno = osGetLastError();
35611    if( lastErrno==NO_ERROR ){
35612      sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
35613                  (void*)hHeap);
35614      rc = SQLITE_NOMEM;
35615    }else{
35616      sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
35617                  osGetLastError(), (void*)hHeap);
35618      rc = SQLITE_ERROR;
35619    }
35620  }
35621#else
35622  sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
35623              (void*)hHeap);
35624  rc = SQLITE_NOTFOUND;
35625#endif
35626  if( pnLargest ) *pnLargest = nLargest;
35627  return rc;
35628}
35629
35630/*
35631** If a Win32 native heap has been configured, this function will attempt to
35632** destroy and recreate it.  If the Win32 native heap is not isolated and/or
35633** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
35634** be returned and no changes will be made to the Win32 native heap.
35635*/
35636SQLITE_API int SQLITE_STDCALL sqlite3_win32_reset_heap(){
35637  int rc;
35638  MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
35639  MUTEX_LOGIC( sqlite3_mutex *pMem; )    /* The memsys static mutex */
35640  MUTEX_LOGIC( pMaster = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); )
35641  MUTEX_LOGIC( pMem = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM); )
35642  sqlite3_mutex_enter(pMaster);
35643  sqlite3_mutex_enter(pMem);
35644  winMemAssertMagic();
35645  if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
35646    /*
35647    ** At this point, there should be no outstanding memory allocations on
35648    ** the heap.  Also, since both the master and memsys locks are currently
35649    ** being held by us, no other function (i.e. from another thread) should
35650    ** be able to even access the heap.  Attempt to destroy and recreate our
35651    ** isolated Win32 native heap now.
35652    */
35653    assert( winMemGetHeap()!=NULL );
35654    assert( winMemGetOwned() );
35655    assert( sqlite3_memory_used()==0 );
35656    winMemShutdown(winMemGetDataPtr());
35657    assert( winMemGetHeap()==NULL );
35658    assert( !winMemGetOwned() );
35659    assert( sqlite3_memory_used()==0 );
35660    rc = winMemInit(winMemGetDataPtr());
35661    assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
35662    assert( rc!=SQLITE_OK || winMemGetOwned() );
35663    assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
35664  }else{
35665    /*
35666    ** The Win32 native heap cannot be modified because it may be in use.
35667    */
35668    rc = SQLITE_BUSY;
35669  }
35670  sqlite3_mutex_leave(pMem);
35671  sqlite3_mutex_leave(pMaster);
35672  return rc;
35673}
35674#endif /* SQLITE_WIN32_MALLOC */
35675
35676/*
35677** This function outputs the specified (ANSI) string to the Win32 debugger
35678** (if available).
35679*/
35680
35681SQLITE_API void SQLITE_STDCALL sqlite3_win32_write_debug(const char *zBuf, int nBuf){
35682  char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
35683  int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
35684  if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
35685  assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
35686#if defined(SQLITE_WIN32_HAS_ANSI)
35687  if( nMin>0 ){
35688    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
35689    memcpy(zDbgBuf, zBuf, nMin);
35690    osOutputDebugStringA(zDbgBuf);
35691  }else{
35692    osOutputDebugStringA(zBuf);
35693  }
35694#elif defined(SQLITE_WIN32_HAS_WIDE)
35695  memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
35696  if ( osMultiByteToWideChar(
35697          osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
35698          nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
35699    return;
35700  }
35701  osOutputDebugStringW((LPCWSTR)zDbgBuf);
35702#else
35703  if( nMin>0 ){
35704    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
35705    memcpy(zDbgBuf, zBuf, nMin);
35706    fprintf(stderr, "%s", zDbgBuf);
35707  }else{
35708    fprintf(stderr, "%s", zBuf);
35709  }
35710#endif
35711}
35712
35713/*
35714** The following routine suspends the current thread for at least ms
35715** milliseconds.  This is equivalent to the Win32 Sleep() interface.
35716*/
35717#if SQLITE_OS_WINRT
35718static HANDLE sleepObj = NULL;
35719#endif
35720
35721SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds){
35722#if SQLITE_OS_WINRT
35723  if ( sleepObj==NULL ){
35724    sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
35725                                SYNCHRONIZE);
35726  }
35727  assert( sleepObj!=NULL );
35728  osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
35729#else
35730  osSleep(milliseconds);
35731#endif
35732}
35733
35734#if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
35735        SQLITE_THREADSAFE>0
35736SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
35737  DWORD rc;
35738  while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
35739                                       TRUE))==WAIT_IO_COMPLETION ){}
35740  return rc;
35741}
35742#endif
35743
35744/*
35745** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
35746** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
35747**
35748** Here is an interesting observation:  Win95, Win98, and WinME lack
35749** the LockFileEx() API.  But we can still statically link against that
35750** API as long as we don't call it when running Win95/98/ME.  A call to
35751** this routine is used to determine if the host is Win95/98/ME or
35752** WinNT/2K/XP so that we will know whether or not we can safely call
35753** the LockFileEx() API.
35754*/
35755
35756#if !defined(SQLITE_WIN32_GETVERSIONEX) || !SQLITE_WIN32_GETVERSIONEX
35757# define osIsNT()  (1)
35758#elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
35759# define osIsNT()  (1)
35760#elif !defined(SQLITE_WIN32_HAS_WIDE)
35761# define osIsNT()  (0)
35762#else
35763# define osIsNT()  ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
35764#endif
35765
35766/*
35767** This function determines if the machine is running a version of Windows
35768** based on the NT kernel.
35769*/
35770SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void){
35771#if SQLITE_OS_WINRT
35772  /*
35773  ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
35774  **       kernel.
35775  */
35776  return 1;
35777#elif defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
35778  if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
35779#if defined(SQLITE_WIN32_HAS_ANSI)
35780    OSVERSIONINFOA sInfo;
35781    sInfo.dwOSVersionInfoSize = sizeof(sInfo);
35782    osGetVersionExA(&sInfo);
35783    osInterlockedCompareExchange(&sqlite3_os_type,
35784        (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
35785#elif defined(SQLITE_WIN32_HAS_WIDE)
35786    OSVERSIONINFOW sInfo;
35787    sInfo.dwOSVersionInfoSize = sizeof(sInfo);
35788    osGetVersionExW(&sInfo);
35789    osInterlockedCompareExchange(&sqlite3_os_type,
35790        (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
35791#endif
35792  }
35793  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
35794#elif SQLITE_TEST
35795  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
35796#else
35797  /*
35798  ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
35799  **       deprecated are always assumed to be based on the NT kernel.
35800  */
35801  return 1;
35802#endif
35803}
35804
35805#ifdef SQLITE_WIN32_MALLOC
35806/*
35807** Allocate nBytes of memory.
35808*/
35809static void *winMemMalloc(int nBytes){
35810  HANDLE hHeap;
35811  void *p;
35812
35813  winMemAssertMagic();
35814  hHeap = winMemGetHeap();
35815  assert( hHeap!=0 );
35816  assert( hHeap!=INVALID_HANDLE_VALUE );
35817#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
35818  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
35819#endif
35820  assert( nBytes>=0 );
35821  p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
35822  if( !p ){
35823    sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
35824                nBytes, osGetLastError(), (void*)hHeap);
35825  }
35826  return p;
35827}
35828
35829/*
35830** Free memory.
35831*/
35832static void winMemFree(void *pPrior){
35833  HANDLE hHeap;
35834
35835  winMemAssertMagic();
35836  hHeap = winMemGetHeap();
35837  assert( hHeap!=0 );
35838  assert( hHeap!=INVALID_HANDLE_VALUE );
35839#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
35840  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
35841#endif
35842  if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
35843  if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
35844    sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
35845                pPrior, osGetLastError(), (void*)hHeap);
35846  }
35847}
35848
35849/*
35850** Change the size of an existing memory allocation
35851*/
35852static void *winMemRealloc(void *pPrior, int nBytes){
35853  HANDLE hHeap;
35854  void *p;
35855
35856  winMemAssertMagic();
35857  hHeap = winMemGetHeap();
35858  assert( hHeap!=0 );
35859  assert( hHeap!=INVALID_HANDLE_VALUE );
35860#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
35861  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
35862#endif
35863  assert( nBytes>=0 );
35864  if( !pPrior ){
35865    p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
35866  }else{
35867    p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
35868  }
35869  if( !p ){
35870    sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
35871                pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
35872                (void*)hHeap);
35873  }
35874  return p;
35875}
35876
35877/*
35878** Return the size of an outstanding allocation, in bytes.
35879*/
35880static int winMemSize(void *p){
35881  HANDLE hHeap;
35882  SIZE_T n;
35883
35884  winMemAssertMagic();
35885  hHeap = winMemGetHeap();
35886  assert( hHeap!=0 );
35887  assert( hHeap!=INVALID_HANDLE_VALUE );
35888#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
35889  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
35890#endif
35891  if( !p ) return 0;
35892  n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
35893  if( n==(SIZE_T)-1 ){
35894    sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
35895                p, osGetLastError(), (void*)hHeap);
35896    return 0;
35897  }
35898  return (int)n;
35899}
35900
35901/*
35902** Round up a request size to the next valid allocation size.
35903*/
35904static int winMemRoundup(int n){
35905  return n;
35906}
35907
35908/*
35909** Initialize this module.
35910*/
35911static int winMemInit(void *pAppData){
35912  winMemData *pWinMemData = (winMemData *)pAppData;
35913
35914  if( !pWinMemData ) return SQLITE_ERROR;
35915  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
35916  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
35917
35918#if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
35919  if( !pWinMemData->hHeap ){
35920    DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
35921    DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
35922    if( dwMaximumSize==0 ){
35923      dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
35924    }else if( dwInitialSize>dwMaximumSize ){
35925      dwInitialSize = dwMaximumSize;
35926    }
35927    pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
35928                                      dwInitialSize, dwMaximumSize);
35929    if( !pWinMemData->hHeap ){
35930      sqlite3_log(SQLITE_NOMEM,
35931          "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
35932          osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
35933          dwMaximumSize);
35934      return SQLITE_NOMEM;
35935    }
35936    pWinMemData->bOwned = TRUE;
35937    assert( pWinMemData->bOwned );
35938  }
35939#else
35940  pWinMemData->hHeap = osGetProcessHeap();
35941  if( !pWinMemData->hHeap ){
35942    sqlite3_log(SQLITE_NOMEM,
35943        "failed to GetProcessHeap (%lu)", osGetLastError());
35944    return SQLITE_NOMEM;
35945  }
35946  pWinMemData->bOwned = FALSE;
35947  assert( !pWinMemData->bOwned );
35948#endif
35949  assert( pWinMemData->hHeap!=0 );
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  return SQLITE_OK;
35955}
35956
35957/*
35958** Deinitialize this module.
35959*/
35960static void winMemShutdown(void *pAppData){
35961  winMemData *pWinMemData = (winMemData *)pAppData;
35962
35963  if( !pWinMemData ) return;
35964  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
35965  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
35966
35967  if( pWinMemData->hHeap ){
35968    assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
35969#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
35970    assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
35971#endif
35972    if( pWinMemData->bOwned ){
35973      if( !osHeapDestroy(pWinMemData->hHeap) ){
35974        sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
35975                    osGetLastError(), (void*)pWinMemData->hHeap);
35976      }
35977      pWinMemData->bOwned = FALSE;
35978    }
35979    pWinMemData->hHeap = NULL;
35980  }
35981}
35982
35983/*
35984** Populate the low-level memory allocation function pointers in
35985** sqlite3GlobalConfig.m with pointers to the routines in this file. The
35986** arguments specify the block of memory to manage.
35987**
35988** This routine is only called by sqlite3_config(), and therefore
35989** is not required to be threadsafe (it is not).
35990*/
35991SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
35992  static const sqlite3_mem_methods winMemMethods = {
35993    winMemMalloc,
35994    winMemFree,
35995    winMemRealloc,
35996    winMemSize,
35997    winMemRoundup,
35998    winMemInit,
35999    winMemShutdown,
36000    &win_mem_data
36001  };
36002  return &winMemMethods;
36003}
36004
36005SQLITE_PRIVATE void sqlite3MemSetDefault(void){
36006  sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
36007}
36008#endif /* SQLITE_WIN32_MALLOC */
36009
36010/*
36011** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
36012**
36013** Space to hold the returned string is obtained from malloc.
36014*/
36015static LPWSTR winUtf8ToUnicode(const char *zFilename){
36016  int nChar;
36017  LPWSTR zWideFilename;
36018
36019  nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
36020  if( nChar==0 ){
36021    return 0;
36022  }
36023  zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
36024  if( zWideFilename==0 ){
36025    return 0;
36026  }
36027  nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
36028                                nChar);
36029  if( nChar==0 ){
36030    sqlite3_free(zWideFilename);
36031    zWideFilename = 0;
36032  }
36033  return zWideFilename;
36034}
36035
36036/*
36037** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
36038** obtained from sqlite3_malloc().
36039*/
36040static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
36041  int nByte;
36042  char *zFilename;
36043
36044  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
36045  if( nByte == 0 ){
36046    return 0;
36047  }
36048  zFilename = sqlite3MallocZero( nByte );
36049  if( zFilename==0 ){
36050    return 0;
36051  }
36052  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
36053                                0, 0);
36054  if( nByte == 0 ){
36055    sqlite3_free(zFilename);
36056    zFilename = 0;
36057  }
36058  return zFilename;
36059}
36060
36061/*
36062** Convert an ANSI string to Microsoft Unicode, based on the
36063** current codepage settings for file apis.
36064**
36065** Space to hold the returned string is obtained
36066** from sqlite3_malloc.
36067*/
36068static LPWSTR winMbcsToUnicode(const char *zFilename){
36069  int nByte;
36070  LPWSTR zMbcsFilename;
36071  int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
36072
36073  nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
36074                                0)*sizeof(WCHAR);
36075  if( nByte==0 ){
36076    return 0;
36077  }
36078  zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
36079  if( zMbcsFilename==0 ){
36080    return 0;
36081  }
36082  nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
36083                                nByte);
36084  if( nByte==0 ){
36085    sqlite3_free(zMbcsFilename);
36086    zMbcsFilename = 0;
36087  }
36088  return zMbcsFilename;
36089}
36090
36091/*
36092** Convert Microsoft Unicode to multi-byte character string, based on the
36093** user's ANSI codepage.
36094**
36095** Space to hold the returned string is obtained from
36096** sqlite3_malloc().
36097*/
36098static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
36099  int nByte;
36100  char *zFilename;
36101  int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
36102
36103  nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
36104  if( nByte == 0 ){
36105    return 0;
36106  }
36107  zFilename = sqlite3MallocZero( nByte );
36108  if( zFilename==0 ){
36109    return 0;
36110  }
36111  nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
36112                                nByte, 0, 0);
36113  if( nByte == 0 ){
36114    sqlite3_free(zFilename);
36115    zFilename = 0;
36116  }
36117  return zFilename;
36118}
36119
36120/*
36121** Convert multibyte character string to UTF-8.  Space to hold the
36122** returned string is obtained from sqlite3_malloc().
36123*/
36124SQLITE_API char *SQLITE_STDCALL sqlite3_win32_mbcs_to_utf8(const char *zFilename){
36125  char *zFilenameUtf8;
36126  LPWSTR zTmpWide;
36127
36128  zTmpWide = winMbcsToUnicode(zFilename);
36129  if( zTmpWide==0 ){
36130    return 0;
36131  }
36132  zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
36133  sqlite3_free(zTmpWide);
36134  return zFilenameUtf8;
36135}
36136
36137/*
36138** Convert UTF-8 to multibyte character string.  Space to hold the
36139** returned string is obtained from sqlite3_malloc().
36140*/
36141SQLITE_API char *SQLITE_STDCALL sqlite3_win32_utf8_to_mbcs(const char *zFilename){
36142  char *zFilenameMbcs;
36143  LPWSTR zTmpWide;
36144
36145  zTmpWide = winUtf8ToUnicode(zFilename);
36146  if( zTmpWide==0 ){
36147    return 0;
36148  }
36149  zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
36150  sqlite3_free(zTmpWide);
36151  return zFilenameMbcs;
36152}
36153
36154/*
36155** This function sets the data directory or the temporary directory based on
36156** the provided arguments.  The type argument must be 1 in order to set the
36157** data directory or 2 in order to set the temporary directory.  The zValue
36158** argument is the name of the directory to use.  The return value will be
36159** SQLITE_OK if successful.
36160*/
36161SQLITE_API int SQLITE_STDCALL sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
36162  char **ppDirectory = 0;
36163#ifndef SQLITE_OMIT_AUTOINIT
36164  int rc = sqlite3_initialize();
36165  if( rc ) return rc;
36166#endif
36167  if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
36168    ppDirectory = &sqlite3_data_directory;
36169  }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
36170    ppDirectory = &sqlite3_temp_directory;
36171  }
36172  assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
36173          || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
36174  );
36175  assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
36176  if( ppDirectory ){
36177    char *zValueUtf8 = 0;
36178    if( zValue && zValue[0] ){
36179      zValueUtf8 = winUnicodeToUtf8(zValue);
36180      if ( zValueUtf8==0 ){
36181        return SQLITE_NOMEM;
36182      }
36183    }
36184    sqlite3_free(*ppDirectory);
36185    *ppDirectory = zValueUtf8;
36186    return SQLITE_OK;
36187  }
36188  return SQLITE_ERROR;
36189}
36190
36191/*
36192** The return value of winGetLastErrorMsg
36193** is zero if the error message fits in the buffer, or non-zero
36194** otherwise (if the message was truncated).
36195*/
36196static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
36197  /* FormatMessage returns 0 on failure.  Otherwise it
36198  ** returns the number of TCHARs written to the output
36199  ** buffer, excluding the terminating null char.
36200  */
36201  DWORD dwLen = 0;
36202  char *zOut = 0;
36203
36204  if( osIsNT() ){
36205#if SQLITE_OS_WINRT
36206    WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
36207    dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
36208                             FORMAT_MESSAGE_IGNORE_INSERTS,
36209                             NULL,
36210                             lastErrno,
36211                             0,
36212                             zTempWide,
36213                             SQLITE_WIN32_MAX_ERRMSG_CHARS,
36214                             0);
36215#else
36216    LPWSTR zTempWide = NULL;
36217    dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
36218                             FORMAT_MESSAGE_FROM_SYSTEM |
36219                             FORMAT_MESSAGE_IGNORE_INSERTS,
36220                             NULL,
36221                             lastErrno,
36222                             0,
36223                             (LPWSTR) &zTempWide,
36224                             0,
36225                             0);
36226#endif
36227    if( dwLen > 0 ){
36228      /* allocate a buffer and convert to UTF8 */
36229      sqlite3BeginBenignMalloc();
36230      zOut = winUnicodeToUtf8(zTempWide);
36231      sqlite3EndBenignMalloc();
36232#if !SQLITE_OS_WINRT
36233      /* free the system buffer allocated by FormatMessage */
36234      osLocalFree(zTempWide);
36235#endif
36236    }
36237  }
36238#ifdef SQLITE_WIN32_HAS_ANSI
36239  else{
36240    char *zTemp = NULL;
36241    dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
36242                             FORMAT_MESSAGE_FROM_SYSTEM |
36243                             FORMAT_MESSAGE_IGNORE_INSERTS,
36244                             NULL,
36245                             lastErrno,
36246                             0,
36247                             (LPSTR) &zTemp,
36248                             0,
36249                             0);
36250    if( dwLen > 0 ){
36251      /* allocate a buffer and convert to UTF8 */
36252      sqlite3BeginBenignMalloc();
36253      zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
36254      sqlite3EndBenignMalloc();
36255      /* free the system buffer allocated by FormatMessage */
36256      osLocalFree(zTemp);
36257    }
36258  }
36259#endif
36260  if( 0 == dwLen ){
36261    sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
36262  }else{
36263    /* copy a maximum of nBuf chars to output buffer */
36264    sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
36265    /* free the UTF8 buffer */
36266    sqlite3_free(zOut);
36267  }
36268  return 0;
36269}
36270
36271/*
36272**
36273** This function - winLogErrorAtLine() - is only ever called via the macro
36274** winLogError().
36275**
36276** This routine is invoked after an error occurs in an OS function.
36277** It logs a message using sqlite3_log() containing the current value of
36278** error code and, if possible, the human-readable equivalent from
36279** FormatMessage.
36280**
36281** The first argument passed to the macro should be the error code that
36282** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
36283** The two subsequent arguments should be the name of the OS function that
36284** failed and the associated file-system path, if any.
36285*/
36286#define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
36287static int winLogErrorAtLine(
36288  int errcode,                    /* SQLite error code */
36289  DWORD lastErrno,                /* Win32 last error */
36290  const char *zFunc,              /* Name of OS function that failed */
36291  const char *zPath,              /* File path associated with error */
36292  int iLine                       /* Source line number where error occurred */
36293){
36294  char zMsg[500];                 /* Human readable error text */
36295  int i;                          /* Loop counter */
36296
36297  zMsg[0] = 0;
36298  winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
36299  assert( errcode!=SQLITE_OK );
36300  if( zPath==0 ) zPath = "";
36301  for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
36302  zMsg[i] = 0;
36303  sqlite3_log(errcode,
36304      "os_win.c:%d: (%lu) %s(%s) - %s",
36305      iLine, lastErrno, zFunc, zPath, zMsg
36306  );
36307
36308  return errcode;
36309}
36310
36311/*
36312** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
36313** will be retried following a locking error - probably caused by
36314** antivirus software.  Also the initial delay before the first retry.
36315** The delay increases linearly with each retry.
36316*/
36317#ifndef SQLITE_WIN32_IOERR_RETRY
36318# define SQLITE_WIN32_IOERR_RETRY 10
36319#endif
36320#ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
36321# define SQLITE_WIN32_IOERR_RETRY_DELAY 25
36322#endif
36323static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
36324static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
36325
36326/*
36327** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
36328** error code obtained via GetLastError() is eligible to be retried.  It
36329** must accept the error code DWORD as its only argument and should return
36330** non-zero if the error code is transient in nature and the operation
36331** responsible for generating the original error might succeed upon being
36332** retried.  The argument to this macro should be a variable.
36333**
36334** Additionally, a macro named "winIoerrCanRetry2" may be defined.  If it
36335** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
36336** returns zero.  The "winIoerrCanRetry2" macro is completely optional and
36337** may be used to include additional error codes in the set that should
36338** result in the failing I/O operation being retried by the caller.  If
36339** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
36340** identical to those of the "winIoerrCanRetry1" macro.
36341*/
36342#if !defined(winIoerrCanRetry1)
36343#define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED)        || \
36344                              ((a)==ERROR_SHARING_VIOLATION)    || \
36345                              ((a)==ERROR_LOCK_VIOLATION)       || \
36346                              ((a)==ERROR_DEV_NOT_EXIST)        || \
36347                              ((a)==ERROR_NETNAME_DELETED)      || \
36348                              ((a)==ERROR_SEM_TIMEOUT)          || \
36349                              ((a)==ERROR_NETWORK_UNREACHABLE))
36350#endif
36351
36352/*
36353** If a ReadFile() or WriteFile() error occurs, invoke this routine
36354** to see if it should be retried.  Return TRUE to retry.  Return FALSE
36355** to give up with an error.
36356*/
36357static int winRetryIoerr(int *pnRetry, DWORD *pError){
36358  DWORD e = osGetLastError();
36359  if( *pnRetry>=winIoerrRetry ){
36360    if( pError ){
36361      *pError = e;
36362    }
36363    return 0;
36364  }
36365  if( winIoerrCanRetry1(e) ){
36366    sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
36367    ++*pnRetry;
36368    return 1;
36369  }
36370#if defined(winIoerrCanRetry2)
36371  else if( winIoerrCanRetry2(e) ){
36372    sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
36373    ++*pnRetry;
36374    return 1;
36375  }
36376#endif
36377  if( pError ){
36378    *pError = e;
36379  }
36380  return 0;
36381}
36382
36383/*
36384** Log a I/O error retry episode.
36385*/
36386static void winLogIoerr(int nRetry, int lineno){
36387  if( nRetry ){
36388    sqlite3_log(SQLITE_NOTICE,
36389      "delayed %dms for lock/sharing conflict at line %d",
36390      winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
36391    );
36392  }
36393}
36394
36395#if SQLITE_OS_WINCE
36396/*************************************************************************
36397** This section contains code for WinCE only.
36398*/
36399#if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
36400/*
36401** The MSVC CRT on Windows CE may not have a localtime() function.  So
36402** create a substitute.
36403*/
36404/* #include <time.h> */
36405struct tm *__cdecl localtime(const time_t *t)
36406{
36407  static struct tm y;
36408  FILETIME uTm, lTm;
36409  SYSTEMTIME pTm;
36410  sqlite3_int64 t64;
36411  t64 = *t;
36412  t64 = (t64 + 11644473600)*10000000;
36413  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
36414  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
36415  osFileTimeToLocalFileTime(&uTm,&lTm);
36416  osFileTimeToSystemTime(&lTm,&pTm);
36417  y.tm_year = pTm.wYear - 1900;
36418  y.tm_mon = pTm.wMonth - 1;
36419  y.tm_wday = pTm.wDayOfWeek;
36420  y.tm_mday = pTm.wDay;
36421  y.tm_hour = pTm.wHour;
36422  y.tm_min = pTm.wMinute;
36423  y.tm_sec = pTm.wSecond;
36424  return &y;
36425}
36426#endif
36427
36428#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
36429
36430/*
36431** Acquire a lock on the handle h
36432*/
36433static void winceMutexAcquire(HANDLE h){
36434   DWORD dwErr;
36435   do {
36436     dwErr = osWaitForSingleObject(h, INFINITE);
36437   } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
36438}
36439/*
36440** Release a lock acquired by winceMutexAcquire()
36441*/
36442#define winceMutexRelease(h) ReleaseMutex(h)
36443
36444/*
36445** Create the mutex and shared memory used for locking in the file
36446** descriptor pFile
36447*/
36448static int winceCreateLock(const char *zFilename, winFile *pFile){
36449  LPWSTR zTok;
36450  LPWSTR zName;
36451  DWORD lastErrno;
36452  BOOL bLogged = FALSE;
36453  BOOL bInit = TRUE;
36454
36455  zName = winUtf8ToUnicode(zFilename);
36456  if( zName==0 ){
36457    /* out of memory */
36458    return SQLITE_IOERR_NOMEM;
36459  }
36460
36461  /* Initialize the local lockdata */
36462  memset(&pFile->local, 0, sizeof(pFile->local));
36463
36464  /* Replace the backslashes from the filename and lowercase it
36465  ** to derive a mutex name. */
36466  zTok = osCharLowerW(zName);
36467  for (;*zTok;zTok++){
36468    if (*zTok == '\\') *zTok = '_';
36469  }
36470
36471  /* Create/open the named mutex */
36472  pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
36473  if (!pFile->hMutex){
36474    pFile->lastErrno = osGetLastError();
36475    sqlite3_free(zName);
36476    return winLogError(SQLITE_IOERR, pFile->lastErrno,
36477                       "winceCreateLock1", zFilename);
36478  }
36479
36480  /* Acquire the mutex before continuing */
36481  winceMutexAcquire(pFile->hMutex);
36482
36483  /* Since the names of named mutexes, semaphores, file mappings etc are
36484  ** case-sensitive, take advantage of that by uppercasing the mutex name
36485  ** and using that as the shared filemapping name.
36486  */
36487  osCharUpperW(zName);
36488  pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
36489                                        PAGE_READWRITE, 0, sizeof(winceLock),
36490                                        zName);
36491
36492  /* Set a flag that indicates we're the first to create the memory so it
36493  ** must be zero-initialized */
36494  lastErrno = osGetLastError();
36495  if (lastErrno == ERROR_ALREADY_EXISTS){
36496    bInit = FALSE;
36497  }
36498
36499  sqlite3_free(zName);
36500
36501  /* If we succeeded in making the shared memory handle, map it. */
36502  if( pFile->hShared ){
36503    pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
36504             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
36505    /* If mapping failed, close the shared memory handle and erase it */
36506    if( !pFile->shared ){
36507      pFile->lastErrno = osGetLastError();
36508      winLogError(SQLITE_IOERR, pFile->lastErrno,
36509                  "winceCreateLock2", zFilename);
36510      bLogged = TRUE;
36511      osCloseHandle(pFile->hShared);
36512      pFile->hShared = NULL;
36513    }
36514  }
36515
36516  /* If shared memory could not be created, then close the mutex and fail */
36517  if( pFile->hShared==NULL ){
36518    if( !bLogged ){
36519      pFile->lastErrno = lastErrno;
36520      winLogError(SQLITE_IOERR, pFile->lastErrno,
36521                  "winceCreateLock3", zFilename);
36522      bLogged = TRUE;
36523    }
36524    winceMutexRelease(pFile->hMutex);
36525    osCloseHandle(pFile->hMutex);
36526    pFile->hMutex = NULL;
36527    return SQLITE_IOERR;
36528  }
36529
36530  /* Initialize the shared memory if we're supposed to */
36531  if( bInit ){
36532    memset(pFile->shared, 0, sizeof(winceLock));
36533  }
36534
36535  winceMutexRelease(pFile->hMutex);
36536  return SQLITE_OK;
36537}
36538
36539/*
36540** Destroy the part of winFile that deals with wince locks
36541*/
36542static void winceDestroyLock(winFile *pFile){
36543  if (pFile->hMutex){
36544    /* Acquire the mutex */
36545    winceMutexAcquire(pFile->hMutex);
36546
36547    /* The following blocks should probably assert in debug mode, but they
36548       are to cleanup in case any locks remained open */
36549    if (pFile->local.nReaders){
36550      pFile->shared->nReaders --;
36551    }
36552    if (pFile->local.bReserved){
36553      pFile->shared->bReserved = FALSE;
36554    }
36555    if (pFile->local.bPending){
36556      pFile->shared->bPending = FALSE;
36557    }
36558    if (pFile->local.bExclusive){
36559      pFile->shared->bExclusive = FALSE;
36560    }
36561
36562    /* De-reference and close our copy of the shared memory handle */
36563    osUnmapViewOfFile(pFile->shared);
36564    osCloseHandle(pFile->hShared);
36565
36566    /* Done with the mutex */
36567    winceMutexRelease(pFile->hMutex);
36568    osCloseHandle(pFile->hMutex);
36569    pFile->hMutex = NULL;
36570  }
36571}
36572
36573/*
36574** An implementation of the LockFile() API of Windows for CE
36575*/
36576static BOOL winceLockFile(
36577  LPHANDLE phFile,
36578  DWORD dwFileOffsetLow,
36579  DWORD dwFileOffsetHigh,
36580  DWORD nNumberOfBytesToLockLow,
36581  DWORD nNumberOfBytesToLockHigh
36582){
36583  winFile *pFile = HANDLE_TO_WINFILE(phFile);
36584  BOOL bReturn = FALSE;
36585
36586  UNUSED_PARAMETER(dwFileOffsetHigh);
36587  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
36588
36589  if (!pFile->hMutex) return TRUE;
36590  winceMutexAcquire(pFile->hMutex);
36591
36592  /* Wanting an exclusive lock? */
36593  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
36594       && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
36595    if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
36596       pFile->shared->bExclusive = TRUE;
36597       pFile->local.bExclusive = TRUE;
36598       bReturn = TRUE;
36599    }
36600  }
36601
36602  /* Want a read-only lock? */
36603  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
36604           nNumberOfBytesToLockLow == 1){
36605    if (pFile->shared->bExclusive == 0){
36606      pFile->local.nReaders ++;
36607      if (pFile->local.nReaders == 1){
36608        pFile->shared->nReaders ++;
36609      }
36610      bReturn = TRUE;
36611    }
36612  }
36613
36614  /* Want a pending lock? */
36615  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
36616           && nNumberOfBytesToLockLow == 1){
36617    /* If no pending lock has been acquired, then acquire it */
36618    if (pFile->shared->bPending == 0) {
36619      pFile->shared->bPending = TRUE;
36620      pFile->local.bPending = TRUE;
36621      bReturn = TRUE;
36622    }
36623  }
36624
36625  /* Want a reserved lock? */
36626  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
36627           && nNumberOfBytesToLockLow == 1){
36628    if (pFile->shared->bReserved == 0) {
36629      pFile->shared->bReserved = TRUE;
36630      pFile->local.bReserved = TRUE;
36631      bReturn = TRUE;
36632    }
36633  }
36634
36635  winceMutexRelease(pFile->hMutex);
36636  return bReturn;
36637}
36638
36639/*
36640** An implementation of the UnlockFile API of Windows for CE
36641*/
36642static BOOL winceUnlockFile(
36643  LPHANDLE phFile,
36644  DWORD dwFileOffsetLow,
36645  DWORD dwFileOffsetHigh,
36646  DWORD nNumberOfBytesToUnlockLow,
36647  DWORD nNumberOfBytesToUnlockHigh
36648){
36649  winFile *pFile = HANDLE_TO_WINFILE(phFile);
36650  BOOL bReturn = FALSE;
36651
36652  UNUSED_PARAMETER(dwFileOffsetHigh);
36653  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
36654
36655  if (!pFile->hMutex) return TRUE;
36656  winceMutexAcquire(pFile->hMutex);
36657
36658  /* Releasing a reader lock or an exclusive lock */
36659  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
36660    /* Did we have an exclusive lock? */
36661    if (pFile->local.bExclusive){
36662      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
36663      pFile->local.bExclusive = FALSE;
36664      pFile->shared->bExclusive = FALSE;
36665      bReturn = TRUE;
36666    }
36667
36668    /* Did we just have a reader lock? */
36669    else if (pFile->local.nReaders){
36670      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
36671             || nNumberOfBytesToUnlockLow == 1);
36672      pFile->local.nReaders --;
36673      if (pFile->local.nReaders == 0)
36674      {
36675        pFile->shared->nReaders --;
36676      }
36677      bReturn = TRUE;
36678    }
36679  }
36680
36681  /* Releasing a pending lock */
36682  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
36683           && nNumberOfBytesToUnlockLow == 1){
36684    if (pFile->local.bPending){
36685      pFile->local.bPending = FALSE;
36686      pFile->shared->bPending = FALSE;
36687      bReturn = TRUE;
36688    }
36689  }
36690  /* Releasing a reserved lock */
36691  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
36692           && nNumberOfBytesToUnlockLow == 1){
36693    if (pFile->local.bReserved) {
36694      pFile->local.bReserved = FALSE;
36695      pFile->shared->bReserved = FALSE;
36696      bReturn = TRUE;
36697    }
36698  }
36699
36700  winceMutexRelease(pFile->hMutex);
36701  return bReturn;
36702}
36703/*
36704** End of the special code for wince
36705*****************************************************************************/
36706#endif /* SQLITE_OS_WINCE */
36707
36708/*
36709** Lock a file region.
36710*/
36711static BOOL winLockFile(
36712  LPHANDLE phFile,
36713  DWORD flags,
36714  DWORD offsetLow,
36715  DWORD offsetHigh,
36716  DWORD numBytesLow,
36717  DWORD numBytesHigh
36718){
36719#if SQLITE_OS_WINCE
36720  /*
36721  ** NOTE: Windows CE is handled differently here due its lack of the Win32
36722  **       API LockFile.
36723  */
36724  return winceLockFile(phFile, offsetLow, offsetHigh,
36725                       numBytesLow, numBytesHigh);
36726#else
36727  if( osIsNT() ){
36728    OVERLAPPED ovlp;
36729    memset(&ovlp, 0, sizeof(OVERLAPPED));
36730    ovlp.Offset = offsetLow;
36731    ovlp.OffsetHigh = offsetHigh;
36732    return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
36733  }else{
36734    return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
36735                      numBytesHigh);
36736  }
36737#endif
36738}
36739
36740/*
36741** Unlock a file region.
36742 */
36743static BOOL winUnlockFile(
36744  LPHANDLE phFile,
36745  DWORD offsetLow,
36746  DWORD offsetHigh,
36747  DWORD numBytesLow,
36748  DWORD numBytesHigh
36749){
36750#if SQLITE_OS_WINCE
36751  /*
36752  ** NOTE: Windows CE is handled differently here due its lack of the Win32
36753  **       API UnlockFile.
36754  */
36755  return winceUnlockFile(phFile, offsetLow, offsetHigh,
36756                         numBytesLow, numBytesHigh);
36757#else
36758  if( osIsNT() ){
36759    OVERLAPPED ovlp;
36760    memset(&ovlp, 0, sizeof(OVERLAPPED));
36761    ovlp.Offset = offsetLow;
36762    ovlp.OffsetHigh = offsetHigh;
36763    return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
36764  }else{
36765    return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
36766                        numBytesHigh);
36767  }
36768#endif
36769}
36770
36771/*****************************************************************************
36772** The next group of routines implement the I/O methods specified
36773** by the sqlite3_io_methods object.
36774******************************************************************************/
36775
36776/*
36777** Some Microsoft compilers lack this definition.
36778*/
36779#ifndef INVALID_SET_FILE_POINTER
36780# define INVALID_SET_FILE_POINTER ((DWORD)-1)
36781#endif
36782
36783/*
36784** Move the current position of the file handle passed as the first
36785** argument to offset iOffset within the file. If successful, return 0.
36786** Otherwise, set pFile->lastErrno and return non-zero.
36787*/
36788static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
36789#if !SQLITE_OS_WINRT
36790  LONG upperBits;                 /* Most sig. 32 bits of new offset */
36791  LONG lowerBits;                 /* Least sig. 32 bits of new offset */
36792  DWORD dwRet;                    /* Value returned by SetFilePointer() */
36793  DWORD lastErrno;                /* Value returned by GetLastError() */
36794
36795  OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
36796
36797  upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
36798  lowerBits = (LONG)(iOffset & 0xffffffff);
36799
36800  /* API oddity: If successful, SetFilePointer() returns a dword
36801  ** containing the lower 32-bits of the new file-offset. Or, if it fails,
36802  ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
36803  ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
36804  ** whether an error has actually occurred, it is also necessary to call
36805  ** GetLastError().
36806  */
36807  dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
36808
36809  if( (dwRet==INVALID_SET_FILE_POINTER
36810      && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
36811    pFile->lastErrno = lastErrno;
36812    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
36813                "winSeekFile", pFile->zPath);
36814    OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
36815    return 1;
36816  }
36817
36818  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
36819  return 0;
36820#else
36821  /*
36822  ** Same as above, except that this implementation works for WinRT.
36823  */
36824
36825  LARGE_INTEGER x;                /* The new offset */
36826  BOOL bRet;                      /* Value returned by SetFilePointerEx() */
36827
36828  x.QuadPart = iOffset;
36829  bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
36830
36831  if(!bRet){
36832    pFile->lastErrno = osGetLastError();
36833    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
36834                "winSeekFile", pFile->zPath);
36835    OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
36836    return 1;
36837  }
36838
36839  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
36840  return 0;
36841#endif
36842}
36843
36844#if SQLITE_MAX_MMAP_SIZE>0
36845/* Forward references to VFS helper methods used for memory mapped files */
36846static int winMapfile(winFile*, sqlite3_int64);
36847static int winUnmapfile(winFile*);
36848#endif
36849
36850/*
36851** Close a file.
36852**
36853** It is reported that an attempt to close a handle might sometimes
36854** fail.  This is a very unreasonable result, but Windows is notorious
36855** for being unreasonable so I do not doubt that it might happen.  If
36856** the close fails, we pause for 100 milliseconds and try again.  As
36857** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
36858** giving up and returning an error.
36859*/
36860#define MX_CLOSE_ATTEMPT 3
36861static int winClose(sqlite3_file *id){
36862  int rc, cnt = 0;
36863  winFile *pFile = (winFile*)id;
36864
36865  assert( id!=0 );
36866#ifndef SQLITE_OMIT_WAL
36867  assert( pFile->pShm==0 );
36868#endif
36869  assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
36870  OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
36871           osGetCurrentProcessId(), pFile, pFile->h));
36872
36873#if SQLITE_MAX_MMAP_SIZE>0
36874  winUnmapfile(pFile);
36875#endif
36876
36877  do{
36878    rc = osCloseHandle(pFile->h);
36879    /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
36880  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
36881#if SQLITE_OS_WINCE
36882#define WINCE_DELETION_ATTEMPTS 3
36883  winceDestroyLock(pFile);
36884  if( pFile->zDeleteOnClose ){
36885    int cnt = 0;
36886    while(
36887           osDeleteFileW(pFile->zDeleteOnClose)==0
36888        && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
36889        && cnt++ < WINCE_DELETION_ATTEMPTS
36890    ){
36891       sqlite3_win32_sleep(100);  /* Wait a little before trying again */
36892    }
36893    sqlite3_free(pFile->zDeleteOnClose);
36894  }
36895#endif
36896  if( rc ){
36897    pFile->h = NULL;
36898  }
36899  OpenCounter(-1);
36900  OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
36901           osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
36902  return rc ? SQLITE_OK
36903            : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
36904                          "winClose", pFile->zPath);
36905}
36906
36907/*
36908** Read data from a file into a buffer.  Return SQLITE_OK if all
36909** bytes were read successfully and SQLITE_IOERR if anything goes
36910** wrong.
36911*/
36912static int winRead(
36913  sqlite3_file *id,          /* File to read from */
36914  void *pBuf,                /* Write content into this buffer */
36915  int amt,                   /* Number of bytes to read */
36916  sqlite3_int64 offset       /* Begin reading at this offset */
36917){
36918#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
36919  OVERLAPPED overlapped;          /* The offset for ReadFile. */
36920#endif
36921  winFile *pFile = (winFile*)id;  /* file handle */
36922  DWORD nRead;                    /* Number of bytes actually read from file */
36923  int nRetry = 0;                 /* Number of retrys */
36924
36925  assert( id!=0 );
36926  assert( amt>0 );
36927  assert( offset>=0 );
36928  SimulateIOError(return SQLITE_IOERR_READ);
36929  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
36930           "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
36931           pFile->h, pBuf, amt, offset, pFile->locktype));
36932
36933#if SQLITE_MAX_MMAP_SIZE>0
36934  /* Deal with as much of this read request as possible by transfering
36935  ** data from the memory mapping using memcpy().  */
36936  if( offset<pFile->mmapSize ){
36937    if( offset+amt <= pFile->mmapSize ){
36938      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
36939      OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
36940               osGetCurrentProcessId(), pFile, pFile->h));
36941      return SQLITE_OK;
36942    }else{
36943      int nCopy = (int)(pFile->mmapSize - offset);
36944      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
36945      pBuf = &((u8 *)pBuf)[nCopy];
36946      amt -= nCopy;
36947      offset += nCopy;
36948    }
36949  }
36950#endif
36951
36952#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
36953  if( winSeekFile(pFile, offset) ){
36954    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
36955             osGetCurrentProcessId(), pFile, pFile->h));
36956    return SQLITE_FULL;
36957  }
36958  while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
36959#else
36960  memset(&overlapped, 0, sizeof(OVERLAPPED));
36961  overlapped.Offset = (LONG)(offset & 0xffffffff);
36962  overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
36963  while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
36964         osGetLastError()!=ERROR_HANDLE_EOF ){
36965#endif
36966    DWORD lastErrno;
36967    if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
36968    pFile->lastErrno = lastErrno;
36969    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
36970             osGetCurrentProcessId(), pFile, pFile->h));
36971    return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
36972                       "winRead", pFile->zPath);
36973  }
36974  winLogIoerr(nRetry, __LINE__);
36975  if( nRead<(DWORD)amt ){
36976    /* Unread parts of the buffer must be zero-filled */
36977    memset(&((char*)pBuf)[nRead], 0, amt-nRead);
36978    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
36979             osGetCurrentProcessId(), pFile, pFile->h));
36980    return SQLITE_IOERR_SHORT_READ;
36981  }
36982
36983  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
36984           osGetCurrentProcessId(), pFile, pFile->h));
36985  return SQLITE_OK;
36986}
36987
36988/*
36989** Write data from a buffer into a file.  Return SQLITE_OK on success
36990** or some other error code on failure.
36991*/
36992static int winWrite(
36993  sqlite3_file *id,               /* File to write into */
36994  const void *pBuf,               /* The bytes to be written */
36995  int amt,                        /* Number of bytes to write */
36996  sqlite3_int64 offset            /* Offset into the file to begin writing at */
36997){
36998  int rc = 0;                     /* True if error has occurred, else false */
36999  winFile *pFile = (winFile*)id;  /* File handle */
37000  int nRetry = 0;                 /* Number of retries */
37001
37002  assert( amt>0 );
37003  assert( pFile );
37004  SimulateIOError(return SQLITE_IOERR_WRITE);
37005  SimulateDiskfullError(return SQLITE_FULL);
37006
37007  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
37008           "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
37009           pFile->h, pBuf, amt, offset, pFile->locktype));
37010
37011#if SQLITE_MAX_MMAP_SIZE>0
37012  /* Deal with as much of this write request as possible by transfering
37013  ** data from the memory mapping using memcpy().  */
37014  if( offset<pFile->mmapSize ){
37015    if( offset+amt <= pFile->mmapSize ){
37016      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
37017      OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
37018               osGetCurrentProcessId(), pFile, pFile->h));
37019      return SQLITE_OK;
37020    }else{
37021      int nCopy = (int)(pFile->mmapSize - offset);
37022      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
37023      pBuf = &((u8 *)pBuf)[nCopy];
37024      amt -= nCopy;
37025      offset += nCopy;
37026    }
37027  }
37028#endif
37029
37030#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
37031  rc = winSeekFile(pFile, offset);
37032  if( rc==0 ){
37033#else
37034  {
37035#endif
37036#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
37037    OVERLAPPED overlapped;        /* The offset for WriteFile. */
37038#endif
37039    u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
37040    int nRem = amt;               /* Number of bytes yet to be written */
37041    DWORD nWrite;                 /* Bytes written by each WriteFile() call */
37042    DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
37043
37044#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
37045    memset(&overlapped, 0, sizeof(OVERLAPPED));
37046    overlapped.Offset = (LONG)(offset & 0xffffffff);
37047    overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
37048#endif
37049
37050    while( nRem>0 ){
37051#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
37052      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
37053#else
37054      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
37055#endif
37056        if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
37057        break;
37058      }
37059      assert( nWrite==0 || nWrite<=(DWORD)nRem );
37060      if( nWrite==0 || nWrite>(DWORD)nRem ){
37061        lastErrno = osGetLastError();
37062        break;
37063      }
37064#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
37065      offset += nWrite;
37066      overlapped.Offset = (LONG)(offset & 0xffffffff);
37067      overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
37068#endif
37069      aRem += nWrite;
37070      nRem -= nWrite;
37071    }
37072    if( nRem>0 ){
37073      pFile->lastErrno = lastErrno;
37074      rc = 1;
37075    }
37076  }
37077
37078  if( rc ){
37079    if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
37080       || ( pFile->lastErrno==ERROR_DISK_FULL )){
37081      OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
37082               osGetCurrentProcessId(), pFile, pFile->h));
37083      return winLogError(SQLITE_FULL, pFile->lastErrno,
37084                         "winWrite1", pFile->zPath);
37085    }
37086    OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
37087             osGetCurrentProcessId(), pFile, pFile->h));
37088    return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
37089                       "winWrite2", pFile->zPath);
37090  }else{
37091    winLogIoerr(nRetry, __LINE__);
37092  }
37093  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
37094           osGetCurrentProcessId(), pFile, pFile->h));
37095  return SQLITE_OK;
37096}
37097
37098/*
37099** Truncate an open file to a specified size
37100*/
37101static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
37102  winFile *pFile = (winFile*)id;  /* File handle object */
37103  int rc = SQLITE_OK;             /* Return code for this function */
37104  DWORD lastErrno;
37105
37106  assert( pFile );
37107  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
37108  OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
37109           osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
37110
37111  /* If the user has configured a chunk-size for this file, truncate the
37112  ** file so that it consists of an integer number of chunks (i.e. the
37113  ** actual file size after the operation may be larger than the requested
37114  ** size).
37115  */
37116  if( pFile->szChunk>0 ){
37117    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
37118  }
37119
37120  /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
37121  if( winSeekFile(pFile, nByte) ){
37122    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
37123                     "winTruncate1", pFile->zPath);
37124  }else if( 0==osSetEndOfFile(pFile->h) &&
37125            ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
37126    pFile->lastErrno = lastErrno;
37127    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
37128                     "winTruncate2", pFile->zPath);
37129  }
37130
37131#if SQLITE_MAX_MMAP_SIZE>0
37132  /* If the file was truncated to a size smaller than the currently
37133  ** mapped region, reduce the effective mapping size as well. SQLite will
37134  ** use read() and write() to access data beyond this point from now on.
37135  */
37136  if( pFile->pMapRegion && nByte<pFile->mmapSize ){
37137    pFile->mmapSize = nByte;
37138  }
37139#endif
37140
37141  OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
37142           osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
37143  return rc;
37144}
37145
37146#ifdef SQLITE_TEST
37147/*
37148** Count the number of fullsyncs and normal syncs.  This is used to test
37149** that syncs and fullsyncs are occuring at the right times.
37150*/
37151SQLITE_API int sqlite3_sync_count = 0;
37152SQLITE_API int sqlite3_fullsync_count = 0;
37153#endif
37154
37155/*
37156** Make sure all writes to a particular file are committed to disk.
37157*/
37158static int winSync(sqlite3_file *id, int flags){
37159#ifndef SQLITE_NO_SYNC
37160  /*
37161  ** Used only when SQLITE_NO_SYNC is not defined.
37162   */
37163  BOOL rc;
37164#endif
37165#if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
37166    defined(SQLITE_HAVE_OS_TRACE)
37167  /*
37168  ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
37169  ** OSTRACE() macros.
37170   */
37171  winFile *pFile = (winFile*)id;
37172#else
37173  UNUSED_PARAMETER(id);
37174#endif
37175
37176  assert( pFile );
37177  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
37178  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
37179      || (flags&0x0F)==SQLITE_SYNC_FULL
37180  );
37181
37182  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
37183  ** line is to test that doing so does not cause any problems.
37184  */
37185  SimulateDiskfullError( return SQLITE_FULL );
37186
37187  OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
37188           osGetCurrentProcessId(), pFile, pFile->h, flags,
37189           pFile->locktype));
37190
37191#ifndef SQLITE_TEST
37192  UNUSED_PARAMETER(flags);
37193#else
37194  if( (flags&0x0F)==SQLITE_SYNC_FULL ){
37195    sqlite3_fullsync_count++;
37196  }
37197  sqlite3_sync_count++;
37198#endif
37199
37200  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
37201  ** no-op
37202  */
37203#ifdef SQLITE_NO_SYNC
37204  OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
37205           osGetCurrentProcessId(), pFile, pFile->h));
37206  return SQLITE_OK;
37207#else
37208#if SQLITE_MAX_MMAP_SIZE>0
37209  if( pFile->pMapRegion ){
37210    if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
37211      OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
37212               "rc=SQLITE_OK\n", osGetCurrentProcessId(),
37213               pFile, pFile->pMapRegion));
37214    }else{
37215      pFile->lastErrno = osGetLastError();
37216      OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
37217               "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
37218               pFile, pFile->pMapRegion));
37219      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
37220                         "winSync1", pFile->zPath);
37221    }
37222  }
37223#endif
37224  rc = osFlushFileBuffers(pFile->h);
37225  SimulateIOError( rc=FALSE );
37226  if( rc ){
37227    OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
37228             osGetCurrentProcessId(), pFile, pFile->h));
37229    return SQLITE_OK;
37230  }else{
37231    pFile->lastErrno = osGetLastError();
37232    OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
37233             osGetCurrentProcessId(), pFile, pFile->h));
37234    return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
37235                       "winSync2", pFile->zPath);
37236  }
37237#endif
37238}
37239
37240/*
37241** Determine the current size of a file in bytes
37242*/
37243static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
37244  winFile *pFile = (winFile*)id;
37245  int rc = SQLITE_OK;
37246
37247  assert( id!=0 );
37248  assert( pSize!=0 );
37249  SimulateIOError(return SQLITE_IOERR_FSTAT);
37250  OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
37251
37252#if SQLITE_OS_WINRT
37253  {
37254    FILE_STANDARD_INFO info;
37255    if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
37256                                     &info, sizeof(info)) ){
37257      *pSize = info.EndOfFile.QuadPart;
37258    }else{
37259      pFile->lastErrno = osGetLastError();
37260      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
37261                       "winFileSize", pFile->zPath);
37262    }
37263  }
37264#else
37265  {
37266    DWORD upperBits;
37267    DWORD lowerBits;
37268    DWORD lastErrno;
37269
37270    lowerBits = osGetFileSize(pFile->h, &upperBits);
37271    *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
37272    if(   (lowerBits == INVALID_FILE_SIZE)
37273       && ((lastErrno = osGetLastError())!=NO_ERROR) ){
37274      pFile->lastErrno = lastErrno;
37275      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
37276                       "winFileSize", pFile->zPath);
37277    }
37278  }
37279#endif
37280  OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
37281           pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
37282  return rc;
37283}
37284
37285/*
37286** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
37287*/
37288#ifndef LOCKFILE_FAIL_IMMEDIATELY
37289# define LOCKFILE_FAIL_IMMEDIATELY 1
37290#endif
37291
37292#ifndef LOCKFILE_EXCLUSIVE_LOCK
37293# define LOCKFILE_EXCLUSIVE_LOCK 2
37294#endif
37295
37296/*
37297** Historically, SQLite has used both the LockFile and LockFileEx functions.
37298** When the LockFile function was used, it was always expected to fail
37299** immediately if the lock could not be obtained.  Also, it always expected to
37300** obtain an exclusive lock.  These flags are used with the LockFileEx function
37301** and reflect those expectations; therefore, they should not be changed.
37302*/
37303#ifndef SQLITE_LOCKFILE_FLAGS
37304# define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
37305                                  LOCKFILE_EXCLUSIVE_LOCK)
37306#endif
37307
37308/*
37309** Currently, SQLite never calls the LockFileEx function without wanting the
37310** call to fail immediately if the lock cannot be obtained.
37311*/
37312#ifndef SQLITE_LOCKFILEEX_FLAGS
37313# define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
37314#endif
37315
37316/*
37317** Acquire a reader lock.
37318** Different API routines are called depending on whether or not this
37319** is Win9x or WinNT.
37320*/
37321static int winGetReadLock(winFile *pFile){
37322  int res;
37323  OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
37324  if( osIsNT() ){
37325#if SQLITE_OS_WINCE
37326    /*
37327    ** NOTE: Windows CE is handled differently here due its lack of the Win32
37328    **       API LockFileEx.
37329    */
37330    res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
37331#else
37332    res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
37333                      SHARED_SIZE, 0);
37334#endif
37335  }
37336#ifdef SQLITE_WIN32_HAS_ANSI
37337  else{
37338    int lk;
37339    sqlite3_randomness(sizeof(lk), &lk);
37340    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
37341    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
37342                      SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
37343  }
37344#endif
37345  if( res == 0 ){
37346    pFile->lastErrno = osGetLastError();
37347    /* No need to log a failure to lock */
37348  }
37349  OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
37350  return res;
37351}
37352
37353/*
37354** Undo a readlock
37355*/
37356static int winUnlockReadLock(winFile *pFile){
37357  int res;
37358  DWORD lastErrno;
37359  OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
37360  if( osIsNT() ){
37361    res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
37362  }
37363#ifdef SQLITE_WIN32_HAS_ANSI
37364  else{
37365    res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
37366  }
37367#endif
37368  if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
37369    pFile->lastErrno = lastErrno;
37370    winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
37371                "winUnlockReadLock", pFile->zPath);
37372  }
37373  OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
37374  return res;
37375}
37376
37377/*
37378** Lock the file with the lock specified by parameter locktype - one
37379** of the following:
37380**
37381**     (1) SHARED_LOCK
37382**     (2) RESERVED_LOCK
37383**     (3) PENDING_LOCK
37384**     (4) EXCLUSIVE_LOCK
37385**
37386** Sometimes when requesting one lock state, additional lock states
37387** are inserted in between.  The locking might fail on one of the later
37388** transitions leaving the lock state different from what it started but
37389** still short of its goal.  The following chart shows the allowed
37390** transitions and the inserted intermediate states:
37391**
37392**    UNLOCKED -> SHARED
37393**    SHARED -> RESERVED
37394**    SHARED -> (PENDING) -> EXCLUSIVE
37395**    RESERVED -> (PENDING) -> EXCLUSIVE
37396**    PENDING -> EXCLUSIVE
37397**
37398** This routine will only increase a lock.  The winUnlock() routine
37399** erases all locks at once and returns us immediately to locking level 0.
37400** It is not possible to lower the locking level one step at a time.  You
37401** must go straight to locking level 0.
37402*/
37403static int winLock(sqlite3_file *id, int locktype){
37404  int rc = SQLITE_OK;    /* Return code from subroutines */
37405  int res = 1;           /* Result of a Windows lock call */
37406  int newLocktype;       /* Set pFile->locktype to this value before exiting */
37407  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
37408  winFile *pFile = (winFile*)id;
37409  DWORD lastErrno = NO_ERROR;
37410
37411  assert( id!=0 );
37412  OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
37413           pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
37414
37415  /* If there is already a lock of this type or more restrictive on the
37416  ** OsFile, do nothing. Don't use the end_lock: exit path, as
37417  ** sqlite3OsEnterMutex() hasn't been called yet.
37418  */
37419  if( pFile->locktype>=locktype ){
37420    OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
37421    return SQLITE_OK;
37422  }
37423
37424  /* Do not allow any kind of write-lock on a read-only database
37425  */
37426  if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
37427    return SQLITE_IOERR_LOCK;
37428  }
37429
37430  /* Make sure the locking sequence is correct
37431  */
37432  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
37433  assert( locktype!=PENDING_LOCK );
37434  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
37435
37436  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
37437  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
37438  ** the PENDING_LOCK byte is temporary.
37439  */
37440  newLocktype = pFile->locktype;
37441  if(   (pFile->locktype==NO_LOCK)
37442     || (   (locktype==EXCLUSIVE_LOCK)
37443         && (pFile->locktype==RESERVED_LOCK))
37444  ){
37445    int cnt = 3;
37446    while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
37447                                         PENDING_BYTE, 0, 1, 0))==0 ){
37448      /* Try 3 times to get the pending lock.  This is needed to work
37449      ** around problems caused by indexing and/or anti-virus software on
37450      ** Windows systems.
37451      ** If you are using this code as a model for alternative VFSes, do not
37452      ** copy this retry logic.  It is a hack intended for Windows only.
37453      */
37454      lastErrno = osGetLastError();
37455      OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
37456               pFile->h, cnt, res));
37457      if( lastErrno==ERROR_INVALID_HANDLE ){
37458        pFile->lastErrno = lastErrno;
37459        rc = SQLITE_IOERR_LOCK;
37460        OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
37461                 pFile->h, cnt, sqlite3ErrName(rc)));
37462        return rc;
37463      }
37464      if( cnt ) sqlite3_win32_sleep(1);
37465    }
37466    gotPendingLock = res;
37467    if( !res ){
37468      lastErrno = osGetLastError();
37469    }
37470  }
37471
37472  /* Acquire a shared lock
37473  */
37474  if( locktype==SHARED_LOCK && res ){
37475    assert( pFile->locktype==NO_LOCK );
37476    res = winGetReadLock(pFile);
37477    if( res ){
37478      newLocktype = SHARED_LOCK;
37479    }else{
37480      lastErrno = osGetLastError();
37481    }
37482  }
37483
37484  /* Acquire a RESERVED lock
37485  */
37486  if( locktype==RESERVED_LOCK && res ){
37487    assert( pFile->locktype==SHARED_LOCK );
37488    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
37489    if( res ){
37490      newLocktype = RESERVED_LOCK;
37491    }else{
37492      lastErrno = osGetLastError();
37493    }
37494  }
37495
37496  /* Acquire a PENDING lock
37497  */
37498  if( locktype==EXCLUSIVE_LOCK && res ){
37499    newLocktype = PENDING_LOCK;
37500    gotPendingLock = 0;
37501  }
37502
37503  /* Acquire an EXCLUSIVE lock
37504  */
37505  if( locktype==EXCLUSIVE_LOCK && res ){
37506    assert( pFile->locktype>=SHARED_LOCK );
37507    res = winUnlockReadLock(pFile);
37508    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
37509                      SHARED_SIZE, 0);
37510    if( res ){
37511      newLocktype = EXCLUSIVE_LOCK;
37512    }else{
37513      lastErrno = osGetLastError();
37514      winGetReadLock(pFile);
37515    }
37516  }
37517
37518  /* If we are holding a PENDING lock that ought to be released, then
37519  ** release it now.
37520  */
37521  if( gotPendingLock && locktype==SHARED_LOCK ){
37522    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
37523  }
37524
37525  /* Update the state of the lock has held in the file descriptor then
37526  ** return the appropriate result code.
37527  */
37528  if( res ){
37529    rc = SQLITE_OK;
37530  }else{
37531    pFile->lastErrno = lastErrno;
37532    rc = SQLITE_BUSY;
37533    OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
37534             pFile->h, locktype, newLocktype));
37535  }
37536  pFile->locktype = (u8)newLocktype;
37537  OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
37538           pFile->h, pFile->locktype, sqlite3ErrName(rc)));
37539  return rc;
37540}
37541
37542/*
37543** This routine checks if there is a RESERVED lock held on the specified
37544** file by this or any other process. If such a lock is held, return
37545** non-zero, otherwise zero.
37546*/
37547static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
37548  int res;
37549  winFile *pFile = (winFile*)id;
37550
37551  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
37552  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
37553
37554  assert( id!=0 );
37555  if( pFile->locktype>=RESERVED_LOCK ){
37556    res = 1;
37557    OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
37558  }else{
37559    res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
37560    if( res ){
37561      winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
37562    }
37563    res = !res;
37564    OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
37565  }
37566  *pResOut = res;
37567  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
37568           pFile->h, pResOut, *pResOut));
37569  return SQLITE_OK;
37570}
37571
37572/*
37573** Lower the locking level on file descriptor id to locktype.  locktype
37574** must be either NO_LOCK or SHARED_LOCK.
37575**
37576** If the locking level of the file descriptor is already at or below
37577** the requested locking level, this routine is a no-op.
37578**
37579** It is not possible for this routine to fail if the second argument
37580** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
37581** might return SQLITE_IOERR;
37582*/
37583static int winUnlock(sqlite3_file *id, int locktype){
37584  int type;
37585  winFile *pFile = (winFile*)id;
37586  int rc = SQLITE_OK;
37587  assert( pFile!=0 );
37588  assert( locktype<=SHARED_LOCK );
37589  OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
37590           pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
37591  type = pFile->locktype;
37592  if( type>=EXCLUSIVE_LOCK ){
37593    winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
37594    if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
37595      /* This should never happen.  We should always be able to
37596      ** reacquire the read lock */
37597      rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
37598                       "winUnlock", pFile->zPath);
37599    }
37600  }
37601  if( type>=RESERVED_LOCK ){
37602    winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
37603  }
37604  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
37605    winUnlockReadLock(pFile);
37606  }
37607  if( type>=PENDING_LOCK ){
37608    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
37609  }
37610  pFile->locktype = (u8)locktype;
37611  OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
37612           pFile->h, pFile->locktype, sqlite3ErrName(rc)));
37613  return rc;
37614}
37615
37616/*
37617** If *pArg is initially negative then this is a query.  Set *pArg to
37618** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
37619**
37620** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
37621*/
37622static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
37623  if( *pArg<0 ){
37624    *pArg = (pFile->ctrlFlags & mask)!=0;
37625  }else if( (*pArg)==0 ){
37626    pFile->ctrlFlags &= ~mask;
37627  }else{
37628    pFile->ctrlFlags |= mask;
37629  }
37630}
37631
37632/* Forward references to VFS helper methods used for temporary files */
37633static int winGetTempname(sqlite3_vfs *, char **);
37634static int winIsDir(const void *);
37635static BOOL winIsDriveLetterAndColon(const char *);
37636
37637/*
37638** Control and query of the open file handle.
37639*/
37640static int winFileControl(sqlite3_file *id, int op, void *pArg){
37641  winFile *pFile = (winFile*)id;
37642  OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
37643  switch( op ){
37644    case SQLITE_FCNTL_LOCKSTATE: {
37645      *(int*)pArg = pFile->locktype;
37646      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
37647      return SQLITE_OK;
37648    }
37649    case SQLITE_LAST_ERRNO: {
37650      *(int*)pArg = (int)pFile->lastErrno;
37651      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
37652      return SQLITE_OK;
37653    }
37654    case SQLITE_FCNTL_CHUNK_SIZE: {
37655      pFile->szChunk = *(int *)pArg;
37656      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
37657      return SQLITE_OK;
37658    }
37659    case SQLITE_FCNTL_SIZE_HINT: {
37660      if( pFile->szChunk>0 ){
37661        sqlite3_int64 oldSz;
37662        int rc = winFileSize(id, &oldSz);
37663        if( rc==SQLITE_OK ){
37664          sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
37665          if( newSz>oldSz ){
37666            SimulateIOErrorBenign(1);
37667            rc = winTruncate(id, newSz);
37668            SimulateIOErrorBenign(0);
37669          }
37670        }
37671        OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
37672        return rc;
37673      }
37674      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
37675      return SQLITE_OK;
37676    }
37677    case SQLITE_FCNTL_PERSIST_WAL: {
37678      winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
37679      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
37680      return SQLITE_OK;
37681    }
37682    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
37683      winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
37684      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
37685      return SQLITE_OK;
37686    }
37687    case SQLITE_FCNTL_VFSNAME: {
37688      *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
37689      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
37690      return SQLITE_OK;
37691    }
37692    case SQLITE_FCNTL_WIN32_AV_RETRY: {
37693      int *a = (int*)pArg;
37694      if( a[0]>0 ){
37695        winIoerrRetry = a[0];
37696      }else{
37697        a[0] = winIoerrRetry;
37698      }
37699      if( a[1]>0 ){
37700        winIoerrRetryDelay = a[1];
37701      }else{
37702        a[1] = winIoerrRetryDelay;
37703      }
37704      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
37705      return SQLITE_OK;
37706    }
37707#ifdef SQLITE_TEST
37708    case SQLITE_FCNTL_WIN32_SET_HANDLE: {
37709      LPHANDLE phFile = (LPHANDLE)pArg;
37710      HANDLE hOldFile = pFile->h;
37711      pFile->h = *phFile;
37712      *phFile = hOldFile;
37713      OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
37714               hOldFile, pFile->h));
37715      return SQLITE_OK;
37716    }
37717#endif
37718    case SQLITE_FCNTL_TEMPFILENAME: {
37719      char *zTFile = 0;
37720      int rc = winGetTempname(pFile->pVfs, &zTFile);
37721      if( rc==SQLITE_OK ){
37722        *(char**)pArg = zTFile;
37723      }
37724      OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
37725      return rc;
37726    }
37727#if SQLITE_MAX_MMAP_SIZE>0
37728    case SQLITE_FCNTL_MMAP_SIZE: {
37729      i64 newLimit = *(i64*)pArg;
37730      int rc = SQLITE_OK;
37731      if( newLimit>sqlite3GlobalConfig.mxMmap ){
37732        newLimit = sqlite3GlobalConfig.mxMmap;
37733      }
37734      *(i64*)pArg = pFile->mmapSizeMax;
37735      if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
37736        pFile->mmapSizeMax = newLimit;
37737        if( pFile->mmapSize>0 ){
37738          winUnmapfile(pFile);
37739          rc = winMapfile(pFile, -1);
37740        }
37741      }
37742      OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
37743      return rc;
37744    }
37745#endif
37746  }
37747  OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
37748  return SQLITE_NOTFOUND;
37749}
37750
37751/*
37752** Return the sector size in bytes of the underlying block device for
37753** the specified file. This is almost always 512 bytes, but may be
37754** larger for some devices.
37755**
37756** SQLite code assumes this function cannot fail. It also assumes that
37757** if two files are created in the same file-system directory (i.e.
37758** a database and its journal file) that the sector size will be the
37759** same for both.
37760*/
37761static int winSectorSize(sqlite3_file *id){
37762  (void)id;
37763  return SQLITE_DEFAULT_SECTOR_SIZE;
37764}
37765
37766/*
37767** Return a vector of device characteristics.
37768*/
37769static int winDeviceCharacteristics(sqlite3_file *id){
37770  winFile *p = (winFile*)id;
37771  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
37772         ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
37773}
37774
37775/*
37776** Windows will only let you create file view mappings
37777** on allocation size granularity boundaries.
37778** During sqlite3_os_init() we do a GetSystemInfo()
37779** to get the granularity size.
37780*/
37781static SYSTEM_INFO winSysInfo;
37782
37783#ifndef SQLITE_OMIT_WAL
37784
37785/*
37786** Helper functions to obtain and relinquish the global mutex. The
37787** global mutex is used to protect the winLockInfo objects used by
37788** this file, all of which may be shared by multiple threads.
37789**
37790** Function winShmMutexHeld() is used to assert() that the global mutex
37791** is held when required. This function is only used as part of assert()
37792** statements. e.g.
37793**
37794**   winShmEnterMutex()
37795**     assert( winShmMutexHeld() );
37796**   winShmLeaveMutex()
37797*/
37798static void winShmEnterMutex(void){
37799  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
37800}
37801static void winShmLeaveMutex(void){
37802  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
37803}
37804#ifndef NDEBUG
37805static int winShmMutexHeld(void) {
37806  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
37807}
37808#endif
37809
37810/*
37811** Object used to represent a single file opened and mmapped to provide
37812** shared memory.  When multiple threads all reference the same
37813** log-summary, each thread has its own winFile object, but they all
37814** point to a single instance of this object.  In other words, each
37815** log-summary is opened only once per process.
37816**
37817** winShmMutexHeld() must be true when creating or destroying
37818** this object or while reading or writing the following fields:
37819**
37820**      nRef
37821**      pNext
37822**
37823** The following fields are read-only after the object is created:
37824**
37825**      fid
37826**      zFilename
37827**
37828** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
37829** winShmMutexHeld() is true when reading or writing any other field
37830** in this structure.
37831**
37832*/
37833struct winShmNode {
37834  sqlite3_mutex *mutex;      /* Mutex to access this object */
37835  char *zFilename;           /* Name of the file */
37836  winFile hFile;             /* File handle from winOpen */
37837
37838  int szRegion;              /* Size of shared-memory regions */
37839  int nRegion;               /* Size of array apRegion */
37840  struct ShmRegion {
37841    HANDLE hMap;             /* File handle from CreateFileMapping */
37842    void *pMap;
37843  } *aRegion;
37844  DWORD lastErrno;           /* The Windows errno from the last I/O error */
37845
37846  int nRef;                  /* Number of winShm objects pointing to this */
37847  winShm *pFirst;            /* All winShm objects pointing to this */
37848  winShmNode *pNext;         /* Next in list of all winShmNode objects */
37849#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
37850  u8 nextShmId;              /* Next available winShm.id value */
37851#endif
37852};
37853
37854/*
37855** A global array of all winShmNode objects.
37856**
37857** The winShmMutexHeld() must be true while reading or writing this list.
37858*/
37859static winShmNode *winShmNodeList = 0;
37860
37861/*
37862** Structure used internally by this VFS to record the state of an
37863** open shared memory connection.
37864**
37865** The following fields are initialized when this object is created and
37866** are read-only thereafter:
37867**
37868**    winShm.pShmNode
37869**    winShm.id
37870**
37871** All other fields are read/write.  The winShm.pShmNode->mutex must be held
37872** while accessing any read/write fields.
37873*/
37874struct winShm {
37875  winShmNode *pShmNode;      /* The underlying winShmNode object */
37876  winShm *pNext;             /* Next winShm with the same winShmNode */
37877  u8 hasMutex;               /* True if holding the winShmNode mutex */
37878  u16 sharedMask;            /* Mask of shared locks held */
37879  u16 exclMask;              /* Mask of exclusive locks held */
37880#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
37881  u8 id;                     /* Id of this connection with its winShmNode */
37882#endif
37883};
37884
37885/*
37886** Constants used for locking
37887*/
37888#define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
37889#define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
37890
37891/*
37892** Apply advisory locks for all n bytes beginning at ofst.
37893*/
37894#define _SHM_UNLCK  1
37895#define _SHM_RDLCK  2
37896#define _SHM_WRLCK  3
37897static int winShmSystemLock(
37898  winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
37899  int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
37900  int ofst,             /* Offset to first byte to be locked/unlocked */
37901  int nByte             /* Number of bytes to lock or unlock */
37902){
37903  int rc = 0;           /* Result code form Lock/UnlockFileEx() */
37904
37905  /* Access to the winShmNode object is serialized by the caller */
37906  assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
37907
37908  OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
37909           pFile->hFile.h, lockType, ofst, nByte));
37910
37911  /* Release/Acquire the system-level lock */
37912  if( lockType==_SHM_UNLCK ){
37913    rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
37914  }else{
37915    /* Initialize the locking parameters */
37916    DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
37917    if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
37918    rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
37919  }
37920
37921  if( rc!= 0 ){
37922    rc = SQLITE_OK;
37923  }else{
37924    pFile->lastErrno =  osGetLastError();
37925    rc = SQLITE_BUSY;
37926  }
37927
37928  OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
37929           pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
37930           "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
37931
37932  return rc;
37933}
37934
37935/* Forward references to VFS methods */
37936static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
37937static int winDelete(sqlite3_vfs *,const char*,int);
37938
37939/*
37940** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
37941**
37942** This is not a VFS shared-memory method; it is a utility function called
37943** by VFS shared-memory methods.
37944*/
37945static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
37946  winShmNode **pp;
37947  winShmNode *p;
37948  assert( winShmMutexHeld() );
37949  OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
37950           osGetCurrentProcessId(), deleteFlag));
37951  pp = &winShmNodeList;
37952  while( (p = *pp)!=0 ){
37953    if( p->nRef==0 ){
37954      int i;
37955      if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
37956      for(i=0; i<p->nRegion; i++){
37957        BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
37958        OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
37959                 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
37960        UNUSED_VARIABLE_VALUE(bRc);
37961        bRc = osCloseHandle(p->aRegion[i].hMap);
37962        OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
37963                 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
37964        UNUSED_VARIABLE_VALUE(bRc);
37965      }
37966      if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
37967        SimulateIOErrorBenign(1);
37968        winClose((sqlite3_file *)&p->hFile);
37969        SimulateIOErrorBenign(0);
37970      }
37971      if( deleteFlag ){
37972        SimulateIOErrorBenign(1);
37973        sqlite3BeginBenignMalloc();
37974        winDelete(pVfs, p->zFilename, 0);
37975        sqlite3EndBenignMalloc();
37976        SimulateIOErrorBenign(0);
37977      }
37978      *pp = p->pNext;
37979      sqlite3_free(p->aRegion);
37980      sqlite3_free(p);
37981    }else{
37982      pp = &p->pNext;
37983    }
37984  }
37985}
37986
37987/*
37988** Open the shared-memory area associated with database file pDbFd.
37989**
37990** When opening a new shared-memory file, if no other instances of that
37991** file are currently open, in this process or in other processes, then
37992** the file must be truncated to zero length or have its header cleared.
37993*/
37994static int winOpenSharedMemory(winFile *pDbFd){
37995  struct winShm *p;                  /* The connection to be opened */
37996  struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
37997  int rc;                            /* Result code */
37998  struct winShmNode *pNew;           /* Newly allocated winShmNode */
37999  int nName;                         /* Size of zName in bytes */
38000
38001  assert( pDbFd->pShm==0 );    /* Not previously opened */
38002
38003  /* Allocate space for the new sqlite3_shm object.  Also speculatively
38004  ** allocate space for a new winShmNode and filename.
38005  */
38006  p = sqlite3MallocZero( sizeof(*p) );
38007  if( p==0 ) return SQLITE_IOERR_NOMEM;
38008  nName = sqlite3Strlen30(pDbFd->zPath);
38009  pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
38010  if( pNew==0 ){
38011    sqlite3_free(p);
38012    return SQLITE_IOERR_NOMEM;
38013  }
38014  pNew->zFilename = (char*)&pNew[1];
38015  sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
38016  sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
38017
38018  /* Look to see if there is an existing winShmNode that can be used.
38019  ** If no matching winShmNode currently exists, create a new one.
38020  */
38021  winShmEnterMutex();
38022  for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
38023    /* TBD need to come up with better match here.  Perhaps
38024    ** use FILE_ID_BOTH_DIR_INFO Structure.
38025    */
38026    if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
38027  }
38028  if( pShmNode ){
38029    sqlite3_free(pNew);
38030  }else{
38031    pShmNode = pNew;
38032    pNew = 0;
38033    ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
38034    pShmNode->pNext = winShmNodeList;
38035    winShmNodeList = pShmNode;
38036
38037    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
38038    if( pShmNode->mutex==0 ){
38039      rc = SQLITE_IOERR_NOMEM;
38040      goto shm_open_err;
38041    }
38042
38043    rc = winOpen(pDbFd->pVfs,
38044                 pShmNode->zFilename,             /* Name of the file (UTF-8) */
38045                 (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
38046                 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
38047                 0);
38048    if( SQLITE_OK!=rc ){
38049      goto shm_open_err;
38050    }
38051
38052    /* Check to see if another process is holding the dead-man switch.
38053    ** If not, truncate the file to zero length.
38054    */
38055    if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
38056      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
38057      if( rc!=SQLITE_OK ){
38058        rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
38059                         "winOpenShm", pDbFd->zPath);
38060      }
38061    }
38062    if( rc==SQLITE_OK ){
38063      winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
38064      rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
38065    }
38066    if( rc ) goto shm_open_err;
38067  }
38068
38069  /* Make the new connection a child of the winShmNode */
38070  p->pShmNode = pShmNode;
38071#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
38072  p->id = pShmNode->nextShmId++;
38073#endif
38074  pShmNode->nRef++;
38075  pDbFd->pShm = p;
38076  winShmLeaveMutex();
38077
38078  /* The reference count on pShmNode has already been incremented under
38079  ** the cover of the winShmEnterMutex() mutex and the pointer from the
38080  ** new (struct winShm) object to the pShmNode has been set. All that is
38081  ** left to do is to link the new object into the linked list starting
38082  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
38083  ** mutex.
38084  */
38085  sqlite3_mutex_enter(pShmNode->mutex);
38086  p->pNext = pShmNode->pFirst;
38087  pShmNode->pFirst = p;
38088  sqlite3_mutex_leave(pShmNode->mutex);
38089  return SQLITE_OK;
38090
38091  /* Jump here on any error */
38092shm_open_err:
38093  winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
38094  winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
38095  sqlite3_free(p);
38096  sqlite3_free(pNew);
38097  winShmLeaveMutex();
38098  return rc;
38099}
38100
38101/*
38102** Close a connection to shared-memory.  Delete the underlying
38103** storage if deleteFlag is true.
38104*/
38105static int winShmUnmap(
38106  sqlite3_file *fd,          /* Database holding shared memory */
38107  int deleteFlag             /* Delete after closing if true */
38108){
38109  winFile *pDbFd;       /* Database holding shared-memory */
38110  winShm *p;            /* The connection to be closed */
38111  winShmNode *pShmNode; /* The underlying shared-memory file */
38112  winShm **pp;          /* For looping over sibling connections */
38113
38114  pDbFd = (winFile*)fd;
38115  p = pDbFd->pShm;
38116  if( p==0 ) return SQLITE_OK;
38117  pShmNode = p->pShmNode;
38118
38119  /* Remove connection p from the set of connections associated
38120  ** with pShmNode */
38121  sqlite3_mutex_enter(pShmNode->mutex);
38122  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
38123  *pp = p->pNext;
38124
38125  /* Free the connection p */
38126  sqlite3_free(p);
38127  pDbFd->pShm = 0;
38128  sqlite3_mutex_leave(pShmNode->mutex);
38129
38130  /* If pShmNode->nRef has reached 0, then close the underlying
38131  ** shared-memory file, too */
38132  winShmEnterMutex();
38133  assert( pShmNode->nRef>0 );
38134  pShmNode->nRef--;
38135  if( pShmNode->nRef==0 ){
38136    winShmPurge(pDbFd->pVfs, deleteFlag);
38137  }
38138  winShmLeaveMutex();
38139
38140  return SQLITE_OK;
38141}
38142
38143/*
38144** Change the lock state for a shared-memory segment.
38145*/
38146static int winShmLock(
38147  sqlite3_file *fd,          /* Database file holding the shared memory */
38148  int ofst,                  /* First lock to acquire or release */
38149  int n,                     /* Number of locks to acquire or release */
38150  int flags                  /* What to do with the lock */
38151){
38152  winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
38153  winShm *p = pDbFd->pShm;              /* The shared memory being locked */
38154  winShm *pX;                           /* For looping over all siblings */
38155  winShmNode *pShmNode = p->pShmNode;
38156  int rc = SQLITE_OK;                   /* Result code */
38157  u16 mask;                             /* Mask of locks to take or release */
38158
38159  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
38160  assert( n>=1 );
38161  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
38162       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
38163       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
38164       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
38165  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
38166
38167  mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
38168  assert( n>1 || mask==(1<<ofst) );
38169  sqlite3_mutex_enter(pShmNode->mutex);
38170  if( flags & SQLITE_SHM_UNLOCK ){
38171    u16 allMask = 0; /* Mask of locks held by siblings */
38172
38173    /* See if any siblings hold this same lock */
38174    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
38175      if( pX==p ) continue;
38176      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
38177      allMask |= pX->sharedMask;
38178    }
38179
38180    /* Unlock the system-level locks */
38181    if( (mask & allMask)==0 ){
38182      rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
38183    }else{
38184      rc = SQLITE_OK;
38185    }
38186
38187    /* Undo the local locks */
38188    if( rc==SQLITE_OK ){
38189      p->exclMask &= ~mask;
38190      p->sharedMask &= ~mask;
38191    }
38192  }else if( flags & SQLITE_SHM_SHARED ){
38193    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
38194
38195    /* Find out which shared locks are already held by sibling connections.
38196    ** If any sibling already holds an exclusive lock, go ahead and return
38197    ** SQLITE_BUSY.
38198    */
38199    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
38200      if( (pX->exclMask & mask)!=0 ){
38201        rc = SQLITE_BUSY;
38202        break;
38203      }
38204      allShared |= pX->sharedMask;
38205    }
38206
38207    /* Get shared locks at the system level, if necessary */
38208    if( rc==SQLITE_OK ){
38209      if( (allShared & mask)==0 ){
38210        rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
38211      }else{
38212        rc = SQLITE_OK;
38213      }
38214    }
38215
38216    /* Get the local shared locks */
38217    if( rc==SQLITE_OK ){
38218      p->sharedMask |= mask;
38219    }
38220  }else{
38221    /* Make sure no sibling connections hold locks that will block this
38222    ** lock.  If any do, return SQLITE_BUSY right away.
38223    */
38224    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
38225      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
38226        rc = SQLITE_BUSY;
38227        break;
38228      }
38229    }
38230
38231    /* Get the exclusive locks at the system level.  Then if successful
38232    ** also mark the local connection as being locked.
38233    */
38234    if( rc==SQLITE_OK ){
38235      rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
38236      if( rc==SQLITE_OK ){
38237        assert( (p->sharedMask & mask)==0 );
38238        p->exclMask |= mask;
38239      }
38240    }
38241  }
38242  sqlite3_mutex_leave(pShmNode->mutex);
38243  OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
38244           osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
38245           sqlite3ErrName(rc)));
38246  return rc;
38247}
38248
38249/*
38250** Implement a memory barrier or memory fence on shared memory.
38251**
38252** All loads and stores begun before the barrier must complete before
38253** any load or store begun after the barrier.
38254*/
38255static void winShmBarrier(
38256  sqlite3_file *fd          /* Database holding the shared memory */
38257){
38258  UNUSED_PARAMETER(fd);
38259  sqlite3MemoryBarrier();   /* compiler-defined memory barrier */
38260  winShmEnterMutex();       /* Also mutex, for redundancy */
38261  winShmLeaveMutex();
38262}
38263
38264/*
38265** This function is called to obtain a pointer to region iRegion of the
38266** shared-memory associated with the database file fd. Shared-memory regions
38267** are numbered starting from zero. Each shared-memory region is szRegion
38268** bytes in size.
38269**
38270** If an error occurs, an error code is returned and *pp is set to NULL.
38271**
38272** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
38273** region has not been allocated (by any client, including one running in a
38274** separate process), then *pp is set to NULL and SQLITE_OK returned. If
38275** isWrite is non-zero and the requested shared-memory region has not yet
38276** been allocated, it is allocated by this function.
38277**
38278** If the shared-memory region has already been allocated or is allocated by
38279** this call as described above, then it is mapped into this processes
38280** address space (if it is not already), *pp is set to point to the mapped
38281** memory and SQLITE_OK returned.
38282*/
38283static int winShmMap(
38284  sqlite3_file *fd,               /* Handle open on database file */
38285  int iRegion,                    /* Region to retrieve */
38286  int szRegion,                   /* Size of regions */
38287  int isWrite,                    /* True to extend file if necessary */
38288  void volatile **pp              /* OUT: Mapped memory */
38289){
38290  winFile *pDbFd = (winFile*)fd;
38291  winShm *pShm = pDbFd->pShm;
38292  winShmNode *pShmNode;
38293  int rc = SQLITE_OK;
38294
38295  if( !pShm ){
38296    rc = winOpenSharedMemory(pDbFd);
38297    if( rc!=SQLITE_OK ) return rc;
38298    pShm = pDbFd->pShm;
38299  }
38300  pShmNode = pShm->pShmNode;
38301
38302  sqlite3_mutex_enter(pShmNode->mutex);
38303  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
38304
38305  if( pShmNode->nRegion<=iRegion ){
38306    struct ShmRegion *apNew;           /* New aRegion[] array */
38307    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
38308    sqlite3_int64 sz;                  /* Current size of wal-index file */
38309
38310    pShmNode->szRegion = szRegion;
38311
38312    /* The requested region is not mapped into this processes address space.
38313    ** Check to see if it has been allocated (i.e. if the wal-index file is
38314    ** large enough to contain the requested region).
38315    */
38316    rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
38317    if( rc!=SQLITE_OK ){
38318      rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
38319                       "winShmMap1", pDbFd->zPath);
38320      goto shmpage_out;
38321    }
38322
38323    if( sz<nByte ){
38324      /* The requested memory region does not exist. If isWrite is set to
38325      ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
38326      **
38327      ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
38328      ** the requested memory region.
38329      */
38330      if( !isWrite ) goto shmpage_out;
38331      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
38332      if( rc!=SQLITE_OK ){
38333        rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
38334                         "winShmMap2", pDbFd->zPath);
38335        goto shmpage_out;
38336      }
38337    }
38338
38339    /* Map the requested memory region into this processes address space. */
38340    apNew = (struct ShmRegion *)sqlite3_realloc64(
38341        pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
38342    );
38343    if( !apNew ){
38344      rc = SQLITE_IOERR_NOMEM;
38345      goto shmpage_out;
38346    }
38347    pShmNode->aRegion = apNew;
38348
38349    while( pShmNode->nRegion<=iRegion ){
38350      HANDLE hMap = NULL;         /* file-mapping handle */
38351      void *pMap = 0;             /* Mapped memory region */
38352
38353#if SQLITE_OS_WINRT
38354      hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
38355          NULL, PAGE_READWRITE, nByte, NULL
38356      );
38357#elif defined(SQLITE_WIN32_HAS_WIDE)
38358      hMap = osCreateFileMappingW(pShmNode->hFile.h,
38359          NULL, PAGE_READWRITE, 0, nByte, NULL
38360      );
38361#elif defined(SQLITE_WIN32_HAS_ANSI)
38362      hMap = osCreateFileMappingA(pShmNode->hFile.h,
38363          NULL, PAGE_READWRITE, 0, nByte, NULL
38364      );
38365#endif
38366      OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
38367               osGetCurrentProcessId(), pShmNode->nRegion, nByte,
38368               hMap ? "ok" : "failed"));
38369      if( hMap ){
38370        int iOffset = pShmNode->nRegion*szRegion;
38371        int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
38372#if SQLITE_OS_WINRT
38373        pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
38374            iOffset - iOffsetShift, szRegion + iOffsetShift
38375        );
38376#else
38377        pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
38378            0, iOffset - iOffsetShift, szRegion + iOffsetShift
38379        );
38380#endif
38381        OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
38382                 osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
38383                 szRegion, pMap ? "ok" : "failed"));
38384      }
38385      if( !pMap ){
38386        pShmNode->lastErrno = osGetLastError();
38387        rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
38388                         "winShmMap3", pDbFd->zPath);
38389        if( hMap ) osCloseHandle(hMap);
38390        goto shmpage_out;
38391      }
38392
38393      pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
38394      pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
38395      pShmNode->nRegion++;
38396    }
38397  }
38398
38399shmpage_out:
38400  if( pShmNode->nRegion>iRegion ){
38401    int iOffset = iRegion*szRegion;
38402    int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
38403    char *p = (char *)pShmNode->aRegion[iRegion].pMap;
38404    *pp = (void *)&p[iOffsetShift];
38405  }else{
38406    *pp = 0;
38407  }
38408  sqlite3_mutex_leave(pShmNode->mutex);
38409  return rc;
38410}
38411
38412#else
38413# define winShmMap     0
38414# define winShmLock    0
38415# define winShmBarrier 0
38416# define winShmUnmap   0
38417#endif /* #ifndef SQLITE_OMIT_WAL */
38418
38419/*
38420** Cleans up the mapped region of the specified file, if any.
38421*/
38422#if SQLITE_MAX_MMAP_SIZE>0
38423static int winUnmapfile(winFile *pFile){
38424  assert( pFile!=0 );
38425  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
38426           "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
38427           osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
38428           pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
38429  if( pFile->pMapRegion ){
38430    if( !osUnmapViewOfFile(pFile->pMapRegion) ){
38431      pFile->lastErrno = osGetLastError();
38432      OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
38433               "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
38434               pFile->pMapRegion));
38435      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
38436                         "winUnmapfile1", pFile->zPath);
38437    }
38438    pFile->pMapRegion = 0;
38439    pFile->mmapSize = 0;
38440    pFile->mmapSizeActual = 0;
38441  }
38442  if( pFile->hMap!=NULL ){
38443    if( !osCloseHandle(pFile->hMap) ){
38444      pFile->lastErrno = osGetLastError();
38445      OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
38446               osGetCurrentProcessId(), pFile, pFile->hMap));
38447      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
38448                         "winUnmapfile2", pFile->zPath);
38449    }
38450    pFile->hMap = NULL;
38451  }
38452  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
38453           osGetCurrentProcessId(), pFile));
38454  return SQLITE_OK;
38455}
38456
38457/*
38458** Memory map or remap the file opened by file-descriptor pFd (if the file
38459** is already mapped, the existing mapping is replaced by the new). Or, if
38460** there already exists a mapping for this file, and there are still
38461** outstanding xFetch() references to it, this function is a no-op.
38462**
38463** If parameter nByte is non-negative, then it is the requested size of
38464** the mapping to create. Otherwise, if nByte is less than zero, then the
38465** requested size is the size of the file on disk. The actual size of the
38466** created mapping is either the requested size or the value configured
38467** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
38468**
38469** SQLITE_OK is returned if no error occurs (even if the mapping is not
38470** recreated as a result of outstanding references) or an SQLite error
38471** code otherwise.
38472*/
38473static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
38474  sqlite3_int64 nMap = nByte;
38475  int rc;
38476
38477  assert( nMap>=0 || pFd->nFetchOut==0 );
38478  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
38479           osGetCurrentProcessId(), pFd, nByte));
38480
38481  if( pFd->nFetchOut>0 ) return SQLITE_OK;
38482
38483  if( nMap<0 ){
38484    rc = winFileSize((sqlite3_file*)pFd, &nMap);
38485    if( rc ){
38486      OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
38487               osGetCurrentProcessId(), pFd));
38488      return SQLITE_IOERR_FSTAT;
38489    }
38490  }
38491  if( nMap>pFd->mmapSizeMax ){
38492    nMap = pFd->mmapSizeMax;
38493  }
38494  nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
38495
38496  if( nMap==0 && pFd->mmapSize>0 ){
38497    winUnmapfile(pFd);
38498  }
38499  if( nMap!=pFd->mmapSize ){
38500    void *pNew = 0;
38501    DWORD protect = PAGE_READONLY;
38502    DWORD flags = FILE_MAP_READ;
38503
38504    winUnmapfile(pFd);
38505    if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
38506      protect = PAGE_READWRITE;
38507      flags |= FILE_MAP_WRITE;
38508    }
38509#if SQLITE_OS_WINRT
38510    pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
38511#elif defined(SQLITE_WIN32_HAS_WIDE)
38512    pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
38513                                (DWORD)((nMap>>32) & 0xffffffff),
38514                                (DWORD)(nMap & 0xffffffff), NULL);
38515#elif defined(SQLITE_WIN32_HAS_ANSI)
38516    pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
38517                                (DWORD)((nMap>>32) & 0xffffffff),
38518                                (DWORD)(nMap & 0xffffffff), NULL);
38519#endif
38520    if( pFd->hMap==NULL ){
38521      pFd->lastErrno = osGetLastError();
38522      rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
38523                       "winMapfile1", pFd->zPath);
38524      /* Log the error, but continue normal operation using xRead/xWrite */
38525      OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
38526               osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
38527      return SQLITE_OK;
38528    }
38529    assert( (nMap % winSysInfo.dwPageSize)==0 );
38530    assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
38531#if SQLITE_OS_WINRT
38532    pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
38533#else
38534    pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
38535#endif
38536    if( pNew==NULL ){
38537      osCloseHandle(pFd->hMap);
38538      pFd->hMap = NULL;
38539      pFd->lastErrno = osGetLastError();
38540      rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
38541                       "winMapfile2", pFd->zPath);
38542      /* Log the error, but continue normal operation using xRead/xWrite */
38543      OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
38544               osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
38545      return SQLITE_OK;
38546    }
38547    pFd->pMapRegion = pNew;
38548    pFd->mmapSize = nMap;
38549    pFd->mmapSizeActual = nMap;
38550  }
38551
38552  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
38553           osGetCurrentProcessId(), pFd));
38554  return SQLITE_OK;
38555}
38556#endif /* SQLITE_MAX_MMAP_SIZE>0 */
38557
38558/*
38559** If possible, return a pointer to a mapping of file fd starting at offset
38560** iOff. The mapping must be valid for at least nAmt bytes.
38561**
38562** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
38563** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
38564** Finally, if an error does occur, return an SQLite error code. The final
38565** value of *pp is undefined in this case.
38566**
38567** If this function does return a pointer, the caller must eventually
38568** release the reference by calling winUnfetch().
38569*/
38570static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
38571#if SQLITE_MAX_MMAP_SIZE>0
38572  winFile *pFd = (winFile*)fd;   /* The underlying database file */
38573#endif
38574  *pp = 0;
38575
38576  OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
38577           osGetCurrentProcessId(), fd, iOff, nAmt, pp));
38578
38579#if SQLITE_MAX_MMAP_SIZE>0
38580  if( pFd->mmapSizeMax>0 ){
38581    if( pFd->pMapRegion==0 ){
38582      int rc = winMapfile(pFd, -1);
38583      if( rc!=SQLITE_OK ){
38584        OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
38585                 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
38586        return rc;
38587      }
38588    }
38589    if( pFd->mmapSize >= iOff+nAmt ){
38590      *pp = &((u8 *)pFd->pMapRegion)[iOff];
38591      pFd->nFetchOut++;
38592    }
38593  }
38594#endif
38595
38596  OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
38597           osGetCurrentProcessId(), fd, pp, *pp));
38598  return SQLITE_OK;
38599}
38600
38601/*
38602** If the third argument is non-NULL, then this function releases a
38603** reference obtained by an earlier call to winFetch(). The second
38604** argument passed to this function must be the same as the corresponding
38605** argument that was passed to the winFetch() invocation.
38606**
38607** Or, if the third argument is NULL, then this function is being called
38608** to inform the VFS layer that, according to POSIX, any existing mapping
38609** may now be invalid and should be unmapped.
38610*/
38611static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
38612#if SQLITE_MAX_MMAP_SIZE>0
38613  winFile *pFd = (winFile*)fd;   /* The underlying database file */
38614
38615  /* If p==0 (unmap the entire file) then there must be no outstanding
38616  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
38617  ** then there must be at least one outstanding.  */
38618  assert( (p==0)==(pFd->nFetchOut==0) );
38619
38620  /* If p!=0, it must match the iOff value. */
38621  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
38622
38623  OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
38624           osGetCurrentProcessId(), pFd, iOff, p));
38625
38626  if( p ){
38627    pFd->nFetchOut--;
38628  }else{
38629    /* FIXME:  If Windows truly always prevents truncating or deleting a
38630    ** file while a mapping is held, then the following winUnmapfile() call
38631    ** is unnecessary can be omitted - potentially improving
38632    ** performance.  */
38633    winUnmapfile(pFd);
38634  }
38635
38636  assert( pFd->nFetchOut>=0 );
38637#endif
38638
38639  OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
38640           osGetCurrentProcessId(), fd));
38641  return SQLITE_OK;
38642}
38643
38644/*
38645** Here ends the implementation of all sqlite3_file methods.
38646**
38647********************** End sqlite3_file Methods *******************************
38648******************************************************************************/
38649
38650/*
38651** This vector defines all the methods that can operate on an
38652** sqlite3_file for win32.
38653*/
38654static const sqlite3_io_methods winIoMethod = {
38655  3,                              /* iVersion */
38656  winClose,                       /* xClose */
38657  winRead,                        /* xRead */
38658  winWrite,                       /* xWrite */
38659  winTruncate,                    /* xTruncate */
38660  winSync,                        /* xSync */
38661  winFileSize,                    /* xFileSize */
38662  winLock,                        /* xLock */
38663  winUnlock,                      /* xUnlock */
38664  winCheckReservedLock,           /* xCheckReservedLock */
38665  winFileControl,                 /* xFileControl */
38666  winSectorSize,                  /* xSectorSize */
38667  winDeviceCharacteristics,       /* xDeviceCharacteristics */
38668  winShmMap,                      /* xShmMap */
38669  winShmLock,                     /* xShmLock */
38670  winShmBarrier,                  /* xShmBarrier */
38671  winShmUnmap,                    /* xShmUnmap */
38672  winFetch,                       /* xFetch */
38673  winUnfetch                      /* xUnfetch */
38674};
38675
38676/****************************************************************************
38677**************************** sqlite3_vfs methods ****************************
38678**
38679** This division contains the implementation of methods on the
38680** sqlite3_vfs object.
38681*/
38682
38683#if defined(__CYGWIN__)
38684/*
38685** Convert a filename from whatever the underlying operating system
38686** supports for filenames into UTF-8.  Space to hold the result is
38687** obtained from malloc and must be freed by the calling function.
38688*/
38689static char *winConvertToUtf8Filename(const void *zFilename){
38690  char *zConverted = 0;
38691  if( osIsNT() ){
38692    zConverted = winUnicodeToUtf8(zFilename);
38693  }
38694#ifdef SQLITE_WIN32_HAS_ANSI
38695  else{
38696    zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
38697  }
38698#endif
38699  /* caller will handle out of memory */
38700  return zConverted;
38701}
38702#endif
38703
38704/*
38705** Convert a UTF-8 filename into whatever form the underlying
38706** operating system wants filenames in.  Space to hold the result
38707** is obtained from malloc and must be freed by the calling
38708** function.
38709*/
38710static void *winConvertFromUtf8Filename(const char *zFilename){
38711  void *zConverted = 0;
38712  if( osIsNT() ){
38713    zConverted = winUtf8ToUnicode(zFilename);
38714  }
38715#ifdef SQLITE_WIN32_HAS_ANSI
38716  else{
38717    zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
38718  }
38719#endif
38720  /* caller will handle out of memory */
38721  return zConverted;
38722}
38723
38724/*
38725** This function returns non-zero if the specified UTF-8 string buffer
38726** ends with a directory separator character or one was successfully
38727** added to it.
38728*/
38729static int winMakeEndInDirSep(int nBuf, char *zBuf){
38730  if( zBuf ){
38731    int nLen = sqlite3Strlen30(zBuf);
38732    if( nLen>0 ){
38733      if( winIsDirSep(zBuf[nLen-1]) ){
38734        return 1;
38735      }else if( nLen+1<nBuf ){
38736        zBuf[nLen] = winGetDirSep();
38737        zBuf[nLen+1] = '\0';
38738        return 1;
38739      }
38740    }
38741  }
38742  return 0;
38743}
38744
38745/*
38746** Create a temporary file name and store the resulting pointer into pzBuf.
38747** The pointer returned in pzBuf must be freed via sqlite3_free().
38748*/
38749static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
38750  static char zChars[] =
38751    "abcdefghijklmnopqrstuvwxyz"
38752    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
38753    "0123456789";
38754  size_t i, j;
38755  int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
38756  int nMax, nBuf, nDir, nLen;
38757  char *zBuf;
38758
38759  /* It's odd to simulate an io-error here, but really this is just
38760  ** using the io-error infrastructure to test that SQLite handles this
38761  ** function failing.
38762  */
38763  SimulateIOError( return SQLITE_IOERR );
38764
38765  /* Allocate a temporary buffer to store the fully qualified file
38766  ** name for the temporary file.  If this fails, we cannot continue.
38767  */
38768  nMax = pVfs->mxPathname; nBuf = nMax + 2;
38769  zBuf = sqlite3MallocZero( nBuf );
38770  if( !zBuf ){
38771    OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
38772    return SQLITE_IOERR_NOMEM;
38773  }
38774
38775  /* Figure out the effective temporary directory.  First, check if one
38776  ** has been explicitly set by the application; otherwise, use the one
38777  ** configured by the operating system.
38778  */
38779  nDir = nMax - (nPre + 15);
38780  assert( nDir>0 );
38781  if( sqlite3_temp_directory ){
38782    int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
38783    if( nDirLen>0 ){
38784      if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
38785        nDirLen++;
38786      }
38787      if( nDirLen>nDir ){
38788        sqlite3_free(zBuf);
38789        OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
38790        return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
38791      }
38792      sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
38793    }
38794  }
38795#if defined(__CYGWIN__)
38796  else{
38797    static const char *azDirs[] = {
38798       0, /* getenv("SQLITE_TMPDIR") */
38799       0, /* getenv("TMPDIR") */
38800       0, /* getenv("TMP") */
38801       0, /* getenv("TEMP") */
38802       0, /* getenv("USERPROFILE") */
38803       "/var/tmp",
38804       "/usr/tmp",
38805       "/tmp",
38806       ".",
38807       0        /* List terminator */
38808    };
38809    unsigned int i;
38810    const char *zDir = 0;
38811
38812    if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
38813    if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
38814    if( !azDirs[2] ) azDirs[2] = getenv("TMP");
38815    if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
38816    if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
38817    for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
38818      void *zConverted;
38819      if( zDir==0 ) continue;
38820      /* If the path starts with a drive letter followed by the colon
38821      ** character, assume it is already a native Win32 path; otherwise,
38822      ** it must be converted to a native Win32 path via the Cygwin API
38823      ** prior to using it.
38824      */
38825      if( winIsDriveLetterAndColon(zDir) ){
38826        zConverted = winConvertFromUtf8Filename(zDir);
38827        if( !zConverted ){
38828          sqlite3_free(zBuf);
38829          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
38830          return SQLITE_IOERR_NOMEM;
38831        }
38832        if( winIsDir(zConverted) ){
38833          sqlite3_snprintf(nMax, zBuf, "%s", zDir);
38834          sqlite3_free(zConverted);
38835          break;
38836        }
38837        sqlite3_free(zConverted);
38838      }else{
38839        zConverted = sqlite3MallocZero( nMax+1 );
38840        if( !zConverted ){
38841          sqlite3_free(zBuf);
38842          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
38843          return SQLITE_IOERR_NOMEM;
38844        }
38845        if( cygwin_conv_path(
38846                osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
38847                zConverted, nMax+1)<0 ){
38848          sqlite3_free(zConverted);
38849          sqlite3_free(zBuf);
38850          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
38851          return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
38852                             "winGetTempname2", zDir);
38853        }
38854        if( winIsDir(zConverted) ){
38855          /* At this point, we know the candidate directory exists and should
38856          ** be used.  However, we may need to convert the string containing
38857          ** its name into UTF-8 (i.e. if it is UTF-16 right now).
38858          */
38859          char *zUtf8 = winConvertToUtf8Filename(zConverted);
38860          if( !zUtf8 ){
38861            sqlite3_free(zConverted);
38862            sqlite3_free(zBuf);
38863            OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
38864            return SQLITE_IOERR_NOMEM;
38865          }
38866          sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
38867          sqlite3_free(zUtf8);
38868          sqlite3_free(zConverted);
38869          break;
38870        }
38871        sqlite3_free(zConverted);
38872      }
38873    }
38874  }
38875#elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
38876  else if( osIsNT() ){
38877    char *zMulti;
38878    LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
38879    if( !zWidePath ){
38880      sqlite3_free(zBuf);
38881      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
38882      return SQLITE_IOERR_NOMEM;
38883    }
38884    if( osGetTempPathW(nMax, zWidePath)==0 ){
38885      sqlite3_free(zWidePath);
38886      sqlite3_free(zBuf);
38887      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
38888      return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
38889                         "winGetTempname2", 0);
38890    }
38891    zMulti = winUnicodeToUtf8(zWidePath);
38892    if( zMulti ){
38893      sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
38894      sqlite3_free(zMulti);
38895      sqlite3_free(zWidePath);
38896    }else{
38897      sqlite3_free(zWidePath);
38898      sqlite3_free(zBuf);
38899      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
38900      return SQLITE_IOERR_NOMEM;
38901    }
38902  }
38903#ifdef SQLITE_WIN32_HAS_ANSI
38904  else{
38905    char *zUtf8;
38906    char *zMbcsPath = sqlite3MallocZero( nMax );
38907    if( !zMbcsPath ){
38908      sqlite3_free(zBuf);
38909      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
38910      return SQLITE_IOERR_NOMEM;
38911    }
38912    if( osGetTempPathA(nMax, zMbcsPath)==0 ){
38913      sqlite3_free(zBuf);
38914      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
38915      return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
38916                         "winGetTempname3", 0);
38917    }
38918    zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
38919    if( zUtf8 ){
38920      sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
38921      sqlite3_free(zUtf8);
38922    }else{
38923      sqlite3_free(zBuf);
38924      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
38925      return SQLITE_IOERR_NOMEM;
38926    }
38927  }
38928#endif /* SQLITE_WIN32_HAS_ANSI */
38929#endif /* !SQLITE_OS_WINRT */
38930
38931  /*
38932  ** Check to make sure the temporary directory ends with an appropriate
38933  ** separator.  If it does not and there is not enough space left to add
38934  ** one, fail.
38935  */
38936  if( !winMakeEndInDirSep(nDir+1, zBuf) ){
38937    sqlite3_free(zBuf);
38938    OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
38939    return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
38940  }
38941
38942  /*
38943  ** Check that the output buffer is large enough for the temporary file
38944  ** name in the following format:
38945  **
38946  **   "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
38947  **
38948  ** If not, return SQLITE_ERROR.  The number 17 is used here in order to
38949  ** account for the space used by the 15 character random suffix and the
38950  ** two trailing NUL characters.  The final directory separator character
38951  ** has already added if it was not already present.
38952  */
38953  nLen = sqlite3Strlen30(zBuf);
38954  if( (nLen + nPre + 17) > nBuf ){
38955    sqlite3_free(zBuf);
38956    OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
38957    return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
38958  }
38959
38960  sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
38961
38962  j = sqlite3Strlen30(zBuf);
38963  sqlite3_randomness(15, &zBuf[j]);
38964  for(i=0; i<15; i++, j++){
38965    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
38966  }
38967  zBuf[j] = 0;
38968  zBuf[j+1] = 0;
38969  *pzBuf = zBuf;
38970
38971  OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
38972  return SQLITE_OK;
38973}
38974
38975/*
38976** Return TRUE if the named file is really a directory.  Return false if
38977** it is something other than a directory, or if there is any kind of memory
38978** allocation failure.
38979*/
38980static int winIsDir(const void *zConverted){
38981  DWORD attr;
38982  int rc = 0;
38983  DWORD lastErrno;
38984
38985  if( osIsNT() ){
38986    int cnt = 0;
38987    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
38988    memset(&sAttrData, 0, sizeof(sAttrData));
38989    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
38990                             GetFileExInfoStandard,
38991                             &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
38992    if( !rc ){
38993      return 0; /* Invalid name? */
38994    }
38995    attr = sAttrData.dwFileAttributes;
38996#if SQLITE_OS_WINCE==0
38997  }else{
38998    attr = osGetFileAttributesA((char*)zConverted);
38999#endif
39000  }
39001  return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
39002}
39003
39004/*
39005** Open a file.
39006*/
39007static int winOpen(
39008  sqlite3_vfs *pVfs,        /* Used to get maximum path name length */
39009  const char *zName,        /* Name of the file (UTF-8) */
39010  sqlite3_file *id,         /* Write the SQLite file handle here */
39011  int flags,                /* Open mode flags */
39012  int *pOutFlags            /* Status return flags */
39013){
39014  HANDLE h;
39015  DWORD lastErrno = 0;
39016  DWORD dwDesiredAccess;
39017  DWORD dwShareMode;
39018  DWORD dwCreationDisposition;
39019  DWORD dwFlagsAndAttributes = 0;
39020#if SQLITE_OS_WINCE
39021  int isTemp = 0;
39022#endif
39023  winFile *pFile = (winFile*)id;
39024  void *zConverted;              /* Filename in OS encoding */
39025  const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
39026  int cnt = 0;
39027
39028  /* If argument zPath is a NULL pointer, this function is required to open
39029  ** a temporary file. Use this buffer to store the file name in.
39030  */
39031  char *zTmpname = 0; /* For temporary filename, if necessary. */
39032
39033  int rc = SQLITE_OK;            /* Function Return Code */
39034#if !defined(NDEBUG) || SQLITE_OS_WINCE
39035  int eType = flags&0xFFFFFF00;  /* Type of file to open */
39036#endif
39037
39038  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
39039  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
39040  int isCreate     = (flags & SQLITE_OPEN_CREATE);
39041  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
39042  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
39043
39044#ifndef NDEBUG
39045  int isOpenJournal = (isCreate && (
39046        eType==SQLITE_OPEN_MASTER_JOURNAL
39047     || eType==SQLITE_OPEN_MAIN_JOURNAL
39048     || eType==SQLITE_OPEN_WAL
39049  ));
39050#endif
39051
39052  OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
39053           zUtf8Name, id, flags, pOutFlags));
39054
39055  /* Check the following statements are true:
39056  **
39057  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
39058  **   (b) if CREATE is set, then READWRITE must also be set, and
39059  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
39060  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
39061  */
39062  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
39063  assert(isCreate==0 || isReadWrite);
39064  assert(isExclusive==0 || isCreate);
39065  assert(isDelete==0 || isCreate);
39066
39067  /* The main DB, main journal, WAL file and master journal are never
39068  ** automatically deleted. Nor are they ever temporary files.  */
39069  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
39070  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
39071  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
39072  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
39073
39074  /* Assert that the upper layer has set one of the "file-type" flags. */
39075  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
39076       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
39077       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
39078       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
39079  );
39080
39081  assert( pFile!=0 );
39082  memset(pFile, 0, sizeof(winFile));
39083  pFile->h = INVALID_HANDLE_VALUE;
39084
39085#if SQLITE_OS_WINRT
39086  if( !zUtf8Name && !sqlite3_temp_directory ){
39087    sqlite3_log(SQLITE_ERROR,
39088        "sqlite3_temp_directory variable should be set for WinRT");
39089  }
39090#endif
39091
39092  /* If the second argument to this function is NULL, generate a
39093  ** temporary file name to use
39094  */
39095  if( !zUtf8Name ){
39096    assert( isDelete && !isOpenJournal );
39097    rc = winGetTempname(pVfs, &zTmpname);
39098    if( rc!=SQLITE_OK ){
39099      OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
39100      return rc;
39101    }
39102    zUtf8Name = zTmpname;
39103  }
39104
39105  /* Database filenames are double-zero terminated if they are not
39106  ** URIs with parameters.  Hence, they can always be passed into
39107  ** sqlite3_uri_parameter().
39108  */
39109  assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
39110       zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
39111
39112  /* Convert the filename to the system encoding. */
39113  zConverted = winConvertFromUtf8Filename(zUtf8Name);
39114  if( zConverted==0 ){
39115    sqlite3_free(zTmpname);
39116    OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
39117    return SQLITE_IOERR_NOMEM;
39118  }
39119
39120  if( winIsDir(zConverted) ){
39121    sqlite3_free(zConverted);
39122    sqlite3_free(zTmpname);
39123    OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
39124    return SQLITE_CANTOPEN_ISDIR;
39125  }
39126
39127  if( isReadWrite ){
39128    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
39129  }else{
39130    dwDesiredAccess = GENERIC_READ;
39131  }
39132
39133  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
39134  ** created. SQLite doesn't use it to indicate "exclusive access"
39135  ** as it is usually understood.
39136  */
39137  if( isExclusive ){
39138    /* Creates a new file, only if it does not already exist. */
39139    /* If the file exists, it fails. */
39140    dwCreationDisposition = CREATE_NEW;
39141  }else if( isCreate ){
39142    /* Open existing file, or create if it doesn't exist */
39143    dwCreationDisposition = OPEN_ALWAYS;
39144  }else{
39145    /* Opens a file, only if it exists. */
39146    dwCreationDisposition = OPEN_EXISTING;
39147  }
39148
39149  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
39150
39151  if( isDelete ){
39152#if SQLITE_OS_WINCE
39153    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
39154    isTemp = 1;
39155#else
39156    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
39157                               | FILE_ATTRIBUTE_HIDDEN
39158                               | FILE_FLAG_DELETE_ON_CLOSE;
39159#endif
39160  }else{
39161    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
39162  }
39163  /* Reports from the internet are that performance is always
39164  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
39165#if SQLITE_OS_WINCE
39166  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
39167#endif
39168
39169  if( osIsNT() ){
39170#if SQLITE_OS_WINRT
39171    CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
39172    extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
39173    extendedParameters.dwFileAttributes =
39174            dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
39175    extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
39176    extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
39177    extendedParameters.lpSecurityAttributes = NULL;
39178    extendedParameters.hTemplateFile = NULL;
39179    while( (h = osCreateFile2((LPCWSTR)zConverted,
39180                              dwDesiredAccess,
39181                              dwShareMode,
39182                              dwCreationDisposition,
39183                              &extendedParameters))==INVALID_HANDLE_VALUE &&
39184                              winRetryIoerr(&cnt, &lastErrno) ){
39185               /* Noop */
39186    }
39187#else
39188    while( (h = osCreateFileW((LPCWSTR)zConverted,
39189                              dwDesiredAccess,
39190                              dwShareMode, NULL,
39191                              dwCreationDisposition,
39192                              dwFlagsAndAttributes,
39193                              NULL))==INVALID_HANDLE_VALUE &&
39194                              winRetryIoerr(&cnt, &lastErrno) ){
39195               /* Noop */
39196    }
39197#endif
39198  }
39199#ifdef SQLITE_WIN32_HAS_ANSI
39200  else{
39201    while( (h = osCreateFileA((LPCSTR)zConverted,
39202                              dwDesiredAccess,
39203                              dwShareMode, NULL,
39204                              dwCreationDisposition,
39205                              dwFlagsAndAttributes,
39206                              NULL))==INVALID_HANDLE_VALUE &&
39207                              winRetryIoerr(&cnt, &lastErrno) ){
39208               /* Noop */
39209    }
39210  }
39211#endif
39212  winLogIoerr(cnt, __LINE__);
39213
39214  OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
39215           dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
39216
39217  if( h==INVALID_HANDLE_VALUE ){
39218    pFile->lastErrno = lastErrno;
39219    winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
39220    sqlite3_free(zConverted);
39221    sqlite3_free(zTmpname);
39222    if( isReadWrite && !isExclusive ){
39223      return winOpen(pVfs, zName, id,
39224         ((flags|SQLITE_OPEN_READONLY) &
39225                     ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
39226         pOutFlags);
39227    }else{
39228      return SQLITE_CANTOPEN_BKPT;
39229    }
39230  }
39231
39232  if( pOutFlags ){
39233    if( isReadWrite ){
39234      *pOutFlags = SQLITE_OPEN_READWRITE;
39235    }else{
39236      *pOutFlags = SQLITE_OPEN_READONLY;
39237    }
39238  }
39239
39240  OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
39241           "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
39242           *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
39243
39244#if SQLITE_OS_WINCE
39245  if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
39246       && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
39247  ){
39248    osCloseHandle(h);
39249    sqlite3_free(zConverted);
39250    sqlite3_free(zTmpname);
39251    OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
39252    return rc;
39253  }
39254  if( isTemp ){
39255    pFile->zDeleteOnClose = zConverted;
39256  }else
39257#endif
39258  {
39259    sqlite3_free(zConverted);
39260  }
39261
39262  sqlite3_free(zTmpname);
39263  pFile->pMethod = &winIoMethod;
39264  pFile->pVfs = pVfs;
39265  pFile->h = h;
39266  if( isReadonly ){
39267    pFile->ctrlFlags |= WINFILE_RDONLY;
39268  }
39269  if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
39270    pFile->ctrlFlags |= WINFILE_PSOW;
39271  }
39272  pFile->lastErrno = NO_ERROR;
39273  pFile->zPath = zName;
39274#if SQLITE_MAX_MMAP_SIZE>0
39275  pFile->hMap = NULL;
39276  pFile->pMapRegion = 0;
39277  pFile->mmapSize = 0;
39278  pFile->mmapSizeActual = 0;
39279  pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
39280#endif
39281
39282  OpenCounter(+1);
39283  return rc;
39284}
39285
39286/*
39287** Delete the named file.
39288**
39289** Note that Windows does not allow a file to be deleted if some other
39290** process has it open.  Sometimes a virus scanner or indexing program
39291** will open a journal file shortly after it is created in order to do
39292** whatever it does.  While this other process is holding the
39293** file open, we will be unable to delete it.  To work around this
39294** problem, we delay 100 milliseconds and try to delete again.  Up
39295** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
39296** up and returning an error.
39297*/
39298static int winDelete(
39299  sqlite3_vfs *pVfs,          /* Not used on win32 */
39300  const char *zFilename,      /* Name of file to delete */
39301  int syncDir                 /* Not used on win32 */
39302){
39303  int cnt = 0;
39304  int rc;
39305  DWORD attr;
39306  DWORD lastErrno = 0;
39307  void *zConverted;
39308  UNUSED_PARAMETER(pVfs);
39309  UNUSED_PARAMETER(syncDir);
39310
39311  SimulateIOError(return SQLITE_IOERR_DELETE);
39312  OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
39313
39314  zConverted = winConvertFromUtf8Filename(zFilename);
39315  if( zConverted==0 ){
39316    OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
39317    return SQLITE_IOERR_NOMEM;
39318  }
39319  if( osIsNT() ){
39320    do {
39321#if SQLITE_OS_WINRT
39322      WIN32_FILE_ATTRIBUTE_DATA sAttrData;
39323      memset(&sAttrData, 0, sizeof(sAttrData));
39324      if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
39325                                  &sAttrData) ){
39326        attr = sAttrData.dwFileAttributes;
39327      }else{
39328        lastErrno = osGetLastError();
39329        if( lastErrno==ERROR_FILE_NOT_FOUND
39330         || lastErrno==ERROR_PATH_NOT_FOUND ){
39331          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
39332        }else{
39333          rc = SQLITE_ERROR;
39334        }
39335        break;
39336      }
39337#else
39338      attr = osGetFileAttributesW(zConverted);
39339#endif
39340      if ( attr==INVALID_FILE_ATTRIBUTES ){
39341        lastErrno = osGetLastError();
39342        if( lastErrno==ERROR_FILE_NOT_FOUND
39343         || lastErrno==ERROR_PATH_NOT_FOUND ){
39344          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
39345        }else{
39346          rc = SQLITE_ERROR;
39347        }
39348        break;
39349      }
39350      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
39351        rc = SQLITE_ERROR; /* Files only. */
39352        break;
39353      }
39354      if ( osDeleteFileW(zConverted) ){
39355        rc = SQLITE_OK; /* Deleted OK. */
39356        break;
39357      }
39358      if ( !winRetryIoerr(&cnt, &lastErrno) ){
39359        rc = SQLITE_ERROR; /* No more retries. */
39360        break;
39361      }
39362    } while(1);
39363  }
39364#ifdef SQLITE_WIN32_HAS_ANSI
39365  else{
39366    do {
39367      attr = osGetFileAttributesA(zConverted);
39368      if ( attr==INVALID_FILE_ATTRIBUTES ){
39369        lastErrno = osGetLastError();
39370        if( lastErrno==ERROR_FILE_NOT_FOUND
39371         || lastErrno==ERROR_PATH_NOT_FOUND ){
39372          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
39373        }else{
39374          rc = SQLITE_ERROR;
39375        }
39376        break;
39377      }
39378      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
39379        rc = SQLITE_ERROR; /* Files only. */
39380        break;
39381      }
39382      if ( osDeleteFileA(zConverted) ){
39383        rc = SQLITE_OK; /* Deleted OK. */
39384        break;
39385      }
39386      if ( !winRetryIoerr(&cnt, &lastErrno) ){
39387        rc = SQLITE_ERROR; /* No more retries. */
39388        break;
39389      }
39390    } while(1);
39391  }
39392#endif
39393  if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
39394    rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
39395  }else{
39396    winLogIoerr(cnt, __LINE__);
39397  }
39398  sqlite3_free(zConverted);
39399  OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
39400  return rc;
39401}
39402
39403/*
39404** Check the existence and status of a file.
39405*/
39406static int winAccess(
39407  sqlite3_vfs *pVfs,         /* Not used on win32 */
39408  const char *zFilename,     /* Name of file to check */
39409  int flags,                 /* Type of test to make on this file */
39410  int *pResOut               /* OUT: Result */
39411){
39412  DWORD attr;
39413  int rc = 0;
39414  DWORD lastErrno = 0;
39415  void *zConverted;
39416  UNUSED_PARAMETER(pVfs);
39417
39418  SimulateIOError( return SQLITE_IOERR_ACCESS; );
39419  OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
39420           zFilename, flags, pResOut));
39421
39422  zConverted = winConvertFromUtf8Filename(zFilename);
39423  if( zConverted==0 ){
39424    OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
39425    return SQLITE_IOERR_NOMEM;
39426  }
39427  if( osIsNT() ){
39428    int cnt = 0;
39429    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
39430    memset(&sAttrData, 0, sizeof(sAttrData));
39431    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
39432                             GetFileExInfoStandard,
39433                             &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
39434    if( rc ){
39435      /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
39436      ** as if it does not exist.
39437      */
39438      if(    flags==SQLITE_ACCESS_EXISTS
39439          && sAttrData.nFileSizeHigh==0
39440          && sAttrData.nFileSizeLow==0 ){
39441        attr = INVALID_FILE_ATTRIBUTES;
39442      }else{
39443        attr = sAttrData.dwFileAttributes;
39444      }
39445    }else{
39446      winLogIoerr(cnt, __LINE__);
39447      if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
39448        sqlite3_free(zConverted);
39449        return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
39450                           zFilename);
39451      }else{
39452        attr = INVALID_FILE_ATTRIBUTES;
39453      }
39454    }
39455  }
39456#ifdef SQLITE_WIN32_HAS_ANSI
39457  else{
39458    attr = osGetFileAttributesA((char*)zConverted);
39459  }
39460#endif
39461  sqlite3_free(zConverted);
39462  switch( flags ){
39463    case SQLITE_ACCESS_READ:
39464    case SQLITE_ACCESS_EXISTS:
39465      rc = attr!=INVALID_FILE_ATTRIBUTES;
39466      break;
39467    case SQLITE_ACCESS_READWRITE:
39468      rc = attr!=INVALID_FILE_ATTRIBUTES &&
39469             (attr & FILE_ATTRIBUTE_READONLY)==0;
39470      break;
39471    default:
39472      assert(!"Invalid flags argument");
39473  }
39474  *pResOut = rc;
39475  OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
39476           zFilename, pResOut, *pResOut));
39477  return SQLITE_OK;
39478}
39479
39480/*
39481** Returns non-zero if the specified path name starts with a drive letter
39482** followed by a colon character.
39483*/
39484static BOOL winIsDriveLetterAndColon(
39485  const char *zPathname
39486){
39487  return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
39488}
39489
39490/*
39491** Returns non-zero if the specified path name should be used verbatim.  If
39492** non-zero is returned from this function, the calling function must simply
39493** use the provided path name verbatim -OR- resolve it into a full path name
39494** using the GetFullPathName Win32 API function (if available).
39495*/
39496static BOOL winIsVerbatimPathname(
39497  const char *zPathname
39498){
39499  /*
39500  ** If the path name starts with a forward slash or a backslash, it is either
39501  ** a legal UNC name, a volume relative path, or an absolute path name in the
39502  ** "Unix" format on Windows.  There is no easy way to differentiate between
39503  ** the final two cases; therefore, we return the safer return value of TRUE
39504  ** so that callers of this function will simply use it verbatim.
39505  */
39506  if ( winIsDirSep(zPathname[0]) ){
39507    return TRUE;
39508  }
39509
39510  /*
39511  ** If the path name starts with a letter and a colon it is either a volume
39512  ** relative path or an absolute path.  Callers of this function must not
39513  ** attempt to treat it as a relative path name (i.e. they should simply use
39514  ** it verbatim).
39515  */
39516  if ( winIsDriveLetterAndColon(zPathname) ){
39517    return TRUE;
39518  }
39519
39520  /*
39521  ** If we get to this point, the path name should almost certainly be a purely
39522  ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
39523  */
39524  return FALSE;
39525}
39526
39527/*
39528** Turn a relative pathname into a full pathname.  Write the full
39529** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
39530** bytes in size.
39531*/
39532static int winFullPathname(
39533  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
39534  const char *zRelative,        /* Possibly relative input path */
39535  int nFull,                    /* Size of output buffer in bytes */
39536  char *zFull                   /* Output buffer */
39537){
39538
39539#if defined(__CYGWIN__)
39540  SimulateIOError( return SQLITE_ERROR );
39541  UNUSED_PARAMETER(nFull);
39542  assert( nFull>=pVfs->mxPathname );
39543  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
39544    /*
39545    ** NOTE: We are dealing with a relative path name and the data
39546    **       directory has been set.  Therefore, use it as the basis
39547    **       for converting the relative path name to an absolute
39548    **       one by prepending the data directory and a slash.
39549    */
39550    char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
39551    if( !zOut ){
39552      return SQLITE_IOERR_NOMEM;
39553    }
39554    if( cygwin_conv_path(
39555            (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
39556            CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
39557      sqlite3_free(zOut);
39558      return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
39559                         "winFullPathname1", zRelative);
39560    }else{
39561      char *zUtf8 = winConvertToUtf8Filename(zOut);
39562      if( !zUtf8 ){
39563        sqlite3_free(zOut);
39564        return SQLITE_IOERR_NOMEM;
39565      }
39566      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
39567                       sqlite3_data_directory, winGetDirSep(), zUtf8);
39568      sqlite3_free(zUtf8);
39569      sqlite3_free(zOut);
39570    }
39571  }else{
39572    char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
39573    if( !zOut ){
39574      return SQLITE_IOERR_NOMEM;
39575    }
39576    if( cygwin_conv_path(
39577            (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
39578            zRelative, zOut, pVfs->mxPathname+1)<0 ){
39579      sqlite3_free(zOut);
39580      return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
39581                         "winFullPathname2", zRelative);
39582    }else{
39583      char *zUtf8 = winConvertToUtf8Filename(zOut);
39584      if( !zUtf8 ){
39585        sqlite3_free(zOut);
39586        return SQLITE_IOERR_NOMEM;
39587      }
39588      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
39589      sqlite3_free(zUtf8);
39590      sqlite3_free(zOut);
39591    }
39592  }
39593  return SQLITE_OK;
39594#endif
39595
39596#if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
39597  SimulateIOError( return SQLITE_ERROR );
39598  /* WinCE has no concept of a relative pathname, or so I am told. */
39599  /* WinRT has no way to convert a relative path to an absolute one. */
39600  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
39601    /*
39602    ** NOTE: We are dealing with a relative path name and the data
39603    **       directory has been set.  Therefore, use it as the basis
39604    **       for converting the relative path name to an absolute
39605    **       one by prepending the data directory and a backslash.
39606    */
39607    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
39608                     sqlite3_data_directory, winGetDirSep(), zRelative);
39609  }else{
39610    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
39611  }
39612  return SQLITE_OK;
39613#endif
39614
39615#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
39616  DWORD nByte;
39617  void *zConverted;
39618  char *zOut;
39619
39620  /* If this path name begins with "/X:", where "X" is any alphabetic
39621  ** character, discard the initial "/" from the pathname.
39622  */
39623  if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
39624    zRelative++;
39625  }
39626
39627  /* It's odd to simulate an io-error here, but really this is just
39628  ** using the io-error infrastructure to test that SQLite handles this
39629  ** function failing. This function could fail if, for example, the
39630  ** current working directory has been unlinked.
39631  */
39632  SimulateIOError( return SQLITE_ERROR );
39633  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
39634    /*
39635    ** NOTE: We are dealing with a relative path name and the data
39636    **       directory has been set.  Therefore, use it as the basis
39637    **       for converting the relative path name to an absolute
39638    **       one by prepending the data directory and a backslash.
39639    */
39640    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
39641                     sqlite3_data_directory, winGetDirSep(), zRelative);
39642    return SQLITE_OK;
39643  }
39644  zConverted = winConvertFromUtf8Filename(zRelative);
39645  if( zConverted==0 ){
39646    return SQLITE_IOERR_NOMEM;
39647  }
39648  if( osIsNT() ){
39649    LPWSTR zTemp;
39650    nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
39651    if( nByte==0 ){
39652      sqlite3_free(zConverted);
39653      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
39654                         "winFullPathname1", zRelative);
39655    }
39656    nByte += 3;
39657    zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
39658    if( zTemp==0 ){
39659      sqlite3_free(zConverted);
39660      return SQLITE_IOERR_NOMEM;
39661    }
39662    nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
39663    if( nByte==0 ){
39664      sqlite3_free(zConverted);
39665      sqlite3_free(zTemp);
39666      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
39667                         "winFullPathname2", zRelative);
39668    }
39669    sqlite3_free(zConverted);
39670    zOut = winUnicodeToUtf8(zTemp);
39671    sqlite3_free(zTemp);
39672  }
39673#ifdef SQLITE_WIN32_HAS_ANSI
39674  else{
39675    char *zTemp;
39676    nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
39677    if( nByte==0 ){
39678      sqlite3_free(zConverted);
39679      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
39680                         "winFullPathname3", zRelative);
39681    }
39682    nByte += 3;
39683    zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
39684    if( zTemp==0 ){
39685      sqlite3_free(zConverted);
39686      return SQLITE_IOERR_NOMEM;
39687    }
39688    nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
39689    if( nByte==0 ){
39690      sqlite3_free(zConverted);
39691      sqlite3_free(zTemp);
39692      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
39693                         "winFullPathname4", zRelative);
39694    }
39695    sqlite3_free(zConverted);
39696    zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
39697    sqlite3_free(zTemp);
39698  }
39699#endif
39700  if( zOut ){
39701    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
39702    sqlite3_free(zOut);
39703    return SQLITE_OK;
39704  }else{
39705    return SQLITE_IOERR_NOMEM;
39706  }
39707#endif
39708}
39709
39710#ifndef SQLITE_OMIT_LOAD_EXTENSION
39711/*
39712** Interfaces for opening a shared library, finding entry points
39713** within the shared library, and closing the shared library.
39714*/
39715static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
39716  HANDLE h;
39717#if defined(__CYGWIN__)
39718  int nFull = pVfs->mxPathname+1;
39719  char *zFull = sqlite3MallocZero( nFull );
39720  void *zConverted = 0;
39721  if( zFull==0 ){
39722    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
39723    return 0;
39724  }
39725  if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
39726    sqlite3_free(zFull);
39727    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
39728    return 0;
39729  }
39730  zConverted = winConvertFromUtf8Filename(zFull);
39731  sqlite3_free(zFull);
39732#else
39733  void *zConverted = winConvertFromUtf8Filename(zFilename);
39734  UNUSED_PARAMETER(pVfs);
39735#endif
39736  if( zConverted==0 ){
39737    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
39738    return 0;
39739  }
39740  if( osIsNT() ){
39741#if SQLITE_OS_WINRT
39742    h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
39743#else
39744    h = osLoadLibraryW((LPCWSTR)zConverted);
39745#endif
39746  }
39747#ifdef SQLITE_WIN32_HAS_ANSI
39748  else{
39749    h = osLoadLibraryA((char*)zConverted);
39750  }
39751#endif
39752  OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
39753  sqlite3_free(zConverted);
39754  return (void*)h;
39755}
39756static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
39757  UNUSED_PARAMETER(pVfs);
39758  winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
39759}
39760static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
39761  FARPROC proc;
39762  UNUSED_PARAMETER(pVfs);
39763  proc = osGetProcAddressA((HANDLE)pH, zSym);
39764  OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
39765           (void*)pH, zSym, (void*)proc));
39766  return (void(*)(void))proc;
39767}
39768static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
39769  UNUSED_PARAMETER(pVfs);
39770  osFreeLibrary((HANDLE)pHandle);
39771  OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
39772}
39773#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
39774  #define winDlOpen  0
39775  #define winDlError 0
39776  #define winDlSym   0
39777  #define winDlClose 0
39778#endif
39779
39780
39781/*
39782** Write up to nBuf bytes of randomness into zBuf.
39783*/
39784static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
39785  int n = 0;
39786  UNUSED_PARAMETER(pVfs);
39787#if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
39788  n = nBuf;
39789  memset(zBuf, 0, nBuf);
39790#else
39791  if( sizeof(SYSTEMTIME)<=nBuf-n ){
39792    SYSTEMTIME x;
39793    osGetSystemTime(&x);
39794    memcpy(&zBuf[n], &x, sizeof(x));
39795    n += sizeof(x);
39796  }
39797  if( sizeof(DWORD)<=nBuf-n ){
39798    DWORD pid = osGetCurrentProcessId();
39799    memcpy(&zBuf[n], &pid, sizeof(pid));
39800    n += sizeof(pid);
39801  }
39802#if SQLITE_OS_WINRT
39803  if( sizeof(ULONGLONG)<=nBuf-n ){
39804    ULONGLONG cnt = osGetTickCount64();
39805    memcpy(&zBuf[n], &cnt, sizeof(cnt));
39806    n += sizeof(cnt);
39807  }
39808#else
39809  if( sizeof(DWORD)<=nBuf-n ){
39810    DWORD cnt = osGetTickCount();
39811    memcpy(&zBuf[n], &cnt, sizeof(cnt));
39812    n += sizeof(cnt);
39813  }
39814#endif
39815  if( sizeof(LARGE_INTEGER)<=nBuf-n ){
39816    LARGE_INTEGER i;
39817    osQueryPerformanceCounter(&i);
39818    memcpy(&zBuf[n], &i, sizeof(i));
39819    n += sizeof(i);
39820  }
39821#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
39822  if( sizeof(UUID)<=nBuf-n ){
39823    UUID id;
39824    memset(&id, 0, sizeof(UUID));
39825    osUuidCreate(&id);
39826    memcpy(&zBuf[n], &id, sizeof(UUID));
39827    n += sizeof(UUID);
39828  }
39829  if( sizeof(UUID)<=nBuf-n ){
39830    UUID id;
39831    memset(&id, 0, sizeof(UUID));
39832    osUuidCreateSequential(&id);
39833    memcpy(&zBuf[n], &id, sizeof(UUID));
39834    n += sizeof(UUID);
39835  }
39836#endif
39837#endif /* defined(SQLITE_TEST) || defined(SQLITE_ZERO_PRNG_SEED) */
39838  return n;
39839}
39840
39841
39842/*
39843** Sleep for a little while.  Return the amount of time slept.
39844*/
39845static int winSleep(sqlite3_vfs *pVfs, int microsec){
39846  sqlite3_win32_sleep((microsec+999)/1000);
39847  UNUSED_PARAMETER(pVfs);
39848  return ((microsec+999)/1000)*1000;
39849}
39850
39851/*
39852** The following variable, if set to a non-zero value, is interpreted as
39853** the number of seconds since 1970 and is used to set the result of
39854** sqlite3OsCurrentTime() during testing.
39855*/
39856#ifdef SQLITE_TEST
39857SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
39858#endif
39859
39860/*
39861** Find the current time (in Universal Coordinated Time).  Write into *piNow
39862** the current time and date as a Julian Day number times 86_400_000.  In
39863** other words, write into *piNow the number of milliseconds since the Julian
39864** epoch of noon in Greenwich on November 24, 4714 B.C according to the
39865** proleptic Gregorian calendar.
39866**
39867** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
39868** cannot be found.
39869*/
39870static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
39871  /* FILETIME structure is a 64-bit value representing the number of
39872     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
39873  */
39874  FILETIME ft;
39875  static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
39876#ifdef SQLITE_TEST
39877  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
39878#endif
39879  /* 2^32 - to avoid use of LL and warnings in gcc */
39880  static const sqlite3_int64 max32BitValue =
39881      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
39882      (sqlite3_int64)294967296;
39883
39884#if SQLITE_OS_WINCE
39885  SYSTEMTIME time;
39886  osGetSystemTime(&time);
39887  /* if SystemTimeToFileTime() fails, it returns zero. */
39888  if (!osSystemTimeToFileTime(&time,&ft)){
39889    return SQLITE_ERROR;
39890  }
39891#else
39892  osGetSystemTimeAsFileTime( &ft );
39893#endif
39894
39895  *piNow = winFiletimeEpoch +
39896            ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
39897               (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
39898
39899#ifdef SQLITE_TEST
39900  if( sqlite3_current_time ){
39901    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
39902  }
39903#endif
39904  UNUSED_PARAMETER(pVfs);
39905  return SQLITE_OK;
39906}
39907
39908/*
39909** Find the current time (in Universal Coordinated Time).  Write the
39910** current time and date as a Julian Day number into *prNow and
39911** return 0.  Return 1 if the time and date cannot be found.
39912*/
39913static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
39914  int rc;
39915  sqlite3_int64 i;
39916  rc = winCurrentTimeInt64(pVfs, &i);
39917  if( !rc ){
39918    *prNow = i/86400000.0;
39919  }
39920  return rc;
39921}
39922
39923/*
39924** The idea is that this function works like a combination of
39925** GetLastError() and FormatMessage() on Windows (or errno and
39926** strerror_r() on Unix). After an error is returned by an OS
39927** function, SQLite calls this function with zBuf pointing to
39928** a buffer of nBuf bytes. The OS layer should populate the
39929** buffer with a nul-terminated UTF-8 encoded error message
39930** describing the last IO error to have occurred within the calling
39931** thread.
39932**
39933** If the error message is too large for the supplied buffer,
39934** it should be truncated. The return value of xGetLastError
39935** is zero if the error message fits in the buffer, or non-zero
39936** otherwise (if the message was truncated). If non-zero is returned,
39937** then it is not necessary to include the nul-terminator character
39938** in the output buffer.
39939**
39940** Not supplying an error message will have no adverse effect
39941** on SQLite. It is fine to have an implementation that never
39942** returns an error message:
39943**
39944**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
39945**     assert(zBuf[0]=='\0');
39946**     return 0;
39947**   }
39948**
39949** However if an error message is supplied, it will be incorporated
39950** by sqlite into the error message available to the user using
39951** sqlite3_errmsg(), possibly making IO errors easier to debug.
39952*/
39953static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
39954  UNUSED_PARAMETER(pVfs);
39955  return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
39956}
39957
39958/*
39959** Initialize and deinitialize the operating system interface.
39960*/
39961SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void){
39962  static sqlite3_vfs winVfs = {
39963    3,                   /* iVersion */
39964    sizeof(winFile),     /* szOsFile */
39965    SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
39966    0,                   /* pNext */
39967    "win32",             /* zName */
39968    0,                   /* pAppData */
39969    winOpen,             /* xOpen */
39970    winDelete,           /* xDelete */
39971    winAccess,           /* xAccess */
39972    winFullPathname,     /* xFullPathname */
39973    winDlOpen,           /* xDlOpen */
39974    winDlError,          /* xDlError */
39975    winDlSym,            /* xDlSym */
39976    winDlClose,          /* xDlClose */
39977    winRandomness,       /* xRandomness */
39978    winSleep,            /* xSleep */
39979    winCurrentTime,      /* xCurrentTime */
39980    winGetLastError,     /* xGetLastError */
39981    winCurrentTimeInt64, /* xCurrentTimeInt64 */
39982    winSetSystemCall,    /* xSetSystemCall */
39983    winGetSystemCall,    /* xGetSystemCall */
39984    winNextSystemCall,   /* xNextSystemCall */
39985  };
39986#if defined(SQLITE_WIN32_HAS_WIDE)
39987  static sqlite3_vfs winLongPathVfs = {
39988    3,                   /* iVersion */
39989    sizeof(winFile),     /* szOsFile */
39990    SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
39991    0,                   /* pNext */
39992    "win32-longpath",    /* zName */
39993    0,                   /* pAppData */
39994    winOpen,             /* xOpen */
39995    winDelete,           /* xDelete */
39996    winAccess,           /* xAccess */
39997    winFullPathname,     /* xFullPathname */
39998    winDlOpen,           /* xDlOpen */
39999    winDlError,          /* xDlError */
40000    winDlSym,            /* xDlSym */
40001    winDlClose,          /* xDlClose */
40002    winRandomness,       /* xRandomness */
40003    winSleep,            /* xSleep */
40004    winCurrentTime,      /* xCurrentTime */
40005    winGetLastError,     /* xGetLastError */
40006    winCurrentTimeInt64, /* xCurrentTimeInt64 */
40007    winSetSystemCall,    /* xSetSystemCall */
40008    winGetSystemCall,    /* xGetSystemCall */
40009    winNextSystemCall,   /* xNextSystemCall */
40010  };
40011#endif
40012
40013  /* Double-check that the aSyscall[] array has been constructed
40014  ** correctly.  See ticket [bb3a86e890c8e96ab] */
40015  assert( ArraySize(aSyscall)==80 );
40016
40017  /* get memory map allocation granularity */
40018  memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
40019#if SQLITE_OS_WINRT
40020  osGetNativeSystemInfo(&winSysInfo);
40021#else
40022  osGetSystemInfo(&winSysInfo);
40023#endif
40024  assert( winSysInfo.dwAllocationGranularity>0 );
40025  assert( winSysInfo.dwPageSize>0 );
40026
40027  sqlite3_vfs_register(&winVfs, 1);
40028
40029#if defined(SQLITE_WIN32_HAS_WIDE)
40030  sqlite3_vfs_register(&winLongPathVfs, 0);
40031#endif
40032
40033  return SQLITE_OK;
40034}
40035
40036SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void){
40037#if SQLITE_OS_WINRT
40038  if( sleepObj!=NULL ){
40039    osCloseHandle(sleepObj);
40040    sleepObj = NULL;
40041  }
40042#endif
40043  return SQLITE_OK;
40044}
40045
40046#endif /* SQLITE_OS_WIN */
40047
40048/************** End of os_win.c **********************************************/
40049/************** Begin file bitvec.c ******************************************/
40050/*
40051** 2008 February 16
40052**
40053** The author disclaims copyright to this source code.  In place of
40054** a legal notice, here is a blessing:
40055**
40056**    May you do good and not evil.
40057**    May you find forgiveness for yourself and forgive others.
40058**    May you share freely, never taking more than you give.
40059**
40060*************************************************************************
40061** This file implements an object that represents a fixed-length
40062** bitmap.  Bits are numbered starting with 1.
40063**
40064** A bitmap is used to record which pages of a database file have been
40065** journalled during a transaction, or which pages have the "dont-write"
40066** property.  Usually only a few pages are meet either condition.
40067** So the bitmap is usually sparse and has low cardinality.
40068** But sometimes (for example when during a DROP of a large table) most
40069** or all of the pages in a database can get journalled.  In those cases,
40070** the bitmap becomes dense with high cardinality.  The algorithm needs
40071** to handle both cases well.
40072**
40073** The size of the bitmap is fixed when the object is created.
40074**
40075** All bits are clear when the bitmap is created.  Individual bits
40076** may be set or cleared one at a time.
40077**
40078** Test operations are about 100 times more common that set operations.
40079** Clear operations are exceedingly rare.  There are usually between
40080** 5 and 500 set operations per Bitvec object, though the number of sets can
40081** sometimes grow into tens of thousands or larger.  The size of the
40082** Bitvec object is the number of pages in the database file at the
40083** start of a transaction, and is thus usually less than a few thousand,
40084** but can be as large as 2 billion for a really big database.
40085*/
40086/* #include "sqliteInt.h" */
40087
40088/* Size of the Bitvec structure in bytes. */
40089#define BITVEC_SZ        512
40090
40091/* Round the union size down to the nearest pointer boundary, since that's how
40092** it will be aligned within the Bitvec struct. */
40093#define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
40094
40095/* Type of the array "element" for the bitmap representation.
40096** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
40097** Setting this to the "natural word" size of your CPU may improve
40098** performance. */
40099#define BITVEC_TELEM     u8
40100/* Size, in bits, of the bitmap element. */
40101#define BITVEC_SZELEM    8
40102/* Number of elements in a bitmap array. */
40103#define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
40104/* Number of bits in the bitmap array. */
40105#define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
40106
40107/* Number of u32 values in hash table. */
40108#define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
40109/* Maximum number of entries in hash table before
40110** sub-dividing and re-hashing. */
40111#define BITVEC_MXHASH    (BITVEC_NINT/2)
40112/* Hashing function for the aHash representation.
40113** Empirical testing showed that the *37 multiplier
40114** (an arbitrary prime)in the hash function provided
40115** no fewer collisions than the no-op *1. */
40116#define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
40117
40118#define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
40119
40120
40121/*
40122** A bitmap is an instance of the following structure.
40123**
40124** This bitmap records the existence of zero or more bits
40125** with values between 1 and iSize, inclusive.
40126**
40127** There are three possible representations of the bitmap.
40128** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
40129** bitmap.  The least significant bit is bit 1.
40130**
40131** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
40132** a hash table that will hold up to BITVEC_MXHASH distinct values.
40133**
40134** Otherwise, the value i is redirected into one of BITVEC_NPTR
40135** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
40136** handles up to iDivisor separate values of i.  apSub[0] holds
40137** values between 1 and iDivisor.  apSub[1] holds values between
40138** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
40139** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
40140** to hold deal with values between 1 and iDivisor.
40141*/
40142struct Bitvec {
40143  u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
40144  u32 nSet;       /* Number of bits that are set - only valid for aHash
40145                  ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
40146                  ** this would be 125. */
40147  u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
40148                  /* Should >=0 for apSub element. */
40149                  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
40150                  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
40151  union {
40152    BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
40153    u32 aHash[BITVEC_NINT];      /* Hash table representation */
40154    Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
40155  } u;
40156};
40157
40158/*
40159** Create a new bitmap object able to handle bits between 0 and iSize,
40160** inclusive.  Return a pointer to the new object.  Return NULL if
40161** malloc fails.
40162*/
40163SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
40164  Bitvec *p;
40165  assert( sizeof(*p)==BITVEC_SZ );
40166  p = sqlite3MallocZero( sizeof(*p) );
40167  if( p ){
40168    p->iSize = iSize;
40169  }
40170  return p;
40171}
40172
40173/*
40174** Check to see if the i-th bit is set.  Return true or false.
40175** If p is NULL (if the bitmap has not been created) or if
40176** i is out of range, then return false.
40177*/
40178SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
40179  assert( p!=0 );
40180  i--;
40181  if( i>=p->iSize ) return 0;
40182  while( p->iDivisor ){
40183    u32 bin = i/p->iDivisor;
40184    i = i%p->iDivisor;
40185    p = p->u.apSub[bin];
40186    if (!p) {
40187      return 0;
40188    }
40189  }
40190  if( p->iSize<=BITVEC_NBIT ){
40191    return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
40192  } else{
40193    u32 h = BITVEC_HASH(i++);
40194    while( p->u.aHash[h] ){
40195      if( p->u.aHash[h]==i ) return 1;
40196      h = (h+1) % BITVEC_NINT;
40197    }
40198    return 0;
40199  }
40200}
40201SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
40202  return p!=0 && sqlite3BitvecTestNotNull(p,i);
40203}
40204
40205/*
40206** Set the i-th bit.  Return 0 on success and an error code if
40207** anything goes wrong.
40208**
40209** This routine might cause sub-bitmaps to be allocated.  Failing
40210** to get the memory needed to hold the sub-bitmap is the only
40211** that can go wrong with an insert, assuming p and i are valid.
40212**
40213** The calling function must ensure that p is a valid Bitvec object
40214** and that the value for "i" is within range of the Bitvec object.
40215** Otherwise the behavior is undefined.
40216*/
40217SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
40218  u32 h;
40219  if( p==0 ) return SQLITE_OK;
40220  assert( i>0 );
40221  assert( i<=p->iSize );
40222  i--;
40223  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
40224    u32 bin = i/p->iDivisor;
40225    i = i%p->iDivisor;
40226    if( p->u.apSub[bin]==0 ){
40227      p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
40228      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
40229    }
40230    p = p->u.apSub[bin];
40231  }
40232  if( p->iSize<=BITVEC_NBIT ){
40233    p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
40234    return SQLITE_OK;
40235  }
40236  h = BITVEC_HASH(i++);
40237  /* if there wasn't a hash collision, and this doesn't */
40238  /* completely fill the hash, then just add it without */
40239  /* worring about sub-dividing and re-hashing. */
40240  if( !p->u.aHash[h] ){
40241    if (p->nSet<(BITVEC_NINT-1)) {
40242      goto bitvec_set_end;
40243    } else {
40244      goto bitvec_set_rehash;
40245    }
40246  }
40247  /* there was a collision, check to see if it's already */
40248  /* in hash, if not, try to find a spot for it */
40249  do {
40250    if( p->u.aHash[h]==i ) return SQLITE_OK;
40251    h++;
40252    if( h>=BITVEC_NINT ) h = 0;
40253  } while( p->u.aHash[h] );
40254  /* we didn't find it in the hash.  h points to the first */
40255  /* available free spot. check to see if this is going to */
40256  /* make our hash too "full".  */
40257bitvec_set_rehash:
40258  if( p->nSet>=BITVEC_MXHASH ){
40259    unsigned int j;
40260    int rc;
40261    u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
40262    if( aiValues==0 ){
40263      return SQLITE_NOMEM;
40264    }else{
40265      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
40266      memset(p->u.apSub, 0, sizeof(p->u.apSub));
40267      p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
40268      rc = sqlite3BitvecSet(p, i);
40269      for(j=0; j<BITVEC_NINT; j++){
40270        if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
40271      }
40272      sqlite3StackFree(0, aiValues);
40273      return rc;
40274    }
40275  }
40276bitvec_set_end:
40277  p->nSet++;
40278  p->u.aHash[h] = i;
40279  return SQLITE_OK;
40280}
40281
40282/*
40283** Clear the i-th bit.
40284**
40285** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
40286** that BitvecClear can use to rebuilt its hash table.
40287*/
40288SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
40289  if( p==0 ) return;
40290  assert( i>0 );
40291  i--;
40292  while( p->iDivisor ){
40293    u32 bin = i/p->iDivisor;
40294    i = i%p->iDivisor;
40295    p = p->u.apSub[bin];
40296    if (!p) {
40297      return;
40298    }
40299  }
40300  if( p->iSize<=BITVEC_NBIT ){
40301    p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
40302  }else{
40303    unsigned int j;
40304    u32 *aiValues = pBuf;
40305    memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
40306    memset(p->u.aHash, 0, sizeof(p->u.aHash));
40307    p->nSet = 0;
40308    for(j=0; j<BITVEC_NINT; j++){
40309      if( aiValues[j] && aiValues[j]!=(i+1) ){
40310        u32 h = BITVEC_HASH(aiValues[j]-1);
40311        p->nSet++;
40312        while( p->u.aHash[h] ){
40313          h++;
40314          if( h>=BITVEC_NINT ) h = 0;
40315        }
40316        p->u.aHash[h] = aiValues[j];
40317      }
40318    }
40319  }
40320}
40321
40322/*
40323** Destroy a bitmap object.  Reclaim all memory used.
40324*/
40325SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
40326  if( p==0 ) return;
40327  if( p->iDivisor ){
40328    unsigned int i;
40329    for(i=0; i<BITVEC_NPTR; i++){
40330      sqlite3BitvecDestroy(p->u.apSub[i]);
40331    }
40332  }
40333  sqlite3_free(p);
40334}
40335
40336/*
40337** Return the value of the iSize parameter specified when Bitvec *p
40338** was created.
40339*/
40340SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
40341  return p->iSize;
40342}
40343
40344#ifndef SQLITE_OMIT_BUILTIN_TEST
40345/*
40346** Let V[] be an array of unsigned characters sufficient to hold
40347** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
40348** Then the following macros can be used to set, clear, or test
40349** individual bits within V.
40350*/
40351#define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
40352#define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
40353#define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
40354
40355/*
40356** This routine runs an extensive test of the Bitvec code.
40357**
40358** The input is an array of integers that acts as a program
40359** to test the Bitvec.  The integers are opcodes followed
40360** by 0, 1, or 3 operands, depending on the opcode.  Another
40361** opcode follows immediately after the last operand.
40362**
40363** There are 6 opcodes numbered from 0 through 5.  0 is the
40364** "halt" opcode and causes the test to end.
40365**
40366**    0          Halt and return the number of errors
40367**    1 N S X    Set N bits beginning with S and incrementing by X
40368**    2 N S X    Clear N bits beginning with S and incrementing by X
40369**    3 N        Set N randomly chosen bits
40370**    4 N        Clear N randomly chosen bits
40371**    5 N S X    Set N bits from S increment X in array only, not in bitvec
40372**
40373** The opcodes 1 through 4 perform set and clear operations are performed
40374** on both a Bitvec object and on a linear array of bits obtained from malloc.
40375** Opcode 5 works on the linear array only, not on the Bitvec.
40376** Opcode 5 is used to deliberately induce a fault in order to
40377** confirm that error detection works.
40378**
40379** At the conclusion of the test the linear array is compared
40380** against the Bitvec object.  If there are any differences,
40381** an error is returned.  If they are the same, zero is returned.
40382**
40383** If a memory allocation error occurs, return -1.
40384*/
40385SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
40386  Bitvec *pBitvec = 0;
40387  unsigned char *pV = 0;
40388  int rc = -1;
40389  int i, nx, pc, op;
40390  void *pTmpSpace;
40391
40392  /* Allocate the Bitvec to be tested and a linear array of
40393  ** bits to act as the reference */
40394  pBitvec = sqlite3BitvecCreate( sz );
40395  pV = sqlite3MallocZero( (sz+7)/8 + 1 );
40396  pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
40397  if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
40398
40399  /* NULL pBitvec tests */
40400  sqlite3BitvecSet(0, 1);
40401  sqlite3BitvecClear(0, 1, pTmpSpace);
40402
40403  /* Run the program */
40404  pc = 0;
40405  while( (op = aOp[pc])!=0 ){
40406    switch( op ){
40407      case 1:
40408      case 2:
40409      case 5: {
40410        nx = 4;
40411        i = aOp[pc+2] - 1;
40412        aOp[pc+2] += aOp[pc+3];
40413        break;
40414      }
40415      case 3:
40416      case 4:
40417      default: {
40418        nx = 2;
40419        sqlite3_randomness(sizeof(i), &i);
40420        break;
40421      }
40422    }
40423    if( (--aOp[pc+1]) > 0 ) nx = 0;
40424    pc += nx;
40425    i = (i & 0x7fffffff)%sz;
40426    if( (op & 1)!=0 ){
40427      SETBIT(pV, (i+1));
40428      if( op!=5 ){
40429        if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
40430      }
40431    }else{
40432      CLEARBIT(pV, (i+1));
40433      sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
40434    }
40435  }
40436
40437  /* Test to make sure the linear array exactly matches the
40438  ** Bitvec object.  Start with the assumption that they do
40439  ** match (rc==0).  Change rc to non-zero if a discrepancy
40440  ** is found.
40441  */
40442  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
40443          + sqlite3BitvecTest(pBitvec, 0)
40444          + (sqlite3BitvecSize(pBitvec) - sz);
40445  for(i=1; i<=sz; i++){
40446    if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
40447      rc = i;
40448      break;
40449    }
40450  }
40451
40452  /* Free allocated structure */
40453bitvec_end:
40454  sqlite3_free(pTmpSpace);
40455  sqlite3_free(pV);
40456  sqlite3BitvecDestroy(pBitvec);
40457  return rc;
40458}
40459#endif /* SQLITE_OMIT_BUILTIN_TEST */
40460
40461/************** End of bitvec.c **********************************************/
40462/************** Begin file pcache.c ******************************************/
40463/*
40464** 2008 August 05
40465**
40466** The author disclaims copyright to this source code.  In place of
40467** a legal notice, here is a blessing:
40468**
40469**    May you do good and not evil.
40470**    May you find forgiveness for yourself and forgive others.
40471**    May you share freely, never taking more than you give.
40472**
40473*************************************************************************
40474** This file implements that page cache.
40475*/
40476/* #include "sqliteInt.h" */
40477
40478/*
40479** A complete page cache is an instance of this structure.
40480*/
40481struct PCache {
40482  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
40483  PgHdr *pSynced;                     /* Last synced page in dirty page list */
40484  int nRefSum;                        /* Sum of ref counts over all pages */
40485  int szCache;                        /* Configured cache size */
40486  int szPage;                         /* Size of every page in this cache */
40487  int szExtra;                        /* Size of extra space for each page */
40488  u8 bPurgeable;                      /* True if pages are on backing store */
40489  u8 eCreate;                         /* eCreate value for for xFetch() */
40490  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
40491  void *pStress;                      /* Argument to xStress */
40492  sqlite3_pcache *pCache;             /* Pluggable cache module */
40493};
40494
40495/********************************** Linked List Management ********************/
40496
40497/* Allowed values for second argument to pcacheManageDirtyList() */
40498#define PCACHE_DIRTYLIST_REMOVE   1    /* Remove pPage from dirty list */
40499#define PCACHE_DIRTYLIST_ADD      2    /* Add pPage to the dirty list */
40500#define PCACHE_DIRTYLIST_FRONT    3    /* Move pPage to the front of the list */
40501
40502/*
40503** Manage pPage's participation on the dirty list.  Bits of the addRemove
40504** argument determines what operation to do.  The 0x01 bit means first
40505** remove pPage from the dirty list.  The 0x02 means add pPage back to
40506** the dirty list.  Doing both moves pPage to the front of the dirty list.
40507*/
40508static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
40509  PCache *p = pPage->pCache;
40510
40511  if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
40512    assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
40513    assert( pPage->pDirtyPrev || pPage==p->pDirty );
40514
40515    /* Update the PCache1.pSynced variable if necessary. */
40516    if( p->pSynced==pPage ){
40517      PgHdr *pSynced = pPage->pDirtyPrev;
40518      while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
40519        pSynced = pSynced->pDirtyPrev;
40520      }
40521      p->pSynced = pSynced;
40522    }
40523
40524    if( pPage->pDirtyNext ){
40525      pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
40526    }else{
40527      assert( pPage==p->pDirtyTail );
40528      p->pDirtyTail = pPage->pDirtyPrev;
40529    }
40530    if( pPage->pDirtyPrev ){
40531      pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
40532    }else{
40533      assert( pPage==p->pDirty );
40534      p->pDirty = pPage->pDirtyNext;
40535      if( p->pDirty==0 && p->bPurgeable ){
40536        assert( p->eCreate==1 );
40537        p->eCreate = 2;
40538      }
40539    }
40540    pPage->pDirtyNext = 0;
40541    pPage->pDirtyPrev = 0;
40542  }
40543  if( addRemove & PCACHE_DIRTYLIST_ADD ){
40544    assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
40545
40546    pPage->pDirtyNext = p->pDirty;
40547    if( pPage->pDirtyNext ){
40548      assert( pPage->pDirtyNext->pDirtyPrev==0 );
40549      pPage->pDirtyNext->pDirtyPrev = pPage;
40550    }else{
40551      p->pDirtyTail = pPage;
40552      if( p->bPurgeable ){
40553        assert( p->eCreate==2 );
40554        p->eCreate = 1;
40555      }
40556    }
40557    p->pDirty = pPage;
40558    if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
40559      p->pSynced = pPage;
40560    }
40561  }
40562}
40563
40564/*
40565** Wrapper around the pluggable caches xUnpin method. If the cache is
40566** being used for an in-memory database, this function is a no-op.
40567*/
40568static void pcacheUnpin(PgHdr *p){
40569  if( p->pCache->bPurgeable ){
40570    sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
40571  }
40572}
40573
40574/*
40575** Compute the number of pages of cache requested.  p->szCache is the
40576** cache size requested by the "PRAGMA cache_size" statement.
40577**
40578**
40579*/
40580static int numberOfCachePages(PCache *p){
40581  if( p->szCache>=0 ){
40582    /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
40583    ** suggested cache size is set to N. */
40584    return p->szCache;
40585  }else{
40586    /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
40587    ** the number of cache pages is adjusted to use approximately abs(N*1024)
40588    ** bytes of memory. */
40589    return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
40590  }
40591}
40592
40593/*************************************************** General Interfaces ******
40594**
40595** Initialize and shutdown the page cache subsystem. Neither of these
40596** functions are threadsafe.
40597*/
40598SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
40599  if( sqlite3GlobalConfig.pcache2.xInit==0 ){
40600    /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
40601    ** built-in default page cache is used instead of the application defined
40602    ** page cache. */
40603    sqlite3PCacheSetDefault();
40604  }
40605  return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
40606}
40607SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
40608  if( sqlite3GlobalConfig.pcache2.xShutdown ){
40609    /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
40610    sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
40611  }
40612}
40613
40614/*
40615** Return the size in bytes of a PCache object.
40616*/
40617SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
40618
40619/*
40620** Create a new PCache object. Storage space to hold the object
40621** has already been allocated and is passed in as the p pointer.
40622** The caller discovers how much space needs to be allocated by
40623** calling sqlite3PcacheSize().
40624*/
40625SQLITE_PRIVATE int sqlite3PcacheOpen(
40626  int szPage,                  /* Size of every page */
40627  int szExtra,                 /* Extra space associated with each page */
40628  int bPurgeable,              /* True if pages are on backing store */
40629  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
40630  void *pStress,               /* Argument to xStress */
40631  PCache *p                    /* Preallocated space for the PCache */
40632){
40633  memset(p, 0, sizeof(PCache));
40634  p->szPage = 1;
40635  p->szExtra = szExtra;
40636  p->bPurgeable = bPurgeable;
40637  p->eCreate = 2;
40638  p->xStress = xStress;
40639  p->pStress = pStress;
40640  p->szCache = 100;
40641  return sqlite3PcacheSetPageSize(p, szPage);
40642}
40643
40644/*
40645** Change the page size for PCache object. The caller must ensure that there
40646** are no outstanding page references when this function is called.
40647*/
40648SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
40649  assert( pCache->nRefSum==0 && pCache->pDirty==0 );
40650  if( pCache->szPage ){
40651    sqlite3_pcache *pNew;
40652    pNew = sqlite3GlobalConfig.pcache2.xCreate(
40653                szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
40654                pCache->bPurgeable
40655    );
40656    if( pNew==0 ) return SQLITE_NOMEM;
40657    sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
40658    if( pCache->pCache ){
40659      sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
40660    }
40661    pCache->pCache = pNew;
40662    pCache->szPage = szPage;
40663  }
40664  return SQLITE_OK;
40665}
40666
40667/*
40668** Try to obtain a page from the cache.
40669**
40670** This routine returns a pointer to an sqlite3_pcache_page object if
40671** such an object is already in cache, or if a new one is created.
40672** This routine returns a NULL pointer if the object was not in cache
40673** and could not be created.
40674**
40675** The createFlags should be 0 to check for existing pages and should
40676** be 3 (not 1, but 3) to try to create a new page.
40677**
40678** If the createFlag is 0, then NULL is always returned if the page
40679** is not already in the cache.  If createFlag is 1, then a new page
40680** is created only if that can be done without spilling dirty pages
40681** and without exceeding the cache size limit.
40682**
40683** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
40684** initialize the sqlite3_pcache_page object and convert it into a
40685** PgHdr object.  The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
40686** routines are split this way for performance reasons. When separated
40687** they can both (usually) operate without having to push values to
40688** the stack on entry and pop them back off on exit, which saves a
40689** lot of pushing and popping.
40690*/
40691SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
40692  PCache *pCache,       /* Obtain the page from this cache */
40693  Pgno pgno,            /* Page number to obtain */
40694  int createFlag        /* If true, create page if it does not exist already */
40695){
40696  int eCreate;
40697
40698  assert( pCache!=0 );
40699  assert( pCache->pCache!=0 );
40700  assert( createFlag==3 || createFlag==0 );
40701  assert( pgno>0 );
40702
40703  /* eCreate defines what to do if the page does not exist.
40704  **    0     Do not allocate a new page.  (createFlag==0)
40705  **    1     Allocate a new page if doing so is inexpensive.
40706  **          (createFlag==1 AND bPurgeable AND pDirty)
40707  **    2     Allocate a new page even it doing so is difficult.
40708  **          (createFlag==1 AND !(bPurgeable AND pDirty)
40709  */
40710  eCreate = createFlag & pCache->eCreate;
40711  assert( eCreate==0 || eCreate==1 || eCreate==2 );
40712  assert( createFlag==0 || pCache->eCreate==eCreate );
40713  assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
40714  return sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
40715}
40716
40717/*
40718** If the sqlite3PcacheFetch() routine is unable to allocate a new
40719** page because new clean pages are available for reuse and the cache
40720** size limit has been reached, then this routine can be invoked to
40721** try harder to allocate a page.  This routine might invoke the stress
40722** callback to spill dirty pages to the journal.  It will then try to
40723** allocate the new page and will only fail to allocate a new page on
40724** an OOM error.
40725**
40726** This routine should be invoked only after sqlite3PcacheFetch() fails.
40727*/
40728SQLITE_PRIVATE int sqlite3PcacheFetchStress(
40729  PCache *pCache,                 /* Obtain the page from this cache */
40730  Pgno pgno,                      /* Page number to obtain */
40731  sqlite3_pcache_page **ppPage    /* Write result here */
40732){
40733  PgHdr *pPg;
40734  if( pCache->eCreate==2 ) return 0;
40735
40736
40737  /* Find a dirty page to write-out and recycle. First try to find a
40738  ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
40739  ** cleared), but if that is not possible settle for any other
40740  ** unreferenced dirty page.
40741  */
40742  for(pPg=pCache->pSynced;
40743      pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
40744      pPg=pPg->pDirtyPrev
40745  );
40746  pCache->pSynced = pPg;
40747  if( !pPg ){
40748    for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
40749  }
40750  if( pPg ){
40751    int rc;
40752#ifdef SQLITE_LOG_CACHE_SPILL
40753    sqlite3_log(SQLITE_FULL,
40754                "spill page %d making room for %d - cache used: %d/%d",
40755                pPg->pgno, pgno,
40756                sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
40757                numberOfCachePages(pCache));
40758#endif
40759    rc = pCache->xStress(pCache->pStress, pPg);
40760    if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
40761      return rc;
40762    }
40763  }
40764  *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
40765  return *ppPage==0 ? SQLITE_NOMEM : SQLITE_OK;
40766}
40767
40768/*
40769** This is a helper routine for sqlite3PcacheFetchFinish()
40770**
40771** In the uncommon case where the page being fetched has not been
40772** initialized, this routine is invoked to do the initialization.
40773** This routine is broken out into a separate function since it
40774** requires extra stack manipulation that can be avoided in the common
40775** case.
40776*/
40777static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
40778  PCache *pCache,             /* Obtain the page from this cache */
40779  Pgno pgno,                  /* Page number obtained */
40780  sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
40781){
40782  PgHdr *pPgHdr;
40783  assert( pPage!=0 );
40784  pPgHdr = (PgHdr*)pPage->pExtra;
40785  assert( pPgHdr->pPage==0 );
40786  memset(pPgHdr, 0, sizeof(PgHdr));
40787  pPgHdr->pPage = pPage;
40788  pPgHdr->pData = pPage->pBuf;
40789  pPgHdr->pExtra = (void *)&pPgHdr[1];
40790  memset(pPgHdr->pExtra, 0, pCache->szExtra);
40791  pPgHdr->pCache = pCache;
40792  pPgHdr->pgno = pgno;
40793  pPgHdr->flags = PGHDR_CLEAN;
40794  return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
40795}
40796
40797/*
40798** This routine converts the sqlite3_pcache_page object returned by
40799** sqlite3PcacheFetch() into an initialized PgHdr object.  This routine
40800** must be called after sqlite3PcacheFetch() in order to get a usable
40801** result.
40802*/
40803SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
40804  PCache *pCache,             /* Obtain the page from this cache */
40805  Pgno pgno,                  /* Page number obtained */
40806  sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
40807){
40808  PgHdr *pPgHdr;
40809
40810  assert( pPage!=0 );
40811  pPgHdr = (PgHdr *)pPage->pExtra;
40812
40813  if( !pPgHdr->pPage ){
40814    return pcacheFetchFinishWithInit(pCache, pgno, pPage);
40815  }
40816  pCache->nRefSum++;
40817  pPgHdr->nRef++;
40818  return pPgHdr;
40819}
40820
40821/*
40822** Decrement the reference count on a page. If the page is clean and the
40823** reference count drops to 0, then it is made eligible for recycling.
40824*/
40825SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
40826  assert( p->nRef>0 );
40827  p->pCache->nRefSum--;
40828  if( (--p->nRef)==0 ){
40829    if( p->flags&PGHDR_CLEAN ){
40830      pcacheUnpin(p);
40831    }else if( p->pDirtyPrev!=0 ){
40832      /* Move the page to the head of the dirty list. */
40833      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
40834    }
40835  }
40836}
40837
40838/*
40839** Increase the reference count of a supplied page by 1.
40840*/
40841SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
40842  assert(p->nRef>0);
40843  p->nRef++;
40844  p->pCache->nRefSum++;
40845}
40846
40847/*
40848** Drop a page from the cache. There must be exactly one reference to the
40849** page. This function deletes that reference, so after it returns the
40850** page pointed to by p is invalid.
40851*/
40852SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
40853  assert( p->nRef==1 );
40854  if( p->flags&PGHDR_DIRTY ){
40855    pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
40856  }
40857  p->pCache->nRefSum--;
40858  sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
40859}
40860
40861/*
40862** Make sure the page is marked as dirty. If it isn't dirty already,
40863** make it so.
40864*/
40865SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
40866  assert( p->nRef>0 );
40867  if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){
40868    p->flags &= ~PGHDR_DONT_WRITE;
40869    if( p->flags & PGHDR_CLEAN ){
40870      p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
40871      assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
40872      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
40873    }
40874  }
40875}
40876
40877/*
40878** Make sure the page is marked as clean. If it isn't clean already,
40879** make it so.
40880*/
40881SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
40882  if( (p->flags & PGHDR_DIRTY) ){
40883    assert( (p->flags & PGHDR_CLEAN)==0 );
40884    pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
40885    p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
40886    p->flags |= PGHDR_CLEAN;
40887    if( p->nRef==0 ){
40888      pcacheUnpin(p);
40889    }
40890  }
40891}
40892
40893/*
40894** Make every page in the cache clean.
40895*/
40896SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
40897  PgHdr *p;
40898  while( (p = pCache->pDirty)!=0 ){
40899    sqlite3PcacheMakeClean(p);
40900  }
40901}
40902
40903/*
40904** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
40905*/
40906SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
40907  PgHdr *p;
40908  for(p=pCache->pDirty; p; p=p->pDirtyNext){
40909    p->flags &= ~PGHDR_NEED_SYNC;
40910  }
40911  pCache->pSynced = pCache->pDirtyTail;
40912}
40913
40914/*
40915** Change the page number of page p to newPgno.
40916*/
40917SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
40918  PCache *pCache = p->pCache;
40919  assert( p->nRef>0 );
40920  assert( newPgno>0 );
40921  sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
40922  p->pgno = newPgno;
40923  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
40924    pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
40925  }
40926}
40927
40928/*
40929** Drop every cache entry whose page number is greater than "pgno". The
40930** caller must ensure that there are no outstanding references to any pages
40931** other than page 1 with a page number greater than pgno.
40932**
40933** If there is a reference to page 1 and the pgno parameter passed to this
40934** function is 0, then the data area associated with page 1 is zeroed, but
40935** the page object is not dropped.
40936*/
40937SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
40938  if( pCache->pCache ){
40939    PgHdr *p;
40940    PgHdr *pNext;
40941    for(p=pCache->pDirty; p; p=pNext){
40942      pNext = p->pDirtyNext;
40943      /* This routine never gets call with a positive pgno except right
40944      ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
40945      ** it must be that pgno==0.
40946      */
40947      assert( p->pgno>0 );
40948      if( ALWAYS(p->pgno>pgno) ){
40949        assert( p->flags&PGHDR_DIRTY );
40950        sqlite3PcacheMakeClean(p);
40951      }
40952    }
40953    if( pgno==0 && pCache->nRefSum ){
40954      sqlite3_pcache_page *pPage1;
40955      pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
40956      if( ALWAYS(pPage1) ){  /* Page 1 is always available in cache, because
40957                             ** pCache->nRefSum>0 */
40958        memset(pPage1->pBuf, 0, pCache->szPage);
40959        pgno = 1;
40960      }
40961    }
40962    sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
40963  }
40964}
40965
40966/*
40967** Close a cache.
40968*/
40969SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
40970  assert( pCache->pCache!=0 );
40971  sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
40972}
40973
40974/*
40975** Discard the contents of the cache.
40976*/
40977SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
40978  sqlite3PcacheTruncate(pCache, 0);
40979}
40980
40981/*
40982** Merge two lists of pages connected by pDirty and in pgno order.
40983** Do not both fixing the pDirtyPrev pointers.
40984*/
40985static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
40986  PgHdr result, *pTail;
40987  pTail = &result;
40988  while( pA && pB ){
40989    if( pA->pgno<pB->pgno ){
40990      pTail->pDirty = pA;
40991      pTail = pA;
40992      pA = pA->pDirty;
40993    }else{
40994      pTail->pDirty = pB;
40995      pTail = pB;
40996      pB = pB->pDirty;
40997    }
40998  }
40999  if( pA ){
41000    pTail->pDirty = pA;
41001  }else if( pB ){
41002    pTail->pDirty = pB;
41003  }else{
41004    pTail->pDirty = 0;
41005  }
41006  return result.pDirty;
41007}
41008
41009/*
41010** Sort the list of pages in accending order by pgno.  Pages are
41011** connected by pDirty pointers.  The pDirtyPrev pointers are
41012** corrupted by this sort.
41013**
41014** Since there cannot be more than 2^31 distinct pages in a database,
41015** there cannot be more than 31 buckets required by the merge sorter.
41016** One extra bucket is added to catch overflow in case something
41017** ever changes to make the previous sentence incorrect.
41018*/
41019#define N_SORT_BUCKET  32
41020static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
41021  PgHdr *a[N_SORT_BUCKET], *p;
41022  int i;
41023  memset(a, 0, sizeof(a));
41024  while( pIn ){
41025    p = pIn;
41026    pIn = p->pDirty;
41027    p->pDirty = 0;
41028    for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
41029      if( a[i]==0 ){
41030        a[i] = p;
41031        break;
41032      }else{
41033        p = pcacheMergeDirtyList(a[i], p);
41034        a[i] = 0;
41035      }
41036    }
41037    if( NEVER(i==N_SORT_BUCKET-1) ){
41038      /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
41039      ** the input list.  But that is impossible.
41040      */
41041      a[i] = pcacheMergeDirtyList(a[i], p);
41042    }
41043  }
41044  p = a[0];
41045  for(i=1; i<N_SORT_BUCKET; i++){
41046    p = pcacheMergeDirtyList(p, a[i]);
41047  }
41048  return p;
41049}
41050
41051/*
41052** Return a list of all dirty pages in the cache, sorted by page number.
41053*/
41054SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
41055  PgHdr *p;
41056  for(p=pCache->pDirty; p; p=p->pDirtyNext){
41057    p->pDirty = p->pDirtyNext;
41058  }
41059  return pcacheSortDirtyList(pCache->pDirty);
41060}
41061
41062/*
41063** Return the total number of references to all pages held by the cache.
41064**
41065** This is not the total number of pages referenced, but the sum of the
41066** reference count for all pages.
41067*/
41068SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
41069  return pCache->nRefSum;
41070}
41071
41072/*
41073** Return the number of references to the page supplied as an argument.
41074*/
41075SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
41076  return p->nRef;
41077}
41078
41079/*
41080** Return the total number of pages in the cache.
41081*/
41082SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
41083  assert( pCache->pCache!=0 );
41084  return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
41085}
41086
41087#ifdef SQLITE_TEST
41088/*
41089** Get the suggested cache-size value.
41090*/
41091SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
41092  return numberOfCachePages(pCache);
41093}
41094#endif
41095
41096/*
41097** Set the suggested cache-size value.
41098*/
41099SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
41100  assert( pCache->pCache!=0 );
41101  pCache->szCache = mxPage;
41102  sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
41103                                         numberOfCachePages(pCache));
41104}
41105
41106/*
41107** Free up as much memory as possible from the page cache.
41108*/
41109SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
41110  assert( pCache->pCache!=0 );
41111  sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
41112}
41113
41114/*
41115** Return the size of the header added by this middleware layer
41116** in the page-cache hierarchy.
41117*/
41118SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
41119
41120
41121#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
41122/*
41123** For all dirty pages currently in the cache, invoke the specified
41124** callback. This is only used if the SQLITE_CHECK_PAGES macro is
41125** defined.
41126*/
41127SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
41128  PgHdr *pDirty;
41129  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
41130    xIter(pDirty);
41131  }
41132}
41133#endif
41134
41135/************** End of pcache.c **********************************************/
41136/************** Begin file pcache1.c *****************************************/
41137/*
41138** 2008 November 05
41139**
41140** The author disclaims copyright to this source code.  In place of
41141** a legal notice, here is a blessing:
41142**
41143**    May you do good and not evil.
41144**    May you find forgiveness for yourself and forgive others.
41145**    May you share freely, never taking more than you give.
41146**
41147*************************************************************************
41148**
41149** This file implements the default page cache implementation (the
41150** sqlite3_pcache interface). It also contains part of the implementation
41151** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
41152** If the default page cache implementation is overridden, then neither of
41153** these two features are available.
41154**
41155** A Page cache line looks like this:
41156**
41157**  -------------------------------------------------------------
41158**  |  database page content   |  PgHdr1  |  MemPage  |  PgHdr  |
41159**  -------------------------------------------------------------
41160**
41161** The database page content is up front (so that buffer overreads tend to
41162** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions).   MemPage
41163** is the extension added by the btree.c module containing information such
41164** as the database page number and how that database page is used.  PgHdr
41165** is added by the pcache.c layer and contains information used to keep track
41166** of which pages are "dirty".  PgHdr1 is an extension added by this
41167** module (pcache1.c).  The PgHdr1 header is a subclass of sqlite3_pcache_page.
41168** PgHdr1 contains information needed to look up a page by its page number.
41169** The superclass sqlite3_pcache_page.pBuf points to the start of the
41170** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
41171**
41172** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
41173** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size).  The
41174** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
41175** size can vary according to architecture, compile-time options, and
41176** SQLite library version number.
41177**
41178** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
41179** using a separate memory allocation from the database page content.  This
41180** seeks to overcome the "clownshoe" problem (also called "internal
41181** fragmentation" in academic literature) of allocating a few bytes more
41182** than a power of two with the memory allocator rounding up to the next
41183** power of two, and leaving the rounded-up space unused.
41184**
41185** This module tracks pointers to PgHdr1 objects.  Only pcache.c communicates
41186** with this module.  Information is passed back and forth as PgHdr1 pointers.
41187**
41188** The pcache.c and pager.c modules deal pointers to PgHdr objects.
41189** The btree.c module deals with pointers to MemPage objects.
41190**
41191** SOURCE OF PAGE CACHE MEMORY:
41192**
41193** Memory for a page might come from any of three sources:
41194**
41195**    (1)  The general-purpose memory allocator - sqlite3Malloc()
41196**    (2)  Global page-cache memory provided using sqlite3_config() with
41197**         SQLITE_CONFIG_PAGECACHE.
41198**    (3)  PCache-local bulk allocation.
41199**
41200** The third case is a chunk of heap memory (defaulting to 100 pages worth)
41201** that is allocated when the page cache is created.  The size of the local
41202** bulk allocation can be adjusted using
41203**
41204**     sqlite3_config(SQLITE_CONFIG_PAGECACHE, 0, 0, N).
41205**
41206** If N is positive, then N pages worth of memory are allocated using a single
41207** sqlite3Malloc() call and that memory is used for the first N pages allocated.
41208** Or if N is negative, then -1024*N bytes of memory are allocated and used
41209** for as many pages as can be accomodated.
41210**
41211** Only one of (2) or (3) can be used.  Once the memory available to (2) or
41212** (3) is exhausted, subsequent allocations fail over to the general-purpose
41213** memory allocator (1).
41214**
41215** Earlier versions of SQLite used only methods (1) and (2).  But experiments
41216** show that method (3) with N==100 provides about a 5% performance boost for
41217** common workloads.
41218*/
41219/* #include "sqliteInt.h" */
41220
41221typedef struct PCache1 PCache1;
41222typedef struct PgHdr1 PgHdr1;
41223typedef struct PgFreeslot PgFreeslot;
41224typedef struct PGroup PGroup;
41225
41226/*
41227** Each cache entry is represented by an instance of the following
41228** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
41229** PgHdr1.pCache->szPage bytes is allocated directly before this structure
41230** in memory.
41231*/
41232struct PgHdr1 {
41233  sqlite3_pcache_page page;      /* Base class. Must be first. pBuf & pExtra */
41234  unsigned int iKey;             /* Key value (page number) */
41235  u8 isPinned;                   /* Page in use, not on the LRU list */
41236  u8 isBulkLocal;                /* This page from bulk local storage */
41237  u8 isAnchor;                   /* This is the PGroup.lru element */
41238  PgHdr1 *pNext;                 /* Next in hash table chain */
41239  PCache1 *pCache;               /* Cache that currently owns this page */
41240  PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
41241  PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
41242};
41243
41244/* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
41245** of one or more PCaches that are able to recycle each other's unpinned
41246** pages when they are under memory pressure.  A PGroup is an instance of
41247** the following object.
41248**
41249** This page cache implementation works in one of two modes:
41250**
41251**   (1)  Every PCache is the sole member of its own PGroup.  There is
41252**        one PGroup per PCache.
41253**
41254**   (2)  There is a single global PGroup that all PCaches are a member
41255**        of.
41256**
41257** Mode 1 uses more memory (since PCache instances are not able to rob
41258** unused pages from other PCaches) but it also operates without a mutex,
41259** and is therefore often faster.  Mode 2 requires a mutex in order to be
41260** threadsafe, but recycles pages more efficiently.
41261**
41262** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
41263** PGroup which is the pcache1.grp global variable and its mutex is
41264** SQLITE_MUTEX_STATIC_LRU.
41265*/
41266struct PGroup {
41267  sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
41268  unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
41269  unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
41270  unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
41271  unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
41272  PgHdr1 lru;                    /* The beginning and end of the LRU list */
41273};
41274
41275/* Each page cache is an instance of the following object.  Every
41276** open database file (including each in-memory database and each
41277** temporary or transient database) has a single page cache which
41278** is an instance of this object.
41279**
41280** Pointers to structures of this type are cast and returned as
41281** opaque sqlite3_pcache* handles.
41282*/
41283struct PCache1 {
41284  /* Cache configuration parameters. Page size (szPage) and the purgeable
41285  ** flag (bPurgeable) are set when the cache is created. nMax may be
41286  ** modified at any time by a call to the pcache1Cachesize() method.
41287  ** The PGroup mutex must be held when accessing nMax.
41288  */
41289  PGroup *pGroup;                     /* PGroup this cache belongs to */
41290  int szPage;                         /* Size of database content section */
41291  int szExtra;                        /* sizeof(MemPage)+sizeof(PgHdr) */
41292  int szAlloc;                        /* Total size of one pcache line */
41293  int bPurgeable;                     /* True if cache is purgeable */
41294  unsigned int nMin;                  /* Minimum number of pages reserved */
41295  unsigned int nMax;                  /* Configured "cache_size" value */
41296  unsigned int n90pct;                /* nMax*9/10 */
41297  unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
41298
41299  /* Hash table of all pages. The following variables may only be accessed
41300  ** when the accessor is holding the PGroup mutex.
41301  */
41302  unsigned int nRecyclable;           /* Number of pages in the LRU list */
41303  unsigned int nPage;                 /* Total number of pages in apHash */
41304  unsigned int nHash;                 /* Number of slots in apHash[] */
41305  PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
41306  PgHdr1 *pFree;                      /* List of unused pcache-local pages */
41307  void *pBulk;                        /* Bulk memory used by pcache-local */
41308};
41309
41310/*
41311** Free slots in the allocator used to divide up the global page cache
41312** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
41313*/
41314struct PgFreeslot {
41315  PgFreeslot *pNext;  /* Next free slot */
41316};
41317
41318/*
41319** Global data used by this cache.
41320*/
41321static SQLITE_WSD struct PCacheGlobal {
41322  PGroup grp;                    /* The global PGroup for mode (2) */
41323
41324  /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
41325  ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
41326  ** fixed at sqlite3_initialize() time and do not require mutex protection.
41327  ** The nFreeSlot and pFree values do require mutex protection.
41328  */
41329  int isInit;                    /* True if initialized */
41330  int separateCache;             /* Use a new PGroup for each PCache */
41331  int nInitPage;                 /* Initial bulk allocation size */
41332  int szSlot;                    /* Size of each free slot */
41333  int nSlot;                     /* The number of pcache slots */
41334  int nReserve;                  /* Try to keep nFreeSlot above this */
41335  void *pStart, *pEnd;           /* Bounds of global page cache memory */
41336  /* Above requires no mutex.  Use mutex below for variable that follow. */
41337  sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
41338  PgFreeslot *pFree;             /* Free page blocks */
41339  int nFreeSlot;                 /* Number of unused pcache slots */
41340  /* The following value requires a mutex to change.  We skip the mutex on
41341  ** reading because (1) most platforms read a 32-bit integer atomically and
41342  ** (2) even if an incorrect value is read, no great harm is done since this
41343  ** is really just an optimization. */
41344  int bUnderPressure;            /* True if low on PAGECACHE memory */
41345} pcache1_g;
41346
41347/*
41348** All code in this file should access the global structure above via the
41349** alias "pcache1". This ensures that the WSD emulation is used when
41350** compiling for systems that do not support real WSD.
41351*/
41352#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
41353
41354/*
41355** Macros to enter and leave the PCache LRU mutex.
41356*/
41357#if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
41358# define pcache1EnterMutex(X)  assert((X)->mutex==0)
41359# define pcache1LeaveMutex(X)  assert((X)->mutex==0)
41360# define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
41361#else
41362# define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
41363# define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
41364# define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
41365#endif
41366
41367/******************************************************************************/
41368/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
41369
41370
41371/*
41372** This function is called during initialization if a static buffer is
41373** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
41374** verb to sqlite3_config(). Parameter pBuf points to an allocation large
41375** enough to contain 'n' buffers of 'sz' bytes each.
41376**
41377** This routine is called from sqlite3_initialize() and so it is guaranteed
41378** to be serialized already.  There is no need for further mutexing.
41379*/
41380SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
41381  if( pcache1.isInit ){
41382    PgFreeslot *p;
41383    if( pBuf==0 ) sz = n = 0;
41384    sz = ROUNDDOWN8(sz);
41385    pcache1.szSlot = sz;
41386    pcache1.nSlot = pcache1.nFreeSlot = n;
41387    pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
41388    pcache1.pStart = pBuf;
41389    pcache1.pFree = 0;
41390    pcache1.bUnderPressure = 0;
41391    while( n-- ){
41392      p = (PgFreeslot*)pBuf;
41393      p->pNext = pcache1.pFree;
41394      pcache1.pFree = p;
41395      pBuf = (void*)&((char*)pBuf)[sz];
41396    }
41397    pcache1.pEnd = pBuf;
41398  }
41399}
41400
41401/*
41402** Try to initialize the pCache->pFree and pCache->pBulk fields.  Return
41403** true if pCache->pFree ends up containing one or more free pages.
41404*/
41405static int pcache1InitBulk(PCache1 *pCache){
41406  i64 szBulk;
41407  char *zBulk;
41408  if( pcache1.nInitPage==0 ) return 0;
41409  /* Do not bother with a bulk allocation if the cache size very small */
41410  if( pCache->nMax<3 ) return 0;
41411  sqlite3BeginBenignMalloc();
41412  if( pcache1.nInitPage>0 ){
41413    szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
41414  }else{
41415    szBulk = -1024 * (i64)pcache1.nInitPage;
41416  }
41417  if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
41418    szBulk = pCache->szAlloc*pCache->nMax;
41419  }
41420  zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
41421  sqlite3EndBenignMalloc();
41422  if( zBulk ){
41423    int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
41424    int i;
41425    for(i=0; i<nBulk; i++){
41426      PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
41427      pX->page.pBuf = zBulk;
41428      pX->page.pExtra = &pX[1];
41429      pX->isBulkLocal = 1;
41430      pX->isAnchor = 0;
41431      pX->pNext = pCache->pFree;
41432      pCache->pFree = pX;
41433      zBulk += pCache->szAlloc;
41434    }
41435  }
41436  return pCache->pFree!=0;
41437}
41438
41439/*
41440** Malloc function used within this file to allocate space from the buffer
41441** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
41442** such buffer exists or there is no space left in it, this function falls
41443** back to sqlite3Malloc().
41444**
41445** Multiple threads can run this routine at the same time.  Global variables
41446** in pcache1 need to be protected via mutex.
41447*/
41448static void *pcache1Alloc(int nByte){
41449  void *p = 0;
41450  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
41451  if( nByte<=pcache1.szSlot ){
41452    sqlite3_mutex_enter(pcache1.mutex);
41453    p = (PgHdr1 *)pcache1.pFree;
41454    if( p ){
41455      pcache1.pFree = pcache1.pFree->pNext;
41456      pcache1.nFreeSlot--;
41457      pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
41458      assert( pcache1.nFreeSlot>=0 );
41459      sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
41460      sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
41461    }
41462    sqlite3_mutex_leave(pcache1.mutex);
41463  }
41464  if( p==0 ){
41465    /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
41466    ** it from sqlite3Malloc instead.
41467    */
41468    p = sqlite3Malloc(nByte);
41469#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
41470    if( p ){
41471      int sz = sqlite3MallocSize(p);
41472      sqlite3_mutex_enter(pcache1.mutex);
41473      sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
41474      sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
41475      sqlite3_mutex_leave(pcache1.mutex);
41476    }
41477#endif
41478    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
41479  }
41480  return p;
41481}
41482
41483/*
41484** Free an allocated buffer obtained from pcache1Alloc().
41485*/
41486static void pcache1Free(void *p){
41487  int nFreed = 0;
41488  if( p==0 ) return;
41489  if( p>=pcache1.pStart && p<pcache1.pEnd ){
41490    PgFreeslot *pSlot;
41491    sqlite3_mutex_enter(pcache1.mutex);
41492    sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
41493    pSlot = (PgFreeslot*)p;
41494    pSlot->pNext = pcache1.pFree;
41495    pcache1.pFree = pSlot;
41496    pcache1.nFreeSlot++;
41497    pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
41498    assert( pcache1.nFreeSlot<=pcache1.nSlot );
41499    sqlite3_mutex_leave(pcache1.mutex);
41500  }else{
41501    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
41502    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
41503#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
41504    nFreed = sqlite3MallocSize(p);
41505    sqlite3_mutex_enter(pcache1.mutex);
41506    sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
41507    sqlite3_mutex_leave(pcache1.mutex);
41508#endif
41509    sqlite3_free(p);
41510  }
41511}
41512
41513#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
41514/*
41515** Return the size of a pcache allocation
41516*/
41517static int pcache1MemSize(void *p){
41518  if( p>=pcache1.pStart && p<pcache1.pEnd ){
41519    return pcache1.szSlot;
41520  }else{
41521    int iSize;
41522    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
41523    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
41524    iSize = sqlite3MallocSize(p);
41525    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
41526    return iSize;
41527  }
41528}
41529#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
41530
41531/*
41532** Allocate a new page object initially associated with cache pCache.
41533*/
41534static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
41535  PgHdr1 *p = 0;
41536  void *pPg;
41537
41538  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
41539  if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
41540    p = pCache->pFree;
41541    pCache->pFree = p->pNext;
41542    p->pNext = 0;
41543  }else{
41544#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
41545    /* The group mutex must be released before pcache1Alloc() is called. This
41546    ** is because it might call sqlite3_release_memory(), which assumes that
41547    ** this mutex is not held. */
41548    assert( pcache1.separateCache==0 );
41549    assert( pCache->pGroup==&pcache1.grp );
41550    pcache1LeaveMutex(pCache->pGroup);
41551#endif
41552    if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
41553#ifdef SQLITE_PCACHE_SEPARATE_HEADER
41554    pPg = pcache1Alloc(pCache->szPage);
41555    p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
41556    if( !pPg || !p ){
41557      pcache1Free(pPg);
41558      sqlite3_free(p);
41559      pPg = 0;
41560    }
41561#else
41562    pPg = pcache1Alloc(pCache->szAlloc);
41563    p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
41564#endif
41565    if( benignMalloc ){ sqlite3EndBenignMalloc(); }
41566#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
41567    pcache1EnterMutex(pCache->pGroup);
41568#endif
41569    if( pPg==0 ) return 0;
41570    p->page.pBuf = pPg;
41571    p->page.pExtra = &p[1];
41572    p->isBulkLocal = 0;
41573    p->isAnchor = 0;
41574  }
41575  if( pCache->bPurgeable ){
41576    pCache->pGroup->nCurrentPage++;
41577  }
41578  return p;
41579}
41580
41581/*
41582** Free a page object allocated by pcache1AllocPage().
41583*/
41584static void pcache1FreePage(PgHdr1 *p){
41585  PCache1 *pCache;
41586  assert( p!=0 );
41587  pCache = p->pCache;
41588  assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
41589  if( p->isBulkLocal ){
41590    p->pNext = pCache->pFree;
41591    pCache->pFree = p;
41592  }else{
41593    pcache1Free(p->page.pBuf);
41594#ifdef SQLITE_PCACHE_SEPARATE_HEADER
41595    sqlite3_free(p);
41596#endif
41597  }
41598  if( pCache->bPurgeable ){
41599    pCache->pGroup->nCurrentPage--;
41600  }
41601}
41602
41603/*
41604** Malloc function used by SQLite to obtain space from the buffer configured
41605** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
41606** exists, this function falls back to sqlite3Malloc().
41607*/
41608SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
41609  return pcache1Alloc(sz);
41610}
41611
41612/*
41613** Free an allocated buffer obtained from sqlite3PageMalloc().
41614*/
41615SQLITE_PRIVATE void sqlite3PageFree(void *p){
41616  pcache1Free(p);
41617}
41618
41619
41620/*
41621** Return true if it desirable to avoid allocating a new page cache
41622** entry.
41623**
41624** If memory was allocated specifically to the page cache using
41625** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
41626** it is desirable to avoid allocating a new page cache entry because
41627** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
41628** for all page cache needs and we should not need to spill the
41629** allocation onto the heap.
41630**
41631** Or, the heap is used for all page cache memory but the heap is
41632** under memory pressure, then again it is desirable to avoid
41633** allocating a new page cache entry in order to avoid stressing
41634** the heap even further.
41635*/
41636static int pcache1UnderMemoryPressure(PCache1 *pCache){
41637  if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
41638    return pcache1.bUnderPressure;
41639  }else{
41640    return sqlite3HeapNearlyFull();
41641  }
41642}
41643
41644/******************************************************************************/
41645/******** General Implementation Functions ************************************/
41646
41647/*
41648** This function is used to resize the hash table used by the cache passed
41649** as the first argument.
41650**
41651** The PCache mutex must be held when this function is called.
41652*/
41653static void pcache1ResizeHash(PCache1 *p){
41654  PgHdr1 **apNew;
41655  unsigned int nNew;
41656  unsigned int i;
41657
41658  assert( sqlite3_mutex_held(p->pGroup->mutex) );
41659
41660  nNew = p->nHash*2;
41661  if( nNew<256 ){
41662    nNew = 256;
41663  }
41664
41665  pcache1LeaveMutex(p->pGroup);
41666  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
41667  apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
41668  if( p->nHash ){ sqlite3EndBenignMalloc(); }
41669  pcache1EnterMutex(p->pGroup);
41670  if( apNew ){
41671    for(i=0; i<p->nHash; i++){
41672      PgHdr1 *pPage;
41673      PgHdr1 *pNext = p->apHash[i];
41674      while( (pPage = pNext)!=0 ){
41675        unsigned int h = pPage->iKey % nNew;
41676        pNext = pPage->pNext;
41677        pPage->pNext = apNew[h];
41678        apNew[h] = pPage;
41679      }
41680    }
41681    sqlite3_free(p->apHash);
41682    p->apHash = apNew;
41683    p->nHash = nNew;
41684  }
41685}
41686
41687/*
41688** This function is used internally to remove the page pPage from the
41689** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
41690** LRU list, then this function is a no-op.
41691**
41692** The PGroup mutex must be held when this function is called.
41693*/
41694static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
41695  PCache1 *pCache;
41696
41697  assert( pPage!=0 );
41698  assert( pPage->isPinned==0 );
41699  pCache = pPage->pCache;
41700  assert( pPage->pLruNext );
41701  assert( pPage->pLruPrev );
41702  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
41703  pPage->pLruPrev->pLruNext = pPage->pLruNext;
41704  pPage->pLruNext->pLruPrev = pPage->pLruPrev;
41705  pPage->pLruNext = 0;
41706  pPage->pLruPrev = 0;
41707  pPage->isPinned = 1;
41708  assert( pPage->isAnchor==0 );
41709  assert( pCache->pGroup->lru.isAnchor==1 );
41710  pCache->nRecyclable--;
41711  return pPage;
41712}
41713
41714
41715/*
41716** Remove the page supplied as an argument from the hash table
41717** (PCache1.apHash structure) that it is currently stored in.
41718** Also free the page if freePage is true.
41719**
41720** The PGroup mutex must be held when this function is called.
41721*/
41722static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
41723  unsigned int h;
41724  PCache1 *pCache = pPage->pCache;
41725  PgHdr1 **pp;
41726
41727  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
41728  h = pPage->iKey % pCache->nHash;
41729  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
41730  *pp = (*pp)->pNext;
41731
41732  pCache->nPage--;
41733  if( freeFlag ) pcache1FreePage(pPage);
41734}
41735
41736/*
41737** If there are currently more than nMaxPage pages allocated, try
41738** to recycle pages to reduce the number allocated to nMaxPage.
41739*/
41740static void pcache1EnforceMaxPage(PCache1 *pCache){
41741  PGroup *pGroup = pCache->pGroup;
41742  PgHdr1 *p;
41743  assert( sqlite3_mutex_held(pGroup->mutex) );
41744  while( pGroup->nCurrentPage>pGroup->nMaxPage
41745      && (p=pGroup->lru.pLruPrev)->isAnchor==0
41746  ){
41747    assert( p->pCache->pGroup==pGroup );
41748    assert( p->isPinned==0 );
41749    pcache1PinPage(p);
41750    pcache1RemoveFromHash(p, 1);
41751  }
41752  if( pCache->nPage==0 && pCache->pBulk ){
41753    sqlite3_free(pCache->pBulk);
41754    pCache->pBulk = pCache->pFree = 0;
41755  }
41756}
41757
41758/*
41759** Discard all pages from cache pCache with a page number (key value)
41760** greater than or equal to iLimit. Any pinned pages that meet this
41761** criteria are unpinned before they are discarded.
41762**
41763** The PCache mutex must be held when this function is called.
41764*/
41765static void pcache1TruncateUnsafe(
41766  PCache1 *pCache,             /* The cache to truncate */
41767  unsigned int iLimit          /* Drop pages with this pgno or larger */
41768){
41769  TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
41770  unsigned int h;
41771  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
41772  for(h=0; h<pCache->nHash; h++){
41773    PgHdr1 **pp = &pCache->apHash[h];
41774    PgHdr1 *pPage;
41775    while( (pPage = *pp)!=0 ){
41776      if( pPage->iKey>=iLimit ){
41777        pCache->nPage--;
41778        *pp = pPage->pNext;
41779        if( !pPage->isPinned ) pcache1PinPage(pPage);
41780        pcache1FreePage(pPage);
41781      }else{
41782        pp = &pPage->pNext;
41783        TESTONLY( nPage++; )
41784      }
41785    }
41786  }
41787  assert( pCache->nPage==nPage );
41788}
41789
41790/******************************************************************************/
41791/******** sqlite3_pcache Methods **********************************************/
41792
41793/*
41794** Implementation of the sqlite3_pcache.xInit method.
41795*/
41796static int pcache1Init(void *NotUsed){
41797  UNUSED_PARAMETER(NotUsed);
41798  assert( pcache1.isInit==0 );
41799  memset(&pcache1, 0, sizeof(pcache1));
41800
41801
41802  /*
41803  ** The pcache1.separateCache variable is true if each PCache has its own
41804  ** private PGroup (mode-1).  pcache1.separateCache is false if the single
41805  ** PGroup in pcache1.grp is used for all page caches (mode-2).
41806  **
41807  **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
41808  **
41809  **   *  Use a unified cache in single-threaded applications that have
41810  **      configured a start-time buffer for use as page-cache memory using
41811  **      sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
41812  **      pBuf argument.
41813  **
41814  **   *  Otherwise use separate caches (mode-1)
41815  */
41816#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
41817  pcache1.separateCache = 0;
41818#elif SQLITE_THREADSAFE
41819  pcache1.separateCache = sqlite3GlobalConfig.pPage==0
41820                          || sqlite3GlobalConfig.bCoreMutex>0;
41821#else
41822  pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
41823#endif
41824
41825#if SQLITE_THREADSAFE
41826  if( sqlite3GlobalConfig.bCoreMutex ){
41827    pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
41828    pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
41829  }
41830#endif
41831  if( pcache1.separateCache
41832   && sqlite3GlobalConfig.nPage!=0
41833   && sqlite3GlobalConfig.pPage==0
41834  ){
41835    pcache1.nInitPage = sqlite3GlobalConfig.nPage;
41836  }else{
41837    pcache1.nInitPage = 0;
41838  }
41839  pcache1.grp.mxPinned = 10;
41840  pcache1.isInit = 1;
41841  return SQLITE_OK;
41842}
41843
41844/*
41845** Implementation of the sqlite3_pcache.xShutdown method.
41846** Note that the static mutex allocated in xInit does
41847** not need to be freed.
41848*/
41849static void pcache1Shutdown(void *NotUsed){
41850  UNUSED_PARAMETER(NotUsed);
41851  assert( pcache1.isInit!=0 );
41852  memset(&pcache1, 0, sizeof(pcache1));
41853}
41854
41855/* forward declaration */
41856static void pcache1Destroy(sqlite3_pcache *p);
41857
41858/*
41859** Implementation of the sqlite3_pcache.xCreate method.
41860**
41861** Allocate a new cache.
41862*/
41863static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
41864  PCache1 *pCache;      /* The newly created page cache */
41865  PGroup *pGroup;       /* The group the new page cache will belong to */
41866  int sz;               /* Bytes of memory required to allocate the new cache */
41867
41868  assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
41869  assert( szExtra < 300 );
41870
41871  sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
41872  pCache = (PCache1 *)sqlite3MallocZero(sz);
41873  if( pCache ){
41874    if( pcache1.separateCache ){
41875      pGroup = (PGroup*)&pCache[1];
41876      pGroup->mxPinned = 10;
41877    }else{
41878      pGroup = &pcache1.grp;
41879    }
41880    if( pGroup->lru.isAnchor==0 ){
41881      pGroup->lru.isAnchor = 1;
41882      pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
41883    }
41884    pCache->pGroup = pGroup;
41885    pCache->szPage = szPage;
41886    pCache->szExtra = szExtra;
41887    pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
41888    pCache->bPurgeable = (bPurgeable ? 1 : 0);
41889    pcache1EnterMutex(pGroup);
41890    pcache1ResizeHash(pCache);
41891    if( bPurgeable ){
41892      pCache->nMin = 10;
41893      pGroup->nMinPage += pCache->nMin;
41894      pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
41895    }
41896    pcache1LeaveMutex(pGroup);
41897    if( pCache->nHash==0 ){
41898      pcache1Destroy((sqlite3_pcache*)pCache);
41899      pCache = 0;
41900    }
41901  }
41902  return (sqlite3_pcache *)pCache;
41903}
41904
41905/*
41906** Implementation of the sqlite3_pcache.xCachesize method.
41907**
41908** Configure the cache_size limit for a cache.
41909*/
41910static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
41911  PCache1 *pCache = (PCache1 *)p;
41912  if( pCache->bPurgeable ){
41913    PGroup *pGroup = pCache->pGroup;
41914    pcache1EnterMutex(pGroup);
41915    pGroup->nMaxPage += (nMax - pCache->nMax);
41916    pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
41917    pCache->nMax = nMax;
41918    pCache->n90pct = pCache->nMax*9/10;
41919    pcache1EnforceMaxPage(pCache);
41920    pcache1LeaveMutex(pGroup);
41921  }
41922}
41923
41924/*
41925** Implementation of the sqlite3_pcache.xShrink method.
41926**
41927** Free up as much memory as possible.
41928*/
41929static void pcache1Shrink(sqlite3_pcache *p){
41930  PCache1 *pCache = (PCache1*)p;
41931  if( pCache->bPurgeable ){
41932    PGroup *pGroup = pCache->pGroup;
41933    int savedMaxPage;
41934    pcache1EnterMutex(pGroup);
41935    savedMaxPage = pGroup->nMaxPage;
41936    pGroup->nMaxPage = 0;
41937    pcache1EnforceMaxPage(pCache);
41938    pGroup->nMaxPage = savedMaxPage;
41939    pcache1LeaveMutex(pGroup);
41940  }
41941}
41942
41943/*
41944** Implementation of the sqlite3_pcache.xPagecount method.
41945*/
41946static int pcache1Pagecount(sqlite3_pcache *p){
41947  int n;
41948  PCache1 *pCache = (PCache1*)p;
41949  pcache1EnterMutex(pCache->pGroup);
41950  n = pCache->nPage;
41951  pcache1LeaveMutex(pCache->pGroup);
41952  return n;
41953}
41954
41955
41956/*
41957** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
41958** in the header of the pcache1Fetch() procedure.
41959**
41960** This steps are broken out into a separate procedure because they are
41961** usually not needed, and by avoiding the stack initialization required
41962** for these steps, the main pcache1Fetch() procedure can run faster.
41963*/
41964static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
41965  PCache1 *pCache,
41966  unsigned int iKey,
41967  int createFlag
41968){
41969  unsigned int nPinned;
41970  PGroup *pGroup = pCache->pGroup;
41971  PgHdr1 *pPage = 0;
41972
41973  /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
41974  assert( pCache->nPage >= pCache->nRecyclable );
41975  nPinned = pCache->nPage - pCache->nRecyclable;
41976  assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
41977  assert( pCache->n90pct == pCache->nMax*9/10 );
41978  if( createFlag==1 && (
41979        nPinned>=pGroup->mxPinned
41980     || nPinned>=pCache->n90pct
41981     || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
41982  )){
41983    return 0;
41984  }
41985
41986  if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
41987  assert( pCache->nHash>0 && pCache->apHash );
41988
41989  /* Step 4. Try to recycle a page. */
41990  if( pCache->bPurgeable
41991   && !pGroup->lru.pLruPrev->isAnchor
41992   && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
41993  ){
41994    PCache1 *pOther;
41995    pPage = pGroup->lru.pLruPrev;
41996    assert( pPage->isPinned==0 );
41997    pcache1RemoveFromHash(pPage, 0);
41998    pcache1PinPage(pPage);
41999    pOther = pPage->pCache;
42000    if( pOther->szAlloc != pCache->szAlloc ){
42001      pcache1FreePage(pPage);
42002      pPage = 0;
42003    }else{
42004      pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
42005    }
42006  }
42007
42008  /* Step 5. If a usable page buffer has still not been found,
42009  ** attempt to allocate a new one.
42010  */
42011  if( !pPage ){
42012    pPage = pcache1AllocPage(pCache, createFlag==1);
42013  }
42014
42015  if( pPage ){
42016    unsigned int h = iKey % pCache->nHash;
42017    pCache->nPage++;
42018    pPage->iKey = iKey;
42019    pPage->pNext = pCache->apHash[h];
42020    pPage->pCache = pCache;
42021    pPage->pLruPrev = 0;
42022    pPage->pLruNext = 0;
42023    pPage->isPinned = 1;
42024    *(void **)pPage->page.pExtra = 0;
42025    pCache->apHash[h] = pPage;
42026    if( iKey>pCache->iMaxKey ){
42027      pCache->iMaxKey = iKey;
42028    }
42029  }
42030  return pPage;
42031}
42032
42033/*
42034** Implementation of the sqlite3_pcache.xFetch method.
42035**
42036** Fetch a page by key value.
42037**
42038** Whether or not a new page may be allocated by this function depends on
42039** the value of the createFlag argument.  0 means do not allocate a new
42040** page.  1 means allocate a new page if space is easily available.  2
42041** means to try really hard to allocate a new page.
42042**
42043** For a non-purgeable cache (a cache used as the storage for an in-memory
42044** database) there is really no difference between createFlag 1 and 2.  So
42045** the calling function (pcache.c) will never have a createFlag of 1 on
42046** a non-purgeable cache.
42047**
42048** There are three different approaches to obtaining space for a page,
42049** depending on the value of parameter createFlag (which may be 0, 1 or 2).
42050**
42051**   1. Regardless of the value of createFlag, the cache is searched for a
42052**      copy of the requested page. If one is found, it is returned.
42053**
42054**   2. If createFlag==0 and the page is not already in the cache, NULL is
42055**      returned.
42056**
42057**   3. If createFlag is 1, and the page is not already in the cache, then
42058**      return NULL (do not allocate a new page) if any of the following
42059**      conditions are true:
42060**
42061**       (a) the number of pages pinned by the cache is greater than
42062**           PCache1.nMax, or
42063**
42064**       (b) the number of pages pinned by the cache is greater than
42065**           the sum of nMax for all purgeable caches, less the sum of
42066**           nMin for all other purgeable caches, or
42067**
42068**   4. If none of the first three conditions apply and the cache is marked
42069**      as purgeable, and if one of the following is true:
42070**
42071**       (a) The number of pages allocated for the cache is already
42072**           PCache1.nMax, or
42073**
42074**       (b) The number of pages allocated for all purgeable caches is
42075**           already equal to or greater than the sum of nMax for all
42076**           purgeable caches,
42077**
42078**       (c) The system is under memory pressure and wants to avoid
42079**           unnecessary pages cache entry allocations
42080**
42081**      then attempt to recycle a page from the LRU list. If it is the right
42082**      size, return the recycled buffer. Otherwise, free the buffer and
42083**      proceed to step 5.
42084**
42085**   5. Otherwise, allocate and return a new page buffer.
42086**
42087** There are two versions of this routine.  pcache1FetchWithMutex() is
42088** the general case.  pcache1FetchNoMutex() is a faster implementation for
42089** the common case where pGroup->mutex is NULL.  The pcache1Fetch() wrapper
42090** invokes the appropriate routine.
42091*/
42092static PgHdr1 *pcache1FetchNoMutex(
42093  sqlite3_pcache *p,
42094  unsigned int iKey,
42095  int createFlag
42096){
42097  PCache1 *pCache = (PCache1 *)p;
42098  PgHdr1 *pPage = 0;
42099
42100  /* Step 1: Search the hash table for an existing entry. */
42101  pPage = pCache->apHash[iKey % pCache->nHash];
42102  while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
42103
42104  /* Step 2: If the page was found in the hash table, then return it.
42105  ** If the page was not in the hash table and createFlag is 0, abort.
42106  ** Otherwise (page not in hash and createFlag!=0) continue with
42107  ** subsequent steps to try to create the page. */
42108  if( pPage ){
42109    if( !pPage->isPinned ){
42110      return pcache1PinPage(pPage);
42111    }else{
42112      return pPage;
42113    }
42114  }else if( createFlag ){
42115    /* Steps 3, 4, and 5 implemented by this subroutine */
42116    return pcache1FetchStage2(pCache, iKey, createFlag);
42117  }else{
42118    return 0;
42119  }
42120}
42121#if PCACHE1_MIGHT_USE_GROUP_MUTEX
42122static PgHdr1 *pcache1FetchWithMutex(
42123  sqlite3_pcache *p,
42124  unsigned int iKey,
42125  int createFlag
42126){
42127  PCache1 *pCache = (PCache1 *)p;
42128  PgHdr1 *pPage;
42129
42130  pcache1EnterMutex(pCache->pGroup);
42131  pPage = pcache1FetchNoMutex(p, iKey, createFlag);
42132  assert( pPage==0 || pCache->iMaxKey>=iKey );
42133  pcache1LeaveMutex(pCache->pGroup);
42134  return pPage;
42135}
42136#endif
42137static sqlite3_pcache_page *pcache1Fetch(
42138  sqlite3_pcache *p,
42139  unsigned int iKey,
42140  int createFlag
42141){
42142#if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
42143  PCache1 *pCache = (PCache1 *)p;
42144#endif
42145
42146  assert( offsetof(PgHdr1,page)==0 );
42147  assert( pCache->bPurgeable || createFlag!=1 );
42148  assert( pCache->bPurgeable || pCache->nMin==0 );
42149  assert( pCache->bPurgeable==0 || pCache->nMin==10 );
42150  assert( pCache->nMin==0 || pCache->bPurgeable );
42151  assert( pCache->nHash>0 );
42152#if PCACHE1_MIGHT_USE_GROUP_MUTEX
42153  if( pCache->pGroup->mutex ){
42154    return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
42155  }else
42156#endif
42157  {
42158    return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
42159  }
42160}
42161
42162
42163/*
42164** Implementation of the sqlite3_pcache.xUnpin method.
42165**
42166** Mark a page as unpinned (eligible for asynchronous recycling).
42167*/
42168static void pcache1Unpin(
42169  sqlite3_pcache *p,
42170  sqlite3_pcache_page *pPg,
42171  int reuseUnlikely
42172){
42173  PCache1 *pCache = (PCache1 *)p;
42174  PgHdr1 *pPage = (PgHdr1 *)pPg;
42175  PGroup *pGroup = pCache->pGroup;
42176
42177  assert( pPage->pCache==pCache );
42178  pcache1EnterMutex(pGroup);
42179
42180  /* It is an error to call this function if the page is already
42181  ** part of the PGroup LRU list.
42182  */
42183  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
42184  assert( pPage->isPinned==1 );
42185
42186  if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
42187    pcache1RemoveFromHash(pPage, 1);
42188  }else{
42189    /* Add the page to the PGroup LRU list. */
42190    PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
42191    pPage->pLruPrev = &pGroup->lru;
42192    (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
42193    *ppFirst = pPage;
42194    pCache->nRecyclable++;
42195    pPage->isPinned = 0;
42196  }
42197
42198  pcache1LeaveMutex(pCache->pGroup);
42199}
42200
42201/*
42202** Implementation of the sqlite3_pcache.xRekey method.
42203*/
42204static void pcache1Rekey(
42205  sqlite3_pcache *p,
42206  sqlite3_pcache_page *pPg,
42207  unsigned int iOld,
42208  unsigned int iNew
42209){
42210  PCache1 *pCache = (PCache1 *)p;
42211  PgHdr1 *pPage = (PgHdr1 *)pPg;
42212  PgHdr1 **pp;
42213  unsigned int h;
42214  assert( pPage->iKey==iOld );
42215  assert( pPage->pCache==pCache );
42216
42217  pcache1EnterMutex(pCache->pGroup);
42218
42219  h = iOld%pCache->nHash;
42220  pp = &pCache->apHash[h];
42221  while( (*pp)!=pPage ){
42222    pp = &(*pp)->pNext;
42223  }
42224  *pp = pPage->pNext;
42225
42226  h = iNew%pCache->nHash;
42227  pPage->iKey = iNew;
42228  pPage->pNext = pCache->apHash[h];
42229  pCache->apHash[h] = pPage;
42230  if( iNew>pCache->iMaxKey ){
42231    pCache->iMaxKey = iNew;
42232  }
42233
42234  pcache1LeaveMutex(pCache->pGroup);
42235}
42236
42237/*
42238** Implementation of the sqlite3_pcache.xTruncate method.
42239**
42240** Discard all unpinned pages in the cache with a page number equal to
42241** or greater than parameter iLimit. Any pinned pages with a page number
42242** equal to or greater than iLimit are implicitly unpinned.
42243*/
42244static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
42245  PCache1 *pCache = (PCache1 *)p;
42246  pcache1EnterMutex(pCache->pGroup);
42247  if( iLimit<=pCache->iMaxKey ){
42248    pcache1TruncateUnsafe(pCache, iLimit);
42249    pCache->iMaxKey = iLimit-1;
42250  }
42251  pcache1LeaveMutex(pCache->pGroup);
42252}
42253
42254/*
42255** Implementation of the sqlite3_pcache.xDestroy method.
42256**
42257** Destroy a cache allocated using pcache1Create().
42258*/
42259static void pcache1Destroy(sqlite3_pcache *p){
42260  PCache1 *pCache = (PCache1 *)p;
42261  PGroup *pGroup = pCache->pGroup;
42262  assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
42263  pcache1EnterMutex(pGroup);
42264  pcache1TruncateUnsafe(pCache, 0);
42265  assert( pGroup->nMaxPage >= pCache->nMax );
42266  pGroup->nMaxPage -= pCache->nMax;
42267  assert( pGroup->nMinPage >= pCache->nMin );
42268  pGroup->nMinPage -= pCache->nMin;
42269  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
42270  pcache1EnforceMaxPage(pCache);
42271  pcache1LeaveMutex(pGroup);
42272  sqlite3_free(pCache->pBulk);
42273  sqlite3_free(pCache->apHash);
42274  sqlite3_free(pCache);
42275}
42276
42277/*
42278** This function is called during initialization (sqlite3_initialize()) to
42279** install the default pluggable cache module, assuming the user has not
42280** already provided an alternative.
42281*/
42282SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
42283  static const sqlite3_pcache_methods2 defaultMethods = {
42284    1,                       /* iVersion */
42285    0,                       /* pArg */
42286    pcache1Init,             /* xInit */
42287    pcache1Shutdown,         /* xShutdown */
42288    pcache1Create,           /* xCreate */
42289    pcache1Cachesize,        /* xCachesize */
42290    pcache1Pagecount,        /* xPagecount */
42291    pcache1Fetch,            /* xFetch */
42292    pcache1Unpin,            /* xUnpin */
42293    pcache1Rekey,            /* xRekey */
42294    pcache1Truncate,         /* xTruncate */
42295    pcache1Destroy,          /* xDestroy */
42296    pcache1Shrink            /* xShrink */
42297  };
42298  sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
42299}
42300
42301/*
42302** Return the size of the header on each page of this PCACHE implementation.
42303*/
42304SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
42305
42306/*
42307** Return the global mutex used by this PCACHE implementation.  The
42308** sqlite3_status() routine needs access to this mutex.
42309*/
42310SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
42311  return pcache1.mutex;
42312}
42313
42314#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
42315/*
42316** This function is called to free superfluous dynamically allocated memory
42317** held by the pager system. Memory in use by any SQLite pager allocated
42318** by the current thread may be sqlite3_free()ed.
42319**
42320** nReq is the number of bytes of memory required. Once this much has
42321** been released, the function returns. The return value is the total number
42322** of bytes of memory released.
42323*/
42324SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
42325  int nFree = 0;
42326  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
42327  assert( sqlite3_mutex_notheld(pcache1.mutex) );
42328  if( sqlite3GlobalConfig.nPage==0 ){
42329    PgHdr1 *p;
42330    pcache1EnterMutex(&pcache1.grp);
42331    while( (nReq<0 || nFree<nReq)
42332       &&  (p=pcache1.grp.lru.pLruPrev)!=0
42333       &&  p->isAnchor==0
42334    ){
42335      nFree += pcache1MemSize(p->page.pBuf);
42336#ifdef SQLITE_PCACHE_SEPARATE_HEADER
42337      nFree += sqlite3MemSize(p);
42338#endif
42339      assert( p->isPinned==0 );
42340      pcache1PinPage(p);
42341      pcache1RemoveFromHash(p, 1);
42342    }
42343    pcache1LeaveMutex(&pcache1.grp);
42344  }
42345  return nFree;
42346}
42347#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
42348
42349#ifdef SQLITE_TEST
42350/*
42351** This function is used by test procedures to inspect the internal state
42352** of the global cache.
42353*/
42354SQLITE_PRIVATE void sqlite3PcacheStats(
42355  int *pnCurrent,      /* OUT: Total number of pages cached */
42356  int *pnMax,          /* OUT: Global maximum cache size */
42357  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
42358  int *pnRecyclable    /* OUT: Total number of pages available for recycling */
42359){
42360  PgHdr1 *p;
42361  int nRecyclable = 0;
42362  for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
42363    assert( p->isPinned==0 );
42364    nRecyclable++;
42365  }
42366  *pnCurrent = pcache1.grp.nCurrentPage;
42367  *pnMax = (int)pcache1.grp.nMaxPage;
42368  *pnMin = (int)pcache1.grp.nMinPage;
42369  *pnRecyclable = nRecyclable;
42370}
42371#endif
42372
42373/************** End of pcache1.c *********************************************/
42374/************** Begin file rowset.c ******************************************/
42375/*
42376** 2008 December 3
42377**
42378** The author disclaims copyright to this source code.  In place of
42379** a legal notice, here is a blessing:
42380**
42381**    May you do good and not evil.
42382**    May you find forgiveness for yourself and forgive others.
42383**    May you share freely, never taking more than you give.
42384**
42385*************************************************************************
42386**
42387** This module implements an object we call a "RowSet".
42388**
42389** The RowSet object is a collection of rowids.  Rowids
42390** are inserted into the RowSet in an arbitrary order.  Inserts
42391** can be intermixed with tests to see if a given rowid has been
42392** previously inserted into the RowSet.
42393**
42394** After all inserts are finished, it is possible to extract the
42395** elements of the RowSet in sorted order.  Once this extraction
42396** process has started, no new elements may be inserted.
42397**
42398** Hence, the primitive operations for a RowSet are:
42399**
42400**    CREATE
42401**    INSERT
42402**    TEST
42403**    SMALLEST
42404**    DESTROY
42405**
42406** The CREATE and DESTROY primitives are the constructor and destructor,
42407** obviously.  The INSERT primitive adds a new element to the RowSet.
42408** TEST checks to see if an element is already in the RowSet.  SMALLEST
42409** extracts the least value from the RowSet.
42410**
42411** The INSERT primitive might allocate additional memory.  Memory is
42412** allocated in chunks so most INSERTs do no allocation.  There is an
42413** upper bound on the size of allocated memory.  No memory is freed
42414** until DESTROY.
42415**
42416** The TEST primitive includes a "batch" number.  The TEST primitive
42417** will only see elements that were inserted before the last change
42418** in the batch number.  In other words, if an INSERT occurs between
42419** two TESTs where the TESTs have the same batch nubmer, then the
42420** value added by the INSERT will not be visible to the second TEST.
42421** The initial batch number is zero, so if the very first TEST contains
42422** a non-zero batch number, it will see all prior INSERTs.
42423**
42424** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
42425** that is attempted.
42426**
42427** The cost of an INSERT is roughly constant.  (Sometimes new memory
42428** has to be allocated on an INSERT.)  The cost of a TEST with a new
42429** batch number is O(NlogN) where N is the number of elements in the RowSet.
42430** The cost of a TEST using the same batch number is O(logN).  The cost
42431** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
42432** primitives are constant time.  The cost of DESTROY is O(N).
42433**
42434** There is an added cost of O(N) when switching between TEST and
42435** SMALLEST primitives.
42436*/
42437/* #include "sqliteInt.h" */
42438
42439
42440/*
42441** Target size for allocation chunks.
42442*/
42443#define ROWSET_ALLOCATION_SIZE 1024
42444
42445/*
42446** The number of rowset entries per allocation chunk.
42447*/
42448#define ROWSET_ENTRY_PER_CHUNK  \
42449                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
42450
42451/*
42452** Each entry in a RowSet is an instance of the following object.
42453**
42454** This same object is reused to store a linked list of trees of RowSetEntry
42455** objects.  In that alternative use, pRight points to the next entry
42456** in the list, pLeft points to the tree, and v is unused.  The
42457** RowSet.pForest value points to the head of this forest list.
42458*/
42459struct RowSetEntry {
42460  i64 v;                        /* ROWID value for this entry */
42461  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
42462  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
42463};
42464
42465/*
42466** RowSetEntry objects are allocated in large chunks (instances of the
42467** following structure) to reduce memory allocation overhead.  The
42468** chunks are kept on a linked list so that they can be deallocated
42469** when the RowSet is destroyed.
42470*/
42471struct RowSetChunk {
42472  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
42473  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
42474};
42475
42476/*
42477** A RowSet in an instance of the following structure.
42478**
42479** A typedef of this structure if found in sqliteInt.h.
42480*/
42481struct RowSet {
42482  struct RowSetChunk *pChunk;    /* List of all chunk allocations */
42483  sqlite3 *db;                   /* The database connection */
42484  struct RowSetEntry *pEntry;    /* List of entries using pRight */
42485  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
42486  struct RowSetEntry *pFresh;    /* Source of new entry objects */
42487  struct RowSetEntry *pForest;   /* List of binary trees of entries */
42488  u16 nFresh;                    /* Number of objects on pFresh */
42489  u16 rsFlags;                   /* Various flags */
42490  int iBatch;                    /* Current insert batch */
42491};
42492
42493/*
42494** Allowed values for RowSet.rsFlags
42495*/
42496#define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
42497#define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
42498
42499/*
42500** Turn bulk memory into a RowSet object.  N bytes of memory
42501** are available at pSpace.  The db pointer is used as a memory context
42502** for any subsequent allocations that need to occur.
42503** Return a pointer to the new RowSet object.
42504**
42505** It must be the case that N is sufficient to make a Rowset.  If not
42506** an assertion fault occurs.
42507**
42508** If N is larger than the minimum, use the surplus as an initial
42509** allocation of entries available to be filled.
42510*/
42511SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
42512  RowSet *p;
42513  assert( N >= ROUND8(sizeof(*p)) );
42514  p = pSpace;
42515  p->pChunk = 0;
42516  p->db = db;
42517  p->pEntry = 0;
42518  p->pLast = 0;
42519  p->pForest = 0;
42520  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
42521  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
42522  p->rsFlags = ROWSET_SORTED;
42523  p->iBatch = 0;
42524  return p;
42525}
42526
42527/*
42528** Deallocate all chunks from a RowSet.  This frees all memory that
42529** the RowSet has allocated over its lifetime.  This routine is
42530** the destructor for the RowSet.
42531*/
42532SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
42533  struct RowSetChunk *pChunk, *pNextChunk;
42534  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
42535    pNextChunk = pChunk->pNextChunk;
42536    sqlite3DbFree(p->db, pChunk);
42537  }
42538  p->pChunk = 0;
42539  p->nFresh = 0;
42540  p->pEntry = 0;
42541  p->pLast = 0;
42542  p->pForest = 0;
42543  p->rsFlags = ROWSET_SORTED;
42544}
42545
42546/*
42547** Allocate a new RowSetEntry object that is associated with the
42548** given RowSet.  Return a pointer to the new and completely uninitialized
42549** objected.
42550**
42551** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
42552** routine returns NULL.
42553*/
42554static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
42555  assert( p!=0 );
42556  if( p->nFresh==0 ){
42557    struct RowSetChunk *pNew;
42558    pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
42559    if( pNew==0 ){
42560      return 0;
42561    }
42562    pNew->pNextChunk = p->pChunk;
42563    p->pChunk = pNew;
42564    p->pFresh = pNew->aEntry;
42565    p->nFresh = ROWSET_ENTRY_PER_CHUNK;
42566  }
42567  p->nFresh--;
42568  return p->pFresh++;
42569}
42570
42571/*
42572** Insert a new value into a RowSet.
42573**
42574** The mallocFailed flag of the database connection is set if a
42575** memory allocation fails.
42576*/
42577SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
42578  struct RowSetEntry *pEntry;  /* The new entry */
42579  struct RowSetEntry *pLast;   /* The last prior entry */
42580
42581  /* This routine is never called after sqlite3RowSetNext() */
42582  assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
42583
42584  pEntry = rowSetEntryAlloc(p);
42585  if( pEntry==0 ) return;
42586  pEntry->v = rowid;
42587  pEntry->pRight = 0;
42588  pLast = p->pLast;
42589  if( pLast ){
42590    if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
42591      p->rsFlags &= ~ROWSET_SORTED;
42592    }
42593    pLast->pRight = pEntry;
42594  }else{
42595    p->pEntry = pEntry;
42596  }
42597  p->pLast = pEntry;
42598}
42599
42600/*
42601** Merge two lists of RowSetEntry objects.  Remove duplicates.
42602**
42603** The input lists are connected via pRight pointers and are
42604** assumed to each already be in sorted order.
42605*/
42606static struct RowSetEntry *rowSetEntryMerge(
42607  struct RowSetEntry *pA,    /* First sorted list to be merged */
42608  struct RowSetEntry *pB     /* Second sorted list to be merged */
42609){
42610  struct RowSetEntry head;
42611  struct RowSetEntry *pTail;
42612
42613  pTail = &head;
42614  while( pA && pB ){
42615    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
42616    assert( pB->pRight==0 || pB->v<=pB->pRight->v );
42617    if( pA->v<pB->v ){
42618      pTail->pRight = pA;
42619      pA = pA->pRight;
42620      pTail = pTail->pRight;
42621    }else if( pB->v<pA->v ){
42622      pTail->pRight = pB;
42623      pB = pB->pRight;
42624      pTail = pTail->pRight;
42625    }else{
42626      pA = pA->pRight;
42627    }
42628  }
42629  if( pA ){
42630    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
42631    pTail->pRight = pA;
42632  }else{
42633    assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
42634    pTail->pRight = pB;
42635  }
42636  return head.pRight;
42637}
42638
42639/*
42640** Sort all elements on the list of RowSetEntry objects into order of
42641** increasing v.
42642*/
42643static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
42644  unsigned int i;
42645  struct RowSetEntry *pNext, *aBucket[40];
42646
42647  memset(aBucket, 0, sizeof(aBucket));
42648  while( pIn ){
42649    pNext = pIn->pRight;
42650    pIn->pRight = 0;
42651    for(i=0; aBucket[i]; i++){
42652      pIn = rowSetEntryMerge(aBucket[i], pIn);
42653      aBucket[i] = 0;
42654    }
42655    aBucket[i] = pIn;
42656    pIn = pNext;
42657  }
42658  pIn = 0;
42659  for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
42660    pIn = rowSetEntryMerge(pIn, aBucket[i]);
42661  }
42662  return pIn;
42663}
42664
42665
42666/*
42667** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
42668** Convert this tree into a linked list connected by the pRight pointers
42669** and return pointers to the first and last elements of the new list.
42670*/
42671static void rowSetTreeToList(
42672  struct RowSetEntry *pIn,         /* Root of the input tree */
42673  struct RowSetEntry **ppFirst,    /* Write head of the output list here */
42674  struct RowSetEntry **ppLast      /* Write tail of the output list here */
42675){
42676  assert( pIn!=0 );
42677  if( pIn->pLeft ){
42678    struct RowSetEntry *p;
42679    rowSetTreeToList(pIn->pLeft, ppFirst, &p);
42680    p->pRight = pIn;
42681  }else{
42682    *ppFirst = pIn;
42683  }
42684  if( pIn->pRight ){
42685    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
42686  }else{
42687    *ppLast = pIn;
42688  }
42689  assert( (*ppLast)->pRight==0 );
42690}
42691
42692
42693/*
42694** Convert a sorted list of elements (connected by pRight) into a binary
42695** tree with depth of iDepth.  A depth of 1 means the tree contains a single
42696** node taken from the head of *ppList.  A depth of 2 means a tree with
42697** three nodes.  And so forth.
42698**
42699** Use as many entries from the input list as required and update the
42700** *ppList to point to the unused elements of the list.  If the input
42701** list contains too few elements, then construct an incomplete tree
42702** and leave *ppList set to NULL.
42703**
42704** Return a pointer to the root of the constructed binary tree.
42705*/
42706static struct RowSetEntry *rowSetNDeepTree(
42707  struct RowSetEntry **ppList,
42708  int iDepth
42709){
42710  struct RowSetEntry *p;         /* Root of the new tree */
42711  struct RowSetEntry *pLeft;     /* Left subtree */
42712  if( *ppList==0 ){
42713    return 0;
42714  }
42715  if( iDepth==1 ){
42716    p = *ppList;
42717    *ppList = p->pRight;
42718    p->pLeft = p->pRight = 0;
42719    return p;
42720  }
42721  pLeft = rowSetNDeepTree(ppList, iDepth-1);
42722  p = *ppList;
42723  if( p==0 ){
42724    return pLeft;
42725  }
42726  p->pLeft = pLeft;
42727  *ppList = p->pRight;
42728  p->pRight = rowSetNDeepTree(ppList, iDepth-1);
42729  return p;
42730}
42731
42732/*
42733** Convert a sorted list of elements into a binary tree. Make the tree
42734** as deep as it needs to be in order to contain the entire list.
42735*/
42736static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
42737  int iDepth;           /* Depth of the tree so far */
42738  struct RowSetEntry *p;       /* Current tree root */
42739  struct RowSetEntry *pLeft;   /* Left subtree */
42740
42741  assert( pList!=0 );
42742  p = pList;
42743  pList = p->pRight;
42744  p->pLeft = p->pRight = 0;
42745  for(iDepth=1; pList; iDepth++){
42746    pLeft = p;
42747    p = pList;
42748    pList = p->pRight;
42749    p->pLeft = pLeft;
42750    p->pRight = rowSetNDeepTree(&pList, iDepth);
42751  }
42752  return p;
42753}
42754
42755/*
42756** Take all the entries on p->pEntry and on the trees in p->pForest and
42757** sort them all together into one big ordered list on p->pEntry.
42758**
42759** This routine should only be called once in the life of a RowSet.
42760*/
42761static void rowSetToList(RowSet *p){
42762
42763  /* This routine is called only once */
42764  assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
42765
42766  if( (p->rsFlags & ROWSET_SORTED)==0 ){
42767    p->pEntry = rowSetEntrySort(p->pEntry);
42768  }
42769
42770  /* While this module could theoretically support it, sqlite3RowSetNext()
42771  ** is never called after sqlite3RowSetText() for the same RowSet.  So
42772  ** there is never a forest to deal with.  Should this change, simply
42773  ** remove the assert() and the #if 0. */
42774  assert( p->pForest==0 );
42775#if 0
42776  while( p->pForest ){
42777    struct RowSetEntry *pTree = p->pForest->pLeft;
42778    if( pTree ){
42779      struct RowSetEntry *pHead, *pTail;
42780      rowSetTreeToList(pTree, &pHead, &pTail);
42781      p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
42782    }
42783    p->pForest = p->pForest->pRight;
42784  }
42785#endif
42786  p->rsFlags |= ROWSET_NEXT;  /* Verify this routine is never called again */
42787}
42788
42789/*
42790** Extract the smallest element from the RowSet.
42791** Write the element into *pRowid.  Return 1 on success.  Return
42792** 0 if the RowSet is already empty.
42793**
42794** After this routine has been called, the sqlite3RowSetInsert()
42795** routine may not be called again.
42796*/
42797SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
42798  assert( p!=0 );
42799
42800  /* Merge the forest into a single sorted list on first call */
42801  if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
42802
42803  /* Return the next entry on the list */
42804  if( p->pEntry ){
42805    *pRowid = p->pEntry->v;
42806    p->pEntry = p->pEntry->pRight;
42807    if( p->pEntry==0 ){
42808      sqlite3RowSetClear(p);
42809    }
42810    return 1;
42811  }else{
42812    return 0;
42813  }
42814}
42815
42816/*
42817** Check to see if element iRowid was inserted into the rowset as
42818** part of any insert batch prior to iBatch.  Return 1 or 0.
42819**
42820** If this is the first test of a new batch and if there exist entries
42821** on pRowSet->pEntry, then sort those entries into the forest at
42822** pRowSet->pForest so that they can be tested.
42823*/
42824SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
42825  struct RowSetEntry *p, *pTree;
42826
42827  /* This routine is never called after sqlite3RowSetNext() */
42828  assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
42829
42830  /* Sort entries into the forest on the first test of a new batch
42831  */
42832  if( iBatch!=pRowSet->iBatch ){
42833    p = pRowSet->pEntry;
42834    if( p ){
42835      struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
42836      if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
42837        p = rowSetEntrySort(p);
42838      }
42839      for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
42840        ppPrevTree = &pTree->pRight;
42841        if( pTree->pLeft==0 ){
42842          pTree->pLeft = rowSetListToTree(p);
42843          break;
42844        }else{
42845          struct RowSetEntry *pAux, *pTail;
42846          rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
42847          pTree->pLeft = 0;
42848          p = rowSetEntryMerge(pAux, p);
42849        }
42850      }
42851      if( pTree==0 ){
42852        *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
42853        if( pTree ){
42854          pTree->v = 0;
42855          pTree->pRight = 0;
42856          pTree->pLeft = rowSetListToTree(p);
42857        }
42858      }
42859      pRowSet->pEntry = 0;
42860      pRowSet->pLast = 0;
42861      pRowSet->rsFlags |= ROWSET_SORTED;
42862    }
42863    pRowSet->iBatch = iBatch;
42864  }
42865
42866  /* Test to see if the iRowid value appears anywhere in the forest.
42867  ** Return 1 if it does and 0 if not.
42868  */
42869  for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
42870    p = pTree->pLeft;
42871    while( p ){
42872      if( p->v<iRowid ){
42873        p = p->pRight;
42874      }else if( p->v>iRowid ){
42875        p = p->pLeft;
42876      }else{
42877        return 1;
42878      }
42879    }
42880  }
42881  return 0;
42882}
42883
42884/************** End of rowset.c **********************************************/
42885/************** Begin file pager.c *******************************************/
42886/*
42887** 2001 September 15
42888**
42889** The author disclaims copyright to this source code.  In place of
42890** a legal notice, here is a blessing:
42891**
42892**    May you do good and not evil.
42893**    May you find forgiveness for yourself and forgive others.
42894**    May you share freely, never taking more than you give.
42895**
42896*************************************************************************
42897** This is the implementation of the page cache subsystem or "pager".
42898**
42899** The pager is used to access a database disk file.  It implements
42900** atomic commit and rollback through the use of a journal file that
42901** is separate from the database file.  The pager also implements file
42902** locking to prevent two processes from writing the same database
42903** file simultaneously, or one process from reading the database while
42904** another is writing.
42905*/
42906#ifndef SQLITE_OMIT_DISKIO
42907/* #include "sqliteInt.h" */
42908/************** Include wal.h in the middle of pager.c ***********************/
42909/************** Begin file wal.h *********************************************/
42910/*
42911** 2010 February 1
42912**
42913** The author disclaims copyright to this source code.  In place of
42914** a legal notice, here is a blessing:
42915**
42916**    May you do good and not evil.
42917**    May you find forgiveness for yourself and forgive others.
42918**    May you share freely, never taking more than you give.
42919**
42920*************************************************************************
42921** This header file defines the interface to the write-ahead logging
42922** system. Refer to the comments below and the header comment attached to
42923** the implementation of each function in log.c for further details.
42924*/
42925
42926#ifndef _WAL_H_
42927#define _WAL_H_
42928
42929/* #include "sqliteInt.h" */
42930
42931/* Additional values that can be added to the sync_flags argument of
42932** sqlite3WalFrames():
42933*/
42934#define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
42935#define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
42936
42937#ifdef SQLITE_OMIT_WAL
42938# define sqlite3WalOpen(x,y,z)                   0
42939# define sqlite3WalLimit(x,y)
42940# define sqlite3WalClose(w,x,y,z)                0
42941# define sqlite3WalBeginReadTransaction(y,z)     0
42942# define sqlite3WalEndReadTransaction(z)
42943# define sqlite3WalDbsize(y)                     0
42944# define sqlite3WalBeginWriteTransaction(y)      0
42945# define sqlite3WalEndWriteTransaction(x)        0
42946# define sqlite3WalUndo(x,y,z)                   0
42947# define sqlite3WalSavepoint(y,z)
42948# define sqlite3WalSavepointUndo(y,z)            0
42949# define sqlite3WalFrames(u,v,w,x,y,z)           0
42950# define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
42951# define sqlite3WalCallback(z)                   0
42952# define sqlite3WalExclusiveMode(y,z)            0
42953# define sqlite3WalHeapMemory(z)                 0
42954# define sqlite3WalFramesize(z)                  0
42955# define sqlite3WalFindFrame(x,y,z)              0
42956#else
42957
42958#define WAL_SAVEPOINT_NDATA 4
42959
42960/* Connection to a write-ahead log (WAL) file.
42961** There is one object of this type for each pager.
42962*/
42963typedef struct Wal Wal;
42964
42965/* Open and close a connection to a write-ahead log. */
42966SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
42967SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
42968
42969/* Set the limiting size of a WAL file. */
42970SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
42971
42972/* Used by readers to open (lock) and close (unlock) a snapshot.  A
42973** snapshot is like a read-transaction.  It is the state of the database
42974** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
42975** preserves the current state even if the other threads or processes
42976** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
42977** transaction and releases the lock.
42978*/
42979SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
42980SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
42981
42982/* Read a page from the write-ahead log, if it is present. */
42983SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
42984SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
42985
42986/* If the WAL is not empty, return the size of the database. */
42987SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
42988
42989/* Obtain or release the WRITER lock. */
42990SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
42991SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
42992
42993/* Undo any frames written (but not committed) to the log */
42994SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
42995
42996/* Return an integer that records the current (uncommitted) write
42997** position in the WAL */
42998SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
42999
43000/* Move the write position of the WAL back to iFrame.  Called in
43001** response to a ROLLBACK TO command. */
43002SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
43003
43004/* Write a frame or frames to the log. */
43005SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
43006
43007/* Copy pages from the log to the database file */
43008SQLITE_PRIVATE int sqlite3WalCheckpoint(
43009  Wal *pWal,                      /* Write-ahead log connection */
43010  int eMode,                      /* One of PASSIVE, FULL and RESTART */
43011  int (*xBusy)(void*),            /* Function to call when busy */
43012  void *pBusyArg,                 /* Context argument for xBusyHandler */
43013  int sync_flags,                 /* Flags to sync db file with (or 0) */
43014  int nBuf,                       /* Size of buffer nBuf */
43015  u8 *zBuf,                       /* Temporary buffer to use */
43016  int *pnLog,                     /* OUT: Number of frames in WAL */
43017  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
43018);
43019
43020/* Return the value to pass to a sqlite3_wal_hook callback, the
43021** number of frames in the WAL at the point of the last commit since
43022** sqlite3WalCallback() was called.  If no commits have occurred since
43023** the last call, then return 0.
43024*/
43025SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
43026
43027/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
43028** by the pager layer on the database file.
43029*/
43030SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
43031
43032/* Return true if the argument is non-NULL and the WAL module is using
43033** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
43034** WAL module is using shared-memory, return false.
43035*/
43036SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
43037
43038#ifdef SQLITE_ENABLE_ZIPVFS
43039/* If the WAL file is not empty, return the number of bytes of content
43040** stored in each frame (i.e. the db page-size when the WAL was created).
43041*/
43042SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
43043#endif
43044
43045#endif /* ifndef SQLITE_OMIT_WAL */
43046#endif /* _WAL_H_ */
43047
43048/************** End of wal.h *************************************************/
43049/************** Continuing where we left off in pager.c **********************/
43050
43051
43052/******************* NOTES ON THE DESIGN OF THE PAGER ************************
43053**
43054** This comment block describes invariants that hold when using a rollback
43055** journal.  These invariants do not apply for journal_mode=WAL,
43056** journal_mode=MEMORY, or journal_mode=OFF.
43057**
43058** Within this comment block, a page is deemed to have been synced
43059** automatically as soon as it is written when PRAGMA synchronous=OFF.
43060** Otherwise, the page is not synced until the xSync method of the VFS
43061** is called successfully on the file containing the page.
43062**
43063** Definition:  A page of the database file is said to be "overwriteable" if
43064** one or more of the following are true about the page:
43065**
43066**     (a)  The original content of the page as it was at the beginning of
43067**          the transaction has been written into the rollback journal and
43068**          synced.
43069**
43070**     (b)  The page was a freelist leaf page at the start of the transaction.
43071**
43072**     (c)  The page number is greater than the largest page that existed in
43073**          the database file at the start of the transaction.
43074**
43075** (1) A page of the database file is never overwritten unless one of the
43076**     following are true:
43077**
43078**     (a) The page and all other pages on the same sector are overwriteable.
43079**
43080**     (b) The atomic page write optimization is enabled, and the entire
43081**         transaction other than the update of the transaction sequence
43082**         number consists of a single page change.
43083**
43084** (2) The content of a page written into the rollback journal exactly matches
43085**     both the content in the database when the rollback journal was written
43086**     and the content in the database at the beginning of the current
43087**     transaction.
43088**
43089** (3) Writes to the database file are an integer multiple of the page size
43090**     in length and are aligned on a page boundary.
43091**
43092** (4) Reads from the database file are either aligned on a page boundary and
43093**     an integer multiple of the page size in length or are taken from the
43094**     first 100 bytes of the database file.
43095**
43096** (5) All writes to the database file are synced prior to the rollback journal
43097**     being deleted, truncated, or zeroed.
43098**
43099** (6) If a master journal file is used, then all writes to the database file
43100**     are synced prior to the master journal being deleted.
43101**
43102** Definition: Two databases (or the same database at two points it time)
43103** are said to be "logically equivalent" if they give the same answer to
43104** all queries.  Note in particular the content of freelist leaf
43105** pages can be changed arbitrarily without affecting the logical equivalence
43106** of the database.
43107**
43108** (7) At any time, if any subset, including the empty set and the total set,
43109**     of the unsynced changes to a rollback journal are removed and the
43110**     journal is rolled back, the resulting database file will be logically
43111**     equivalent to the database file at the beginning of the transaction.
43112**
43113** (8) When a transaction is rolled back, the xTruncate method of the VFS
43114**     is called to restore the database file to the same size it was at
43115**     the beginning of the transaction.  (In some VFSes, the xTruncate
43116**     method is a no-op, but that does not change the fact the SQLite will
43117**     invoke it.)
43118**
43119** (9) Whenever the database file is modified, at least one bit in the range
43120**     of bytes from 24 through 39 inclusive will be changed prior to releasing
43121**     the EXCLUSIVE lock, thus signaling other connections on the same
43122**     database to flush their caches.
43123**
43124** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
43125**      than one billion transactions.
43126**
43127** (11) A database file is well-formed at the beginning and at the conclusion
43128**      of every transaction.
43129**
43130** (12) An EXCLUSIVE lock is held on the database file when writing to
43131**      the database file.
43132**
43133** (13) A SHARED lock is held on the database file while reading any
43134**      content out of the database file.
43135**
43136******************************************************************************/
43137
43138/*
43139** Macros for troubleshooting.  Normally turned off
43140*/
43141#if 0
43142int sqlite3PagerTrace=1;  /* True to enable tracing */
43143#define sqlite3DebugPrintf printf
43144#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
43145#else
43146#define PAGERTRACE(X)
43147#endif
43148
43149/*
43150** The following two macros are used within the PAGERTRACE() macros above
43151** to print out file-descriptors.
43152**
43153** PAGERID() takes a pointer to a Pager struct as its argument. The
43154** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
43155** struct as its argument.
43156*/
43157#define PAGERID(p) ((int)(p->fd))
43158#define FILEHANDLEID(fd) ((int)fd)
43159
43160/*
43161** The Pager.eState variable stores the current 'state' of a pager. A
43162** pager may be in any one of the seven states shown in the following
43163** state diagram.
43164**
43165**                            OPEN <------+------+
43166**                              |         |      |
43167**                              V         |      |
43168**               +---------> READER-------+      |
43169**               |              |                |
43170**               |              V                |
43171**               |<-------WRITER_LOCKED------> ERROR
43172**               |              |                ^
43173**               |              V                |
43174**               |<------WRITER_CACHEMOD-------->|
43175**               |              |                |
43176**               |              V                |
43177**               |<-------WRITER_DBMOD---------->|
43178**               |              |                |
43179**               |              V                |
43180**               +<------WRITER_FINISHED-------->+
43181**
43182**
43183** List of state transitions and the C [function] that performs each:
43184**
43185**   OPEN              -> READER              [sqlite3PagerSharedLock]
43186**   READER            -> OPEN                [pager_unlock]
43187**
43188**   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
43189**   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
43190**   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
43191**   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
43192**   WRITER_***        -> READER              [pager_end_transaction]
43193**
43194**   WRITER_***        -> ERROR               [pager_error]
43195**   ERROR             -> OPEN                [pager_unlock]
43196**
43197**
43198**  OPEN:
43199**
43200**    The pager starts up in this state. Nothing is guaranteed in this
43201**    state - the file may or may not be locked and the database size is
43202**    unknown. The database may not be read or written.
43203**
43204**    * No read or write transaction is active.
43205**    * Any lock, or no lock at all, may be held on the database file.
43206**    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
43207**
43208**  READER:
43209**
43210**    In this state all the requirements for reading the database in
43211**    rollback (non-WAL) mode are met. Unless the pager is (or recently
43212**    was) in exclusive-locking mode, a user-level read transaction is
43213**    open. The database size is known in this state.
43214**
43215**    A connection running with locking_mode=normal enters this state when
43216**    it opens a read-transaction on the database and returns to state
43217**    OPEN after the read-transaction is completed. However a connection
43218**    running in locking_mode=exclusive (including temp databases) remains in
43219**    this state even after the read-transaction is closed. The only way
43220**    a locking_mode=exclusive connection can transition from READER to OPEN
43221**    is via the ERROR state (see below).
43222**
43223**    * A read transaction may be active (but a write-transaction cannot).
43224**    * A SHARED or greater lock is held on the database file.
43225**    * The dbSize variable may be trusted (even if a user-level read
43226**      transaction is not active). The dbOrigSize and dbFileSize variables
43227**      may not be trusted at this point.
43228**    * If the database is a WAL database, then the WAL connection is open.
43229**    * Even if a read-transaction is not open, it is guaranteed that
43230**      there is no hot-journal in the file-system.
43231**
43232**  WRITER_LOCKED:
43233**
43234**    The pager moves to this state from READER when a write-transaction
43235**    is first opened on the database. In WRITER_LOCKED state, all locks
43236**    required to start a write-transaction are held, but no actual
43237**    modifications to the cache or database have taken place.
43238**
43239**    In rollback mode, a RESERVED or (if the transaction was opened with
43240**    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
43241**    moving to this state, but the journal file is not written to or opened
43242**    to in this state. If the transaction is committed or rolled back while
43243**    in WRITER_LOCKED state, all that is required is to unlock the database
43244**    file.
43245**
43246**    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
43247**    If the connection is running with locking_mode=exclusive, an attempt
43248**    is made to obtain an EXCLUSIVE lock on the database file.
43249**
43250**    * A write transaction is active.
43251**    * If the connection is open in rollback-mode, a RESERVED or greater
43252**      lock is held on the database file.
43253**    * If the connection is open in WAL-mode, a WAL write transaction
43254**      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
43255**      called).
43256**    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
43257**    * The contents of the pager cache have not been modified.
43258**    * The journal file may or may not be open.
43259**    * Nothing (not even the first header) has been written to the journal.
43260**
43261**  WRITER_CACHEMOD:
43262**
43263**    A pager moves from WRITER_LOCKED state to this state when a page is
43264**    first modified by the upper layer. In rollback mode the journal file
43265**    is opened (if it is not already open) and a header written to the
43266**    start of it. The database file on disk has not been modified.
43267**
43268**    * A write transaction is active.
43269**    * A RESERVED or greater lock is held on the database file.
43270**    * The journal file is open and the first header has been written
43271**      to it, but the header has not been synced to disk.
43272**    * The contents of the page cache have been modified.
43273**
43274**  WRITER_DBMOD:
43275**
43276**    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
43277**    when it modifies the contents of the database file. WAL connections
43278**    never enter this state (since they do not modify the database file,
43279**    just the log file).
43280**
43281**    * A write transaction is active.
43282**    * An EXCLUSIVE or greater lock is held on the database file.
43283**    * The journal file is open and the first header has been written
43284**      and synced to disk.
43285**    * The contents of the page cache have been modified (and possibly
43286**      written to disk).
43287**
43288**  WRITER_FINISHED:
43289**
43290**    It is not possible for a WAL connection to enter this state.
43291**
43292**    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
43293**    state after the entire transaction has been successfully written into the
43294**    database file. In this state the transaction may be committed simply
43295**    by finalizing the journal file. Once in WRITER_FINISHED state, it is
43296**    not possible to modify the database further. At this point, the upper
43297**    layer must either commit or rollback the transaction.
43298**
43299**    * A write transaction is active.
43300**    * An EXCLUSIVE or greater lock is held on the database file.
43301**    * All writing and syncing of journal and database data has finished.
43302**      If no error occurred, all that remains is to finalize the journal to
43303**      commit the transaction. If an error did occur, the caller will need
43304**      to rollback the transaction.
43305**
43306**  ERROR:
43307**
43308**    The ERROR state is entered when an IO or disk-full error (including
43309**    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
43310**    difficult to be sure that the in-memory pager state (cache contents,
43311**    db size etc.) are consistent with the contents of the file-system.
43312**
43313**    Temporary pager files may enter the ERROR state, but in-memory pagers
43314**    cannot.
43315**
43316**    For example, if an IO error occurs while performing a rollback,
43317**    the contents of the page-cache may be left in an inconsistent state.
43318**    At this point it would be dangerous to change back to READER state
43319**    (as usually happens after a rollback). Any subsequent readers might
43320**    report database corruption (due to the inconsistent cache), and if
43321**    they upgrade to writers, they may inadvertently corrupt the database
43322**    file. To avoid this hazard, the pager switches into the ERROR state
43323**    instead of READER following such an error.
43324**
43325**    Once it has entered the ERROR state, any attempt to use the pager
43326**    to read or write data returns an error. Eventually, once all
43327**    outstanding transactions have been abandoned, the pager is able to
43328**    transition back to OPEN state, discarding the contents of the
43329**    page-cache and any other in-memory state at the same time. Everything
43330**    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
43331**    when a read-transaction is next opened on the pager (transitioning
43332**    the pager into READER state). At that point the system has recovered
43333**    from the error.
43334**
43335**    Specifically, the pager jumps into the ERROR state if:
43336**
43337**      1. An error occurs while attempting a rollback. This happens in
43338**         function sqlite3PagerRollback().
43339**
43340**      2. An error occurs while attempting to finalize a journal file
43341**         following a commit in function sqlite3PagerCommitPhaseTwo().
43342**
43343**      3. An error occurs while attempting to write to the journal or
43344**         database file in function pagerStress() in order to free up
43345**         memory.
43346**
43347**    In other cases, the error is returned to the b-tree layer. The b-tree
43348**    layer then attempts a rollback operation. If the error condition
43349**    persists, the pager enters the ERROR state via condition (1) above.
43350**
43351**    Condition (3) is necessary because it can be triggered by a read-only
43352**    statement executed within a transaction. In this case, if the error
43353**    code were simply returned to the user, the b-tree layer would not
43354**    automatically attempt a rollback, as it assumes that an error in a
43355**    read-only statement cannot leave the pager in an internally inconsistent
43356**    state.
43357**
43358**    * The Pager.errCode variable is set to something other than SQLITE_OK.
43359**    * There are one or more outstanding references to pages (after the
43360**      last reference is dropped the pager should move back to OPEN state).
43361**    * The pager is not an in-memory pager.
43362**
43363**
43364** Notes:
43365**
43366**   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
43367**     connection is open in WAL mode. A WAL connection is always in one
43368**     of the first four states.
43369**
43370**   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
43371**     state. There are two exceptions: immediately after exclusive-mode has
43372**     been turned on (and before any read or write transactions are
43373**     executed), and when the pager is leaving the "error state".
43374**
43375**   * See also: assert_pager_state().
43376*/
43377#define PAGER_OPEN                  0
43378#define PAGER_READER                1
43379#define PAGER_WRITER_LOCKED         2
43380#define PAGER_WRITER_CACHEMOD       3
43381#define PAGER_WRITER_DBMOD          4
43382#define PAGER_WRITER_FINISHED       5
43383#define PAGER_ERROR                 6
43384
43385/*
43386** The Pager.eLock variable is almost always set to one of the
43387** following locking-states, according to the lock currently held on
43388** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
43389** This variable is kept up to date as locks are taken and released by
43390** the pagerLockDb() and pagerUnlockDb() wrappers.
43391**
43392** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
43393** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
43394** the operation was successful. In these circumstances pagerLockDb() and
43395** pagerUnlockDb() take a conservative approach - eLock is always updated
43396** when unlocking the file, and only updated when locking the file if the
43397** VFS call is successful. This way, the Pager.eLock variable may be set
43398** to a less exclusive (lower) value than the lock that is actually held
43399** at the system level, but it is never set to a more exclusive value.
43400**
43401** This is usually safe. If an xUnlock fails or appears to fail, there may
43402** be a few redundant xLock() calls or a lock may be held for longer than
43403** required, but nothing really goes wrong.
43404**
43405** The exception is when the database file is unlocked as the pager moves
43406** from ERROR to OPEN state. At this point there may be a hot-journal file
43407** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
43408** transition, by the same pager or any other). If the call to xUnlock()
43409** fails at this point and the pager is left holding an EXCLUSIVE lock, this
43410** can confuse the call to xCheckReservedLock() call made later as part
43411** of hot-journal detection.
43412**
43413** xCheckReservedLock() is defined as returning true "if there is a RESERVED
43414** lock held by this process or any others". So xCheckReservedLock may
43415** return true because the caller itself is holding an EXCLUSIVE lock (but
43416** doesn't know it because of a previous error in xUnlock). If this happens
43417** a hot-journal may be mistaken for a journal being created by an active
43418** transaction in another process, causing SQLite to read from the database
43419** without rolling it back.
43420**
43421** To work around this, if a call to xUnlock() fails when unlocking the
43422** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
43423** is only changed back to a real locking state after a successful call
43424** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
43425** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
43426** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
43427** lock on the database file before attempting to roll it back. See function
43428** PagerSharedLock() for more detail.
43429**
43430** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
43431** PAGER_OPEN state.
43432*/
43433#define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
43434
43435/*
43436** A macro used for invoking the codec if there is one
43437*/
43438#ifdef SQLITE_HAS_CODEC
43439# define CODEC1(P,D,N,X,E) \
43440    if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
43441# define CODEC2(P,D,N,X,E,O) \
43442    if( P->xCodec==0 ){ O=(char*)D; }else \
43443    if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
43444#else
43445# define CODEC1(P,D,N,X,E)   /* NO-OP */
43446# define CODEC2(P,D,N,X,E,O) O=(char*)D
43447#endif
43448
43449/*
43450** The maximum allowed sector size. 64KiB. If the xSectorsize() method
43451** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
43452** This could conceivably cause corruption following a power failure on
43453** such a system. This is currently an undocumented limit.
43454*/
43455#define MAX_SECTOR_SIZE 0x10000
43456
43457/*
43458** An instance of the following structure is allocated for each active
43459** savepoint and statement transaction in the system. All such structures
43460** are stored in the Pager.aSavepoint[] array, which is allocated and
43461** resized using sqlite3Realloc().
43462**
43463** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
43464** set to 0. If a journal-header is written into the main journal while
43465** the savepoint is active, then iHdrOffset is set to the byte offset
43466** immediately following the last journal record written into the main
43467** journal before the journal-header. This is required during savepoint
43468** rollback (see pagerPlaybackSavepoint()).
43469*/
43470typedef struct PagerSavepoint PagerSavepoint;
43471struct PagerSavepoint {
43472  i64 iOffset;                 /* Starting offset in main journal */
43473  i64 iHdrOffset;              /* See above */
43474  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
43475  Pgno nOrig;                  /* Original number of pages in file */
43476  Pgno iSubRec;                /* Index of first record in sub-journal */
43477#ifndef SQLITE_OMIT_WAL
43478  u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
43479#endif
43480};
43481
43482/*
43483** Bits of the Pager.doNotSpill flag.  See further description below.
43484*/
43485#define SPILLFLAG_OFF         0x01 /* Never spill cache.  Set via pragma */
43486#define SPILLFLAG_ROLLBACK    0x02 /* Current rolling back, so do not spill */
43487#define SPILLFLAG_NOSYNC      0x04 /* Spill is ok, but do not sync */
43488
43489/*
43490** An open page cache is an instance of struct Pager. A description of
43491** some of the more important member variables follows:
43492**
43493** eState
43494**
43495**   The current 'state' of the pager object. See the comment and state
43496**   diagram above for a description of the pager state.
43497**
43498** eLock
43499**
43500**   For a real on-disk database, the current lock held on the database file -
43501**   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
43502**
43503**   For a temporary or in-memory database (neither of which require any
43504**   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
43505**   databases always have Pager.exclusiveMode==1, this tricks the pager
43506**   logic into thinking that it already has all the locks it will ever
43507**   need (and no reason to release them).
43508**
43509**   In some (obscure) circumstances, this variable may also be set to
43510**   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
43511**   details.
43512**
43513** changeCountDone
43514**
43515**   This boolean variable is used to make sure that the change-counter
43516**   (the 4-byte header field at byte offset 24 of the database file) is
43517**   not updated more often than necessary.
43518**
43519**   It is set to true when the change-counter field is updated, which
43520**   can only happen if an exclusive lock is held on the database file.
43521**   It is cleared (set to false) whenever an exclusive lock is
43522**   relinquished on the database file. Each time a transaction is committed,
43523**   The changeCountDone flag is inspected. If it is true, the work of
43524**   updating the change-counter is omitted for the current transaction.
43525**
43526**   This mechanism means that when running in exclusive mode, a connection
43527**   need only update the change-counter once, for the first transaction
43528**   committed.
43529**
43530** setMaster
43531**
43532**   When PagerCommitPhaseOne() is called to commit a transaction, it may
43533**   (or may not) specify a master-journal name to be written into the
43534**   journal file before it is synced to disk.
43535**
43536**   Whether or not a journal file contains a master-journal pointer affects
43537**   the way in which the journal file is finalized after the transaction is
43538**   committed or rolled back when running in "journal_mode=PERSIST" mode.
43539**   If a journal file does not contain a master-journal pointer, it is
43540**   finalized by overwriting the first journal header with zeroes. If
43541**   it does contain a master-journal pointer the journal file is finalized
43542**   by truncating it to zero bytes, just as if the connection were
43543**   running in "journal_mode=truncate" mode.
43544**
43545**   Journal files that contain master journal pointers cannot be finalized
43546**   simply by overwriting the first journal-header with zeroes, as the
43547**   master journal pointer could interfere with hot-journal rollback of any
43548**   subsequently interrupted transaction that reuses the journal file.
43549**
43550**   The flag is cleared as soon as the journal file is finalized (either
43551**   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
43552**   journal file from being successfully finalized, the setMaster flag
43553**   is cleared anyway (and the pager will move to ERROR state).
43554**
43555** doNotSpill
43556**
43557**   This variables control the behavior of cache-spills  (calls made by
43558**   the pcache module to the pagerStress() routine to write cached data
43559**   to the file-system in order to free up memory).
43560**
43561**   When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
43562**   writing to the database from pagerStress() is disabled altogether.
43563**   The SPILLFLAG_ROLLBACK case is done in a very obscure case that
43564**   comes up during savepoint rollback that requires the pcache module
43565**   to allocate a new page to prevent the journal file from being written
43566**   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF
43567**   case is a user preference.
43568**
43569**   If the SPILLFLAG_NOSYNC bit is set, writing to the database from
43570**   pagerStress() is permitted, but syncing the journal file is not.
43571**   This flag is set by sqlite3PagerWrite() when the file-system sector-size
43572**   is larger than the database page-size in order to prevent a journal sync
43573**   from happening in between the journalling of two pages on the same sector.
43574**
43575** subjInMemory
43576**
43577**   This is a boolean variable. If true, then any required sub-journal
43578**   is opened as an in-memory journal file. If false, then in-memory
43579**   sub-journals are only used for in-memory pager files.
43580**
43581**   This variable is updated by the upper layer each time a new
43582**   write-transaction is opened.
43583**
43584** dbSize, dbOrigSize, dbFileSize
43585**
43586**   Variable dbSize is set to the number of pages in the database file.
43587**   It is valid in PAGER_READER and higher states (all states except for
43588**   OPEN and ERROR).
43589**
43590**   dbSize is set based on the size of the database file, which may be
43591**   larger than the size of the database (the value stored at offset
43592**   28 of the database header by the btree). If the size of the file
43593**   is not an integer multiple of the page-size, the value stored in
43594**   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
43595**   Except, any file that is greater than 0 bytes in size is considered
43596**   to have at least one page. (i.e. a 1KB file with 2K page-size leads
43597**   to dbSize==1).
43598**
43599**   During a write-transaction, if pages with page-numbers greater than
43600**   dbSize are modified in the cache, dbSize is updated accordingly.
43601**   Similarly, if the database is truncated using PagerTruncateImage(),
43602**   dbSize is updated.
43603**
43604**   Variables dbOrigSize and dbFileSize are valid in states
43605**   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
43606**   variable at the start of the transaction. It is used during rollback,
43607**   and to determine whether or not pages need to be journalled before
43608**   being modified.
43609**
43610**   Throughout a write-transaction, dbFileSize contains the size of
43611**   the file on disk in pages. It is set to a copy of dbSize when the
43612**   write-transaction is first opened, and updated when VFS calls are made
43613**   to write or truncate the database file on disk.
43614**
43615**   The only reason the dbFileSize variable is required is to suppress
43616**   unnecessary calls to xTruncate() after committing a transaction. If,
43617**   when a transaction is committed, the dbFileSize variable indicates
43618**   that the database file is larger than the database image (Pager.dbSize),
43619**   pager_truncate() is called. The pager_truncate() call uses xFilesize()
43620**   to measure the database file on disk, and then truncates it if required.
43621**   dbFileSize is not used when rolling back a transaction. In this case
43622**   pager_truncate() is called unconditionally (which means there may be
43623**   a call to xFilesize() that is not strictly required). In either case,
43624**   pager_truncate() may cause the file to become smaller or larger.
43625**
43626** dbHintSize
43627**
43628**   The dbHintSize variable is used to limit the number of calls made to
43629**   the VFS xFileControl(FCNTL_SIZE_HINT) method.
43630**
43631**   dbHintSize is set to a copy of the dbSize variable when a
43632**   write-transaction is opened (at the same time as dbFileSize and
43633**   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
43634**   dbHintSize is increased to the number of pages that correspond to the
43635**   size-hint passed to the method call. See pager_write_pagelist() for
43636**   details.
43637**
43638** errCode
43639**
43640**   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
43641**   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
43642**   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
43643**   sub-codes.
43644*/
43645struct Pager {
43646  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
43647  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
43648  u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
43649  u8 useJournal;              /* Use a rollback journal on this file */
43650  u8 noSync;                  /* Do not sync the journal if true */
43651  u8 fullSync;                /* Do extra syncs of the journal for robustness */
43652  u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
43653  u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
43654  u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
43655  u8 tempFile;                /* zFilename is a temporary or immutable file */
43656  u8 noLock;                  /* Do not lock (except in WAL mode) */
43657  u8 readOnly;                /* True for a read-only database */
43658  u8 memDb;                   /* True to inhibit all file I/O */
43659
43660  /**************************************************************************
43661  ** The following block contains those class members that change during
43662  ** routine operation.  Class members not in this block are either fixed
43663  ** when the pager is first created or else only change when there is a
43664  ** significant mode change (such as changing the page_size, locking_mode,
43665  ** or the journal_mode).  From another view, these class members describe
43666  ** the "state" of the pager, while other class members describe the
43667  ** "configuration" of the pager.
43668  */
43669  u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
43670  u8 eLock;                   /* Current lock held on database file */
43671  u8 changeCountDone;         /* Set after incrementing the change-counter */
43672  u8 setMaster;               /* True if a m-j name has been written to jrnl */
43673  u8 doNotSpill;              /* Do not spill the cache when non-zero */
43674  u8 subjInMemory;            /* True to use in-memory sub-journals */
43675  u8 bUseFetch;               /* True to use xFetch() */
43676  u8 hasHeldSharedLock;       /* True if a shared lock has ever been held */
43677  Pgno dbSize;                /* Number of pages in the database */
43678  Pgno dbOrigSize;            /* dbSize before the current transaction */
43679  Pgno dbFileSize;            /* Number of pages in the database file */
43680  Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
43681  int errCode;                /* One of several kinds of errors */
43682  int nRec;                   /* Pages journalled since last j-header written */
43683  u32 cksumInit;              /* Quasi-random value added to every checksum */
43684  u32 nSubRec;                /* Number of records written to sub-journal */
43685  Bitvec *pInJournal;         /* One bit for each page in the database file */
43686  sqlite3_file *fd;           /* File descriptor for database */
43687  sqlite3_file *jfd;          /* File descriptor for main journal */
43688  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
43689  i64 journalOff;             /* Current write offset in the journal file */
43690  i64 journalHdr;             /* Byte offset to previous journal header */
43691  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
43692  PagerSavepoint *aSavepoint; /* Array of active savepoints */
43693  int nSavepoint;             /* Number of elements in aSavepoint[] */
43694  u32 iDataVersion;           /* Changes whenever database content changes */
43695  char dbFileVers[16];        /* Changes whenever database file changes */
43696
43697  int nMmapOut;               /* Number of mmap pages currently outstanding */
43698  sqlite3_int64 szMmap;       /* Desired maximum mmap size */
43699  PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
43700  /*
43701  ** End of the routinely-changing class members
43702  ***************************************************************************/
43703
43704  u16 nExtra;                 /* Add this many bytes to each in-memory page */
43705  i16 nReserve;               /* Number of unused bytes at end of each page */
43706  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
43707  u32 sectorSize;             /* Assumed sector size during rollback */
43708  int pageSize;               /* Number of bytes in a page */
43709  Pgno mxPgno;                /* Maximum allowed size of the database */
43710  i64 journalSizeLimit;       /* Size limit for persistent journal files */
43711  char *zFilename;            /* Name of the database file */
43712  char *zJournal;             /* Name of the journal file */
43713  int (*xBusyHandler)(void*); /* Function to call when busy */
43714  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
43715  int aStat[3];               /* Total cache hits, misses and writes */
43716#ifdef SQLITE_TEST
43717  int nRead;                  /* Database pages read */
43718#endif
43719  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
43720#ifdef SQLITE_HAS_CODEC
43721  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
43722  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
43723  void (*xCodecFree)(void*);             /* Destructor for the codec */
43724  void *pCodec;               /* First argument to xCodec... methods */
43725#endif
43726  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
43727  PCache *pPCache;            /* Pointer to page cache object */
43728#ifndef SQLITE_OMIT_WAL
43729  Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
43730  char *zWal;                 /* File name for write-ahead log */
43731#endif
43732};
43733
43734/*
43735** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
43736** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
43737** or CACHE_WRITE to sqlite3_db_status().
43738*/
43739#define PAGER_STAT_HIT   0
43740#define PAGER_STAT_MISS  1
43741#define PAGER_STAT_WRITE 2
43742
43743/*
43744** The following global variables hold counters used for
43745** testing purposes only.  These variables do not exist in
43746** a non-testing build.  These variables are not thread-safe.
43747*/
43748#ifdef SQLITE_TEST
43749SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
43750SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
43751SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
43752# define PAGER_INCR(v)  v++
43753#else
43754# define PAGER_INCR(v)
43755#endif
43756
43757
43758
43759/*
43760** Journal files begin with the following magic string.  The data
43761** was obtained from /dev/random.  It is used only as a sanity check.
43762**
43763** Since version 2.8.0, the journal format contains additional sanity
43764** checking information.  If the power fails while the journal is being
43765** written, semi-random garbage data might appear in the journal
43766** file after power is restored.  If an attempt is then made
43767** to roll the journal back, the database could be corrupted.  The additional
43768** sanity checking data is an attempt to discover the garbage in the
43769** journal and ignore it.
43770**
43771** The sanity checking information for the new journal format consists
43772** of a 32-bit checksum on each page of data.  The checksum covers both
43773** the page number and the pPager->pageSize bytes of data for the page.
43774** This cksum is initialized to a 32-bit random value that appears in the
43775** journal file right after the header.  The random initializer is important,
43776** because garbage data that appears at the end of a journal is likely
43777** data that was once in other files that have now been deleted.  If the
43778** garbage data came from an obsolete journal file, the checksums might
43779** be correct.  But by initializing the checksum to random value which
43780** is different for every journal, we minimize that risk.
43781*/
43782static const unsigned char aJournalMagic[] = {
43783  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
43784};
43785
43786/*
43787** The size of the of each page record in the journal is given by
43788** the following macro.
43789*/
43790#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
43791
43792/*
43793** The journal header size for this pager. This is usually the same
43794** size as a single disk sector. See also setSectorSize().
43795*/
43796#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
43797
43798/*
43799** The macro MEMDB is true if we are dealing with an in-memory database.
43800** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
43801** the value of MEMDB will be a constant and the compiler will optimize
43802** out code that would never execute.
43803*/
43804#ifdef SQLITE_OMIT_MEMORYDB
43805# define MEMDB 0
43806#else
43807# define MEMDB pPager->memDb
43808#endif
43809
43810/*
43811** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
43812** interfaces to access the database using memory-mapped I/O.
43813*/
43814#if SQLITE_MAX_MMAP_SIZE>0
43815# define USEFETCH(x) ((x)->bUseFetch)
43816#else
43817# define USEFETCH(x) 0
43818#endif
43819
43820/*
43821** The maximum legal page number is (2^31 - 1).
43822*/
43823#define PAGER_MAX_PGNO 2147483647
43824
43825/*
43826** The argument to this macro is a file descriptor (type sqlite3_file*).
43827** Return 0 if it is not open, or non-zero (but not 1) if it is.
43828**
43829** This is so that expressions can be written as:
43830**
43831**   if( isOpen(pPager->jfd) ){ ...
43832**
43833** instead of
43834**
43835**   if( pPager->jfd->pMethods ){ ...
43836*/
43837#define isOpen(pFd) ((pFd)->pMethods!=0)
43838
43839/*
43840** Return true if this pager uses a write-ahead log instead of the usual
43841** rollback journal. Otherwise false.
43842*/
43843#ifndef SQLITE_OMIT_WAL
43844static int pagerUseWal(Pager *pPager){
43845  return (pPager->pWal!=0);
43846}
43847#else
43848# define pagerUseWal(x) 0
43849# define pagerRollbackWal(x) 0
43850# define pagerWalFrames(v,w,x,y) 0
43851# define pagerOpenWalIfPresent(z) SQLITE_OK
43852# define pagerBeginReadTransaction(z) SQLITE_OK
43853#endif
43854
43855#ifndef NDEBUG
43856/*
43857** Usage:
43858**
43859**   assert( assert_pager_state(pPager) );
43860**
43861** This function runs many asserts to try to find inconsistencies in
43862** the internal state of the Pager object.
43863*/
43864static int assert_pager_state(Pager *p){
43865  Pager *pPager = p;
43866
43867  /* State must be valid. */
43868  assert( p->eState==PAGER_OPEN
43869       || p->eState==PAGER_READER
43870       || p->eState==PAGER_WRITER_LOCKED
43871       || p->eState==PAGER_WRITER_CACHEMOD
43872       || p->eState==PAGER_WRITER_DBMOD
43873       || p->eState==PAGER_WRITER_FINISHED
43874       || p->eState==PAGER_ERROR
43875  );
43876
43877  /* Regardless of the current state, a temp-file connection always behaves
43878  ** as if it has an exclusive lock on the database file. It never updates
43879  ** the change-counter field, so the changeCountDone flag is always set.
43880  */
43881  assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
43882  assert( p->tempFile==0 || pPager->changeCountDone );
43883
43884  /* If the useJournal flag is clear, the journal-mode must be "OFF".
43885  ** And if the journal-mode is "OFF", the journal file must not be open.
43886  */
43887  assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
43888  assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
43889
43890  /* Check that MEMDB implies noSync. And an in-memory journal. Since
43891  ** this means an in-memory pager performs no IO at all, it cannot encounter
43892  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
43893  ** a journal file. (although the in-memory journal implementation may
43894  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
43895  ** is therefore not possible for an in-memory pager to enter the ERROR
43896  ** state.
43897  */
43898  if( MEMDB ){
43899    assert( p->noSync );
43900    assert( p->journalMode==PAGER_JOURNALMODE_OFF
43901         || p->journalMode==PAGER_JOURNALMODE_MEMORY
43902    );
43903    assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
43904    assert( pagerUseWal(p)==0 );
43905  }
43906
43907  /* If changeCountDone is set, a RESERVED lock or greater must be held
43908  ** on the file.
43909  */
43910  assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
43911  assert( p->eLock!=PENDING_LOCK );
43912
43913  switch( p->eState ){
43914    case PAGER_OPEN:
43915      assert( !MEMDB );
43916      assert( pPager->errCode==SQLITE_OK );
43917      assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
43918      break;
43919
43920    case PAGER_READER:
43921      assert( pPager->errCode==SQLITE_OK );
43922      assert( p->eLock!=UNKNOWN_LOCK );
43923      assert( p->eLock>=SHARED_LOCK );
43924      break;
43925
43926    case PAGER_WRITER_LOCKED:
43927      assert( p->eLock!=UNKNOWN_LOCK );
43928      assert( pPager->errCode==SQLITE_OK );
43929      if( !pagerUseWal(pPager) ){
43930        assert( p->eLock>=RESERVED_LOCK );
43931      }
43932      assert( pPager->dbSize==pPager->dbOrigSize );
43933      assert( pPager->dbOrigSize==pPager->dbFileSize );
43934      assert( pPager->dbOrigSize==pPager->dbHintSize );
43935      assert( pPager->setMaster==0 );
43936      break;
43937
43938    case PAGER_WRITER_CACHEMOD:
43939      assert( p->eLock!=UNKNOWN_LOCK );
43940      assert( pPager->errCode==SQLITE_OK );
43941      if( !pagerUseWal(pPager) ){
43942        /* It is possible that if journal_mode=wal here that neither the
43943        ** journal file nor the WAL file are open. This happens during
43944        ** a rollback transaction that switches from journal_mode=off
43945        ** to journal_mode=wal.
43946        */
43947        assert( p->eLock>=RESERVED_LOCK );
43948        assert( isOpen(p->jfd)
43949             || p->journalMode==PAGER_JOURNALMODE_OFF
43950             || p->journalMode==PAGER_JOURNALMODE_WAL
43951        );
43952      }
43953      assert( pPager->dbOrigSize==pPager->dbFileSize );
43954      assert( pPager->dbOrigSize==pPager->dbHintSize );
43955      break;
43956
43957    case PAGER_WRITER_DBMOD:
43958      assert( p->eLock==EXCLUSIVE_LOCK );
43959      assert( pPager->errCode==SQLITE_OK );
43960      assert( !pagerUseWal(pPager) );
43961      assert( p->eLock>=EXCLUSIVE_LOCK );
43962      assert( isOpen(p->jfd)
43963           || p->journalMode==PAGER_JOURNALMODE_OFF
43964           || p->journalMode==PAGER_JOURNALMODE_WAL
43965      );
43966      assert( pPager->dbOrigSize<=pPager->dbHintSize );
43967      break;
43968
43969    case PAGER_WRITER_FINISHED:
43970      assert( p->eLock==EXCLUSIVE_LOCK );
43971      assert( pPager->errCode==SQLITE_OK );
43972      assert( !pagerUseWal(pPager) );
43973      assert( isOpen(p->jfd)
43974           || p->journalMode==PAGER_JOURNALMODE_OFF
43975           || p->journalMode==PAGER_JOURNALMODE_WAL
43976      );
43977      break;
43978
43979    case PAGER_ERROR:
43980      /* There must be at least one outstanding reference to the pager if
43981      ** in ERROR state. Otherwise the pager should have already dropped
43982      ** back to OPEN state.
43983      */
43984      assert( pPager->errCode!=SQLITE_OK );
43985      assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
43986      break;
43987  }
43988
43989  return 1;
43990}
43991#endif /* ifndef NDEBUG */
43992
43993#ifdef SQLITE_DEBUG
43994/*
43995** Return a pointer to a human readable string in a static buffer
43996** containing the state of the Pager object passed as an argument. This
43997** is intended to be used within debuggers. For example, as an alternative
43998** to "print *pPager" in gdb:
43999**
44000** (gdb) printf "%s", print_pager_state(pPager)
44001*/
44002static char *print_pager_state(Pager *p){
44003  static char zRet[1024];
44004
44005  sqlite3_snprintf(1024, zRet,
44006      "Filename:      %s\n"
44007      "State:         %s errCode=%d\n"
44008      "Lock:          %s\n"
44009      "Locking mode:  locking_mode=%s\n"
44010      "Journal mode:  journal_mode=%s\n"
44011      "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
44012      "Journal:       journalOff=%lld journalHdr=%lld\n"
44013      "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
44014      , p->zFilename
44015      , p->eState==PAGER_OPEN            ? "OPEN" :
44016        p->eState==PAGER_READER          ? "READER" :
44017        p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
44018        p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
44019        p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
44020        p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
44021        p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
44022      , (int)p->errCode
44023      , p->eLock==NO_LOCK         ? "NO_LOCK" :
44024        p->eLock==RESERVED_LOCK   ? "RESERVED" :
44025        p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
44026        p->eLock==SHARED_LOCK     ? "SHARED" :
44027        p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
44028      , p->exclusiveMode ? "exclusive" : "normal"
44029      , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
44030        p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
44031        p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
44032        p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
44033        p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
44034        p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
44035      , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
44036      , p->journalOff, p->journalHdr
44037      , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
44038  );
44039
44040  return zRet;
44041}
44042#endif
44043
44044/*
44045** Return true if it is necessary to write page *pPg into the sub-journal.
44046** A page needs to be written into the sub-journal if there exists one
44047** or more open savepoints for which:
44048**
44049**   * The page-number is less than or equal to PagerSavepoint.nOrig, and
44050**   * The bit corresponding to the page-number is not set in
44051**     PagerSavepoint.pInSavepoint.
44052*/
44053static int subjRequiresPage(PgHdr *pPg){
44054  Pager *pPager = pPg->pPager;
44055  PagerSavepoint *p;
44056  Pgno pgno = pPg->pgno;
44057  int i;
44058  for(i=0; i<pPager->nSavepoint; i++){
44059    p = &pPager->aSavepoint[i];
44060    if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
44061      return 1;
44062    }
44063  }
44064  return 0;
44065}
44066
44067#ifdef SQLITE_DEBUG
44068/*
44069** Return true if the page is already in the journal file.
44070*/
44071static int pageInJournal(Pager *pPager, PgHdr *pPg){
44072  return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
44073}
44074#endif
44075
44076/*
44077** Read a 32-bit integer from the given file descriptor.  Store the integer
44078** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
44079** error code is something goes wrong.
44080**
44081** All values are stored on disk as big-endian.
44082*/
44083static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
44084  unsigned char ac[4];
44085  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
44086  if( rc==SQLITE_OK ){
44087    *pRes = sqlite3Get4byte(ac);
44088  }
44089  return rc;
44090}
44091
44092/*
44093** Write a 32-bit integer into a string buffer in big-endian byte order.
44094*/
44095#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
44096
44097
44098/*
44099** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
44100** on success or an error code is something goes wrong.
44101*/
44102static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
44103  char ac[4];
44104  put32bits(ac, val);
44105  return sqlite3OsWrite(fd, ac, 4, offset);
44106}
44107
44108/*
44109** Unlock the database file to level eLock, which must be either NO_LOCK
44110** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
44111** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
44112**
44113** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
44114** called, do not modify it. See the comment above the #define of
44115** UNKNOWN_LOCK for an explanation of this.
44116*/
44117static int pagerUnlockDb(Pager *pPager, int eLock){
44118  int rc = SQLITE_OK;
44119
44120  assert( !pPager->exclusiveMode || pPager->eLock==eLock );
44121  assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
44122  assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
44123  if( isOpen(pPager->fd) ){
44124    assert( pPager->eLock>=eLock );
44125    rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
44126    if( pPager->eLock!=UNKNOWN_LOCK ){
44127      pPager->eLock = (u8)eLock;
44128    }
44129    IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
44130  }
44131  return rc;
44132}
44133
44134/*
44135** Lock the database file to level eLock, which must be either SHARED_LOCK,
44136** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
44137** Pager.eLock variable to the new locking state.
44138**
44139** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
44140** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
44141** See the comment above the #define of UNKNOWN_LOCK for an explanation
44142** of this.
44143*/
44144static int pagerLockDb(Pager *pPager, int eLock){
44145  int rc = SQLITE_OK;
44146
44147  assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
44148  if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
44149    rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
44150    if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
44151      pPager->eLock = (u8)eLock;
44152      IOTRACE(("LOCK %p %d\n", pPager, eLock))
44153    }
44154  }
44155  return rc;
44156}
44157
44158/*
44159** This function determines whether or not the atomic-write optimization
44160** can be used with this pager. The optimization can be used if:
44161**
44162**  (a) the value returned by OsDeviceCharacteristics() indicates that
44163**      a database page may be written atomically, and
44164**  (b) the value returned by OsSectorSize() is less than or equal
44165**      to the page size.
44166**
44167** The optimization is also always enabled for temporary files. It is
44168** an error to call this function if pPager is opened on an in-memory
44169** database.
44170**
44171** If the optimization cannot be used, 0 is returned. If it can be used,
44172** then the value returned is the size of the journal file when it
44173** contains rollback data for exactly one page.
44174*/
44175#ifdef SQLITE_ENABLE_ATOMIC_WRITE
44176static int jrnlBufferSize(Pager *pPager){
44177  assert( !MEMDB );
44178  if( !pPager->tempFile ){
44179    int dc;                           /* Device characteristics */
44180    int nSector;                      /* Sector size */
44181    int szPage;                       /* Page size */
44182
44183    assert( isOpen(pPager->fd) );
44184    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
44185    nSector = pPager->sectorSize;
44186    szPage = pPager->pageSize;
44187
44188    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
44189    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
44190    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
44191      return 0;
44192    }
44193  }
44194
44195  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
44196}
44197#endif
44198
44199/*
44200** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
44201** on the cache using a hash function.  This is used for testing
44202** and debugging only.
44203*/
44204#ifdef SQLITE_CHECK_PAGES
44205/*
44206** Return a 32-bit hash of the page data for pPage.
44207*/
44208static u32 pager_datahash(int nByte, unsigned char *pData){
44209  u32 hash = 0;
44210  int i;
44211  for(i=0; i<nByte; i++){
44212    hash = (hash*1039) + pData[i];
44213  }
44214  return hash;
44215}
44216static u32 pager_pagehash(PgHdr *pPage){
44217  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
44218}
44219static void pager_set_pagehash(PgHdr *pPage){
44220  pPage->pageHash = pager_pagehash(pPage);
44221}
44222
44223/*
44224** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
44225** is defined, and NDEBUG is not defined, an assert() statement checks
44226** that the page is either dirty or still matches the calculated page-hash.
44227*/
44228#define CHECK_PAGE(x) checkPage(x)
44229static void checkPage(PgHdr *pPg){
44230  Pager *pPager = pPg->pPager;
44231  assert( pPager->eState!=PAGER_ERROR );
44232  assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
44233}
44234
44235#else
44236#define pager_datahash(X,Y)  0
44237#define pager_pagehash(X)  0
44238#define pager_set_pagehash(X)
44239#define CHECK_PAGE(x)
44240#endif  /* SQLITE_CHECK_PAGES */
44241
44242/*
44243** When this is called the journal file for pager pPager must be open.
44244** This function attempts to read a master journal file name from the
44245** end of the file and, if successful, copies it into memory supplied
44246** by the caller. See comments above writeMasterJournal() for the format
44247** used to store a master journal file name at the end of a journal file.
44248**
44249** zMaster must point to a buffer of at least nMaster bytes allocated by
44250** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
44251** enough space to write the master journal name). If the master journal
44252** name in the journal is longer than nMaster bytes (including a
44253** nul-terminator), then this is handled as if no master journal name
44254** were present in the journal.
44255**
44256** If a master journal file name is present at the end of the journal
44257** file, then it is copied into the buffer pointed to by zMaster. A
44258** nul-terminator byte is appended to the buffer following the master
44259** journal file name.
44260**
44261** If it is determined that no master journal file name is present
44262** zMaster[0] is set to 0 and SQLITE_OK returned.
44263**
44264** If an error occurs while reading from the journal file, an SQLite
44265** error code is returned.
44266*/
44267static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
44268  int rc;                    /* Return code */
44269  u32 len;                   /* Length in bytes of master journal name */
44270  i64 szJ;                   /* Total size in bytes of journal file pJrnl */
44271  u32 cksum;                 /* MJ checksum value read from journal */
44272  u32 u;                     /* Unsigned loop counter */
44273  unsigned char aMagic[8];   /* A buffer to hold the magic header */
44274  zMaster[0] = '\0';
44275
44276  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
44277   || szJ<16
44278   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
44279   || len>=nMaster
44280   || len==0
44281   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
44282   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
44283   || memcmp(aMagic, aJournalMagic, 8)
44284   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
44285  ){
44286    return rc;
44287  }
44288
44289  /* See if the checksum matches the master journal name */
44290  for(u=0; u<len; u++){
44291    cksum -= zMaster[u];
44292  }
44293  if( cksum ){
44294    /* If the checksum doesn't add up, then one or more of the disk sectors
44295    ** containing the master journal filename is corrupted. This means
44296    ** definitely roll back, so just return SQLITE_OK and report a (nul)
44297    ** master-journal filename.
44298    */
44299    len = 0;
44300  }
44301  zMaster[len] = '\0';
44302
44303  return SQLITE_OK;
44304}
44305
44306/*
44307** Return the offset of the sector boundary at or immediately
44308** following the value in pPager->journalOff, assuming a sector
44309** size of pPager->sectorSize bytes.
44310**
44311** i.e for a sector size of 512:
44312**
44313**   Pager.journalOff          Return value
44314**   ---------------------------------------
44315**   0                         0
44316**   512                       512
44317**   100                       512
44318**   2000                      2048
44319**
44320*/
44321static i64 journalHdrOffset(Pager *pPager){
44322  i64 offset = 0;
44323  i64 c = pPager->journalOff;
44324  if( c ){
44325    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
44326  }
44327  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
44328  assert( offset>=c );
44329  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
44330  return offset;
44331}
44332
44333/*
44334** The journal file must be open when this function is called.
44335**
44336** This function is a no-op if the journal file has not been written to
44337** within the current transaction (i.e. if Pager.journalOff==0).
44338**
44339** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
44340** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
44341** zero the 28-byte header at the start of the journal file. In either case,
44342** if the pager is not in no-sync mode, sync the journal file immediately
44343** after writing or truncating it.
44344**
44345** If Pager.journalSizeLimit is set to a positive, non-zero value, and
44346** following the truncation or zeroing described above the size of the
44347** journal file in bytes is larger than this value, then truncate the
44348** journal file to Pager.journalSizeLimit bytes. The journal file does
44349** not need to be synced following this operation.
44350**
44351** If an IO error occurs, abandon processing and return the IO error code.
44352** Otherwise, return SQLITE_OK.
44353*/
44354static int zeroJournalHdr(Pager *pPager, int doTruncate){
44355  int rc = SQLITE_OK;                               /* Return code */
44356  assert( isOpen(pPager->jfd) );
44357  if( pPager->journalOff ){
44358    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
44359
44360    IOTRACE(("JZEROHDR %p\n", pPager))
44361    if( doTruncate || iLimit==0 ){
44362      rc = sqlite3OsTruncate(pPager->jfd, 0);
44363    }else{
44364      static const char zeroHdr[28] = {0};
44365      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
44366    }
44367    if( rc==SQLITE_OK && !pPager->noSync ){
44368      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
44369    }
44370
44371    /* At this point the transaction is committed but the write lock
44372    ** is still held on the file. If there is a size limit configured for
44373    ** the persistent journal and the journal file currently consumes more
44374    ** space than that limit allows for, truncate it now. There is no need
44375    ** to sync the file following this operation.
44376    */
44377    if( rc==SQLITE_OK && iLimit>0 ){
44378      i64 sz;
44379      rc = sqlite3OsFileSize(pPager->jfd, &sz);
44380      if( rc==SQLITE_OK && sz>iLimit ){
44381        rc = sqlite3OsTruncate(pPager->jfd, iLimit);
44382      }
44383    }
44384  }
44385  return rc;
44386}
44387
44388/*
44389** The journal file must be open when this routine is called. A journal
44390** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
44391** current location.
44392**
44393** The format for the journal header is as follows:
44394** - 8 bytes: Magic identifying journal format.
44395** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
44396** - 4 bytes: Random number used for page hash.
44397** - 4 bytes: Initial database page count.
44398** - 4 bytes: Sector size used by the process that wrote this journal.
44399** - 4 bytes: Database page size.
44400**
44401** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
44402*/
44403static int writeJournalHdr(Pager *pPager){
44404  int rc = SQLITE_OK;                 /* Return code */
44405  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
44406  u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
44407  u32 nWrite;                         /* Bytes of header sector written */
44408  int ii;                             /* Loop counter */
44409
44410  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
44411
44412  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
44413    nHeader = JOURNAL_HDR_SZ(pPager);
44414  }
44415
44416  /* If there are active savepoints and any of them were created
44417  ** since the most recent journal header was written, update the
44418  ** PagerSavepoint.iHdrOffset fields now.
44419  */
44420  for(ii=0; ii<pPager->nSavepoint; ii++){
44421    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
44422      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
44423    }
44424  }
44425
44426  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
44427
44428  /*
44429  ** Write the nRec Field - the number of page records that follow this
44430  ** journal header. Normally, zero is written to this value at this time.
44431  ** After the records are added to the journal (and the journal synced,
44432  ** if in full-sync mode), the zero is overwritten with the true number
44433  ** of records (see syncJournal()).
44434  **
44435  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
44436  ** reading the journal this value tells SQLite to assume that the
44437  ** rest of the journal file contains valid page records. This assumption
44438  ** is dangerous, as if a failure occurred whilst writing to the journal
44439  ** file it may contain some garbage data. There are two scenarios
44440  ** where this risk can be ignored:
44441  **
44442  **   * When the pager is in no-sync mode. Corruption can follow a
44443  **     power failure in this case anyway.
44444  **
44445  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
44446  **     that garbage data is never appended to the journal file.
44447  */
44448  assert( isOpen(pPager->fd) || pPager->noSync );
44449  if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
44450   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
44451  ){
44452    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
44453    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
44454  }else{
44455    memset(zHeader, 0, sizeof(aJournalMagic)+4);
44456  }
44457
44458  /* The random check-hash initializer */
44459  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
44460  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
44461  /* The initial database size */
44462  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
44463  /* The assumed sector size for this process */
44464  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
44465
44466  /* The page size */
44467  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
44468
44469  /* Initializing the tail of the buffer is not necessary.  Everything
44470  ** works find if the following memset() is omitted.  But initializing
44471  ** the memory prevents valgrind from complaining, so we are willing to
44472  ** take the performance hit.
44473  */
44474  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
44475         nHeader-(sizeof(aJournalMagic)+20));
44476
44477  /* In theory, it is only necessary to write the 28 bytes that the
44478  ** journal header consumes to the journal file here. Then increment the
44479  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
44480  ** record is written to the following sector (leaving a gap in the file
44481  ** that will be implicitly filled in by the OS).
44482  **
44483  ** However it has been discovered that on some systems this pattern can
44484  ** be significantly slower than contiguously writing data to the file,
44485  ** even if that means explicitly writing data to the block of
44486  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
44487  ** is done.
44488  **
44489  ** The loop is required here in case the sector-size is larger than the
44490  ** database page size. Since the zHeader buffer is only Pager.pageSize
44491  ** bytes in size, more than one call to sqlite3OsWrite() may be required
44492  ** to populate the entire journal header sector.
44493  */
44494  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
44495    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
44496    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
44497    assert( pPager->journalHdr <= pPager->journalOff );
44498    pPager->journalOff += nHeader;
44499  }
44500
44501  return rc;
44502}
44503
44504/*
44505** The journal file must be open when this is called. A journal header file
44506** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
44507** file. The current location in the journal file is given by
44508** pPager->journalOff. See comments above function writeJournalHdr() for
44509** a description of the journal header format.
44510**
44511** If the header is read successfully, *pNRec is set to the number of
44512** page records following this header and *pDbSize is set to the size of the
44513** database before the transaction began, in pages. Also, pPager->cksumInit
44514** is set to the value read from the journal header. SQLITE_OK is returned
44515** in this case.
44516**
44517** If the journal header file appears to be corrupted, SQLITE_DONE is
44518** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
44519** cannot be read from the journal file an error code is returned.
44520*/
44521static int readJournalHdr(
44522  Pager *pPager,               /* Pager object */
44523  int isHot,
44524  i64 journalSize,             /* Size of the open journal file in bytes */
44525  u32 *pNRec,                  /* OUT: Value read from the nRec field */
44526  u32 *pDbSize                 /* OUT: Value of original database size field */
44527){
44528  int rc;                      /* Return code */
44529  unsigned char aMagic[8];     /* A buffer to hold the magic header */
44530  i64 iHdrOff;                 /* Offset of journal header being read */
44531
44532  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
44533
44534  /* Advance Pager.journalOff to the start of the next sector. If the
44535  ** journal file is too small for there to be a header stored at this
44536  ** point, return SQLITE_DONE.
44537  */
44538  pPager->journalOff = journalHdrOffset(pPager);
44539  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
44540    return SQLITE_DONE;
44541  }
44542  iHdrOff = pPager->journalOff;
44543
44544  /* Read in the first 8 bytes of the journal header. If they do not match
44545  ** the  magic string found at the start of each journal header, return
44546  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
44547  ** proceed.
44548  */
44549  if( isHot || iHdrOff!=pPager->journalHdr ){
44550    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
44551    if( rc ){
44552      return rc;
44553    }
44554    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
44555      return SQLITE_DONE;
44556    }
44557  }
44558
44559  /* Read the first three 32-bit fields of the journal header: The nRec
44560  ** field, the checksum-initializer and the database size at the start
44561  ** of the transaction. Return an error code if anything goes wrong.
44562  */
44563  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
44564   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
44565   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
44566  ){
44567    return rc;
44568  }
44569
44570  if( pPager->journalOff==0 ){
44571    u32 iPageSize;               /* Page-size field of journal header */
44572    u32 iSectorSize;             /* Sector-size field of journal header */
44573
44574    /* Read the page-size and sector-size journal header fields. */
44575    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
44576     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
44577    ){
44578      return rc;
44579    }
44580
44581    /* Versions of SQLite prior to 3.5.8 set the page-size field of the
44582    ** journal header to zero. In this case, assume that the Pager.pageSize
44583    ** variable is already set to the correct page size.
44584    */
44585    if( iPageSize==0 ){
44586      iPageSize = pPager->pageSize;
44587    }
44588
44589    /* Check that the values read from the page-size and sector-size fields
44590    ** are within range. To be 'in range', both values need to be a power
44591    ** of two greater than or equal to 512 or 32, and not greater than their
44592    ** respective compile time maximum limits.
44593    */
44594    if( iPageSize<512                  || iSectorSize<32
44595     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
44596     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
44597    ){
44598      /* If the either the page-size or sector-size in the journal-header is
44599      ** invalid, then the process that wrote the journal-header must have
44600      ** crashed before the header was synced. In this case stop reading
44601      ** the journal file here.
44602      */
44603      return SQLITE_DONE;
44604    }
44605
44606    /* Update the page-size to match the value read from the journal.
44607    ** Use a testcase() macro to make sure that malloc failure within
44608    ** PagerSetPagesize() is tested.
44609    */
44610    rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
44611    testcase( rc!=SQLITE_OK );
44612
44613    /* Update the assumed sector-size to match the value used by
44614    ** the process that created this journal. If this journal was
44615    ** created by a process other than this one, then this routine
44616    ** is being called from within pager_playback(). The local value
44617    ** of Pager.sectorSize is restored at the end of that routine.
44618    */
44619    pPager->sectorSize = iSectorSize;
44620  }
44621
44622  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
44623  return rc;
44624}
44625
44626
44627/*
44628** Write the supplied master journal name into the journal file for pager
44629** pPager at the current location. The master journal name must be the last
44630** thing written to a journal file. If the pager is in full-sync mode, the
44631** journal file descriptor is advanced to the next sector boundary before
44632** anything is written. The format is:
44633**
44634**   + 4 bytes: PAGER_MJ_PGNO.
44635**   + N bytes: Master journal filename in utf-8.
44636**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
44637**   + 4 bytes: Master journal name checksum.
44638**   + 8 bytes: aJournalMagic[].
44639**
44640** The master journal page checksum is the sum of the bytes in the master
44641** journal name, where each byte is interpreted as a signed 8-bit integer.
44642**
44643** If zMaster is a NULL pointer (occurs for a single database transaction),
44644** this call is a no-op.
44645*/
44646static int writeMasterJournal(Pager *pPager, const char *zMaster){
44647  int rc;                          /* Return code */
44648  int nMaster;                     /* Length of string zMaster */
44649  i64 iHdrOff;                     /* Offset of header in journal file */
44650  i64 jrnlSize;                    /* Size of journal file on disk */
44651  u32 cksum = 0;                   /* Checksum of string zMaster */
44652
44653  assert( pPager->setMaster==0 );
44654  assert( !pagerUseWal(pPager) );
44655
44656  if( !zMaster
44657   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
44658   || !isOpen(pPager->jfd)
44659  ){
44660    return SQLITE_OK;
44661  }
44662  pPager->setMaster = 1;
44663  assert( pPager->journalHdr <= pPager->journalOff );
44664
44665  /* Calculate the length in bytes and the checksum of zMaster */
44666  for(nMaster=0; zMaster[nMaster]; nMaster++){
44667    cksum += zMaster[nMaster];
44668  }
44669
44670  /* If in full-sync mode, advance to the next disk sector before writing
44671  ** the master journal name. This is in case the previous page written to
44672  ** the journal has already been synced.
44673  */
44674  if( pPager->fullSync ){
44675    pPager->journalOff = journalHdrOffset(pPager);
44676  }
44677  iHdrOff = pPager->journalOff;
44678
44679  /* Write the master journal data to the end of the journal file. If
44680  ** an error occurs, return the error code to the caller.
44681  */
44682  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
44683   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
44684   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
44685   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
44686   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
44687                                 iHdrOff+4+nMaster+8)))
44688  ){
44689    return rc;
44690  }
44691  pPager->journalOff += (nMaster+20);
44692
44693  /* If the pager is in peristent-journal mode, then the physical
44694  ** journal-file may extend past the end of the master-journal name
44695  ** and 8 bytes of magic data just written to the file. This is
44696  ** dangerous because the code to rollback a hot-journal file
44697  ** will not be able to find the master-journal name to determine
44698  ** whether or not the journal is hot.
44699  **
44700  ** Easiest thing to do in this scenario is to truncate the journal
44701  ** file to the required size.
44702  */
44703  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
44704   && jrnlSize>pPager->journalOff
44705  ){
44706    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
44707  }
44708  return rc;
44709}
44710
44711/*
44712** Discard the entire contents of the in-memory page-cache.
44713*/
44714static void pager_reset(Pager *pPager){
44715  pPager->iDataVersion++;
44716  sqlite3BackupRestart(pPager->pBackup);
44717  sqlite3PcacheClear(pPager->pPCache);
44718}
44719
44720/*
44721** Return the pPager->iDataVersion value
44722*/
44723SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
44724  assert( pPager->eState>PAGER_OPEN );
44725  return pPager->iDataVersion;
44726}
44727
44728/*
44729** Free all structures in the Pager.aSavepoint[] array and set both
44730** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
44731** if it is open and the pager is not in exclusive mode.
44732*/
44733static void releaseAllSavepoints(Pager *pPager){
44734  int ii;               /* Iterator for looping through Pager.aSavepoint */
44735  for(ii=0; ii<pPager->nSavepoint; ii++){
44736    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
44737  }
44738  if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
44739    sqlite3OsClose(pPager->sjfd);
44740  }
44741  sqlite3_free(pPager->aSavepoint);
44742  pPager->aSavepoint = 0;
44743  pPager->nSavepoint = 0;
44744  pPager->nSubRec = 0;
44745}
44746
44747/*
44748** Set the bit number pgno in the PagerSavepoint.pInSavepoint
44749** bitvecs of all open savepoints. Return SQLITE_OK if successful
44750** or SQLITE_NOMEM if a malloc failure occurs.
44751*/
44752static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
44753  int ii;                   /* Loop counter */
44754  int rc = SQLITE_OK;       /* Result code */
44755
44756  for(ii=0; ii<pPager->nSavepoint; ii++){
44757    PagerSavepoint *p = &pPager->aSavepoint[ii];
44758    if( pgno<=p->nOrig ){
44759      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
44760      testcase( rc==SQLITE_NOMEM );
44761      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
44762    }
44763  }
44764  return rc;
44765}
44766
44767/*
44768** This function is a no-op if the pager is in exclusive mode and not
44769** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
44770** state.
44771**
44772** If the pager is not in exclusive-access mode, the database file is
44773** completely unlocked. If the file is unlocked and the file-system does
44774** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
44775** closed (if it is open).
44776**
44777** If the pager is in ERROR state when this function is called, the
44778** contents of the pager cache are discarded before switching back to
44779** the OPEN state. Regardless of whether the pager is in exclusive-mode
44780** or not, any journal file left in the file-system will be treated
44781** as a hot-journal and rolled back the next time a read-transaction
44782** is opened (by this or by any other connection).
44783*/
44784static void pager_unlock(Pager *pPager){
44785
44786  assert( pPager->eState==PAGER_READER
44787       || pPager->eState==PAGER_OPEN
44788       || pPager->eState==PAGER_ERROR
44789  );
44790
44791  sqlite3BitvecDestroy(pPager->pInJournal);
44792  pPager->pInJournal = 0;
44793  releaseAllSavepoints(pPager);
44794
44795  if( pagerUseWal(pPager) ){
44796    assert( !isOpen(pPager->jfd) );
44797    sqlite3WalEndReadTransaction(pPager->pWal);
44798    pPager->eState = PAGER_OPEN;
44799  }else if( !pPager->exclusiveMode ){
44800    int rc;                       /* Error code returned by pagerUnlockDb() */
44801    int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
44802
44803    /* If the operating system support deletion of open files, then
44804    ** close the journal file when dropping the database lock.  Otherwise
44805    ** another connection with journal_mode=delete might delete the file
44806    ** out from under us.
44807    */
44808    assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
44809    assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
44810    assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
44811    assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
44812    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
44813    assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
44814    if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
44815     || 1!=(pPager->journalMode & 5)
44816    ){
44817      sqlite3OsClose(pPager->jfd);
44818    }
44819
44820    /* If the pager is in the ERROR state and the call to unlock the database
44821    ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
44822    ** above the #define for UNKNOWN_LOCK for an explanation of why this
44823    ** is necessary.
44824    */
44825    rc = pagerUnlockDb(pPager, NO_LOCK);
44826    if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
44827      pPager->eLock = UNKNOWN_LOCK;
44828    }
44829
44830    /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
44831    ** without clearing the error code. This is intentional - the error
44832    ** code is cleared and the cache reset in the block below.
44833    */
44834    assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
44835    pPager->changeCountDone = 0;
44836    pPager->eState = PAGER_OPEN;
44837  }
44838
44839  /* If Pager.errCode is set, the contents of the pager cache cannot be
44840  ** trusted. Now that there are no outstanding references to the pager,
44841  ** it can safely move back to PAGER_OPEN state. This happens in both
44842  ** normal and exclusive-locking mode.
44843  */
44844  if( pPager->errCode ){
44845    assert( !MEMDB );
44846    pager_reset(pPager);
44847    pPager->changeCountDone = pPager->tempFile;
44848    pPager->eState = PAGER_OPEN;
44849    pPager->errCode = SQLITE_OK;
44850    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
44851  }
44852
44853  pPager->journalOff = 0;
44854  pPager->journalHdr = 0;
44855  pPager->setMaster = 0;
44856}
44857
44858/*
44859** This function is called whenever an IOERR or FULL error that requires
44860** the pager to transition into the ERROR state may ahve occurred.
44861** The first argument is a pointer to the pager structure, the second
44862** the error-code about to be returned by a pager API function. The
44863** value returned is a copy of the second argument to this function.
44864**
44865** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
44866** IOERR sub-codes, the pager enters the ERROR state and the error code
44867** is stored in Pager.errCode. While the pager remains in the ERROR state,
44868** all major API calls on the Pager will immediately return Pager.errCode.
44869**
44870** The ERROR state indicates that the contents of the pager-cache
44871** cannot be trusted. This state can be cleared by completely discarding
44872** the contents of the pager-cache. If a transaction was active when
44873** the persistent error occurred, then the rollback journal may need
44874** to be replayed to restore the contents of the database file (as if
44875** it were a hot-journal).
44876*/
44877static int pager_error(Pager *pPager, int rc){
44878  int rc2 = rc & 0xff;
44879  assert( rc==SQLITE_OK || !MEMDB );
44880  assert(
44881       pPager->errCode==SQLITE_FULL ||
44882       pPager->errCode==SQLITE_OK ||
44883       (pPager->errCode & 0xff)==SQLITE_IOERR
44884  );
44885  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
44886    pPager->errCode = rc;
44887    pPager->eState = PAGER_ERROR;
44888  }
44889  return rc;
44890}
44891
44892static int pager_truncate(Pager *pPager, Pgno nPage);
44893
44894/*
44895** This routine ends a transaction. A transaction is usually ended by
44896** either a COMMIT or a ROLLBACK operation. This routine may be called
44897** after rollback of a hot-journal, or if an error occurs while opening
44898** the journal file or writing the very first journal-header of a
44899** database transaction.
44900**
44901** This routine is never called in PAGER_ERROR state. If it is called
44902** in PAGER_NONE or PAGER_SHARED state and the lock held is less
44903** exclusive than a RESERVED lock, it is a no-op.
44904**
44905** Otherwise, any active savepoints are released.
44906**
44907** If the journal file is open, then it is "finalized". Once a journal
44908** file has been finalized it is not possible to use it to roll back a
44909** transaction. Nor will it be considered to be a hot-journal by this
44910** or any other database connection. Exactly how a journal is finalized
44911** depends on whether or not the pager is running in exclusive mode and
44912** the current journal-mode (Pager.journalMode value), as follows:
44913**
44914**   journalMode==MEMORY
44915**     Journal file descriptor is simply closed. This destroys an
44916**     in-memory journal.
44917**
44918**   journalMode==TRUNCATE
44919**     Journal file is truncated to zero bytes in size.
44920**
44921**   journalMode==PERSIST
44922**     The first 28 bytes of the journal file are zeroed. This invalidates
44923**     the first journal header in the file, and hence the entire journal
44924**     file. An invalid journal file cannot be rolled back.
44925**
44926**   journalMode==DELETE
44927**     The journal file is closed and deleted using sqlite3OsDelete().
44928**
44929**     If the pager is running in exclusive mode, this method of finalizing
44930**     the journal file is never used. Instead, if the journalMode is
44931**     DELETE and the pager is in exclusive mode, the method described under
44932**     journalMode==PERSIST is used instead.
44933**
44934** After the journal is finalized, the pager moves to PAGER_READER state.
44935** If running in non-exclusive rollback mode, the lock on the file is
44936** downgraded to a SHARED_LOCK.
44937**
44938** SQLITE_OK is returned if no error occurs. If an error occurs during
44939** any of the IO operations to finalize the journal file or unlock the
44940** database then the IO error code is returned to the user. If the
44941** operation to finalize the journal file fails, then the code still
44942** tries to unlock the database file if not in exclusive mode. If the
44943** unlock operation fails as well, then the first error code related
44944** to the first error encountered (the journal finalization one) is
44945** returned.
44946*/
44947static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
44948  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
44949  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
44950
44951  /* Do nothing if the pager does not have an open write transaction
44952  ** or at least a RESERVED lock. This function may be called when there
44953  ** is no write-transaction active but a RESERVED or greater lock is
44954  ** held under two circumstances:
44955  **
44956  **   1. After a successful hot-journal rollback, it is called with
44957  **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
44958  **
44959  **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
44960  **      lock switches back to locking_mode=normal and then executes a
44961  **      read-transaction, this function is called with eState==PAGER_READER
44962  **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
44963  */
44964  assert( assert_pager_state(pPager) );
44965  assert( pPager->eState!=PAGER_ERROR );
44966  if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
44967    return SQLITE_OK;
44968  }
44969
44970  releaseAllSavepoints(pPager);
44971  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
44972  if( isOpen(pPager->jfd) ){
44973    assert( !pagerUseWal(pPager) );
44974
44975    /* Finalize the journal file. */
44976    if( sqlite3IsMemJournal(pPager->jfd) ){
44977      assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
44978      sqlite3OsClose(pPager->jfd);
44979    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
44980      if( pPager->journalOff==0 ){
44981        rc = SQLITE_OK;
44982      }else{
44983        rc = sqlite3OsTruncate(pPager->jfd, 0);
44984        if( rc==SQLITE_OK && pPager->fullSync ){
44985          /* Make sure the new file size is written into the inode right away.
44986          ** Otherwise the journal might resurrect following a power loss and
44987          ** cause the last transaction to roll back.  See
44988          ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
44989          */
44990          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
44991        }
44992      }
44993      pPager->journalOff = 0;
44994    }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
44995      || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
44996    ){
44997      rc = zeroJournalHdr(pPager, hasMaster);
44998      pPager->journalOff = 0;
44999    }else{
45000      /* This branch may be executed with Pager.journalMode==MEMORY if
45001      ** a hot-journal was just rolled back. In this case the journal
45002      ** file should be closed and deleted. If this connection writes to
45003      ** the database file, it will do so using an in-memory journal.
45004      */
45005      int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
45006      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
45007           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
45008           || pPager->journalMode==PAGER_JOURNALMODE_WAL
45009      );
45010      sqlite3OsClose(pPager->jfd);
45011      if( bDelete ){
45012        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
45013      }
45014    }
45015  }
45016
45017#ifdef SQLITE_CHECK_PAGES
45018  sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
45019  if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
45020    PgHdr *p = sqlite3PagerLookup(pPager, 1);
45021    if( p ){
45022      p->pageHash = 0;
45023      sqlite3PagerUnrefNotNull(p);
45024    }
45025  }
45026#endif
45027
45028  sqlite3BitvecDestroy(pPager->pInJournal);
45029  pPager->pInJournal = 0;
45030  pPager->nRec = 0;
45031  sqlite3PcacheCleanAll(pPager->pPCache);
45032  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
45033
45034  if( pagerUseWal(pPager) ){
45035    /* Drop the WAL write-lock, if any. Also, if the connection was in
45036    ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
45037    ** lock held on the database file.
45038    */
45039    rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
45040    assert( rc2==SQLITE_OK );
45041  }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
45042    /* This branch is taken when committing a transaction in rollback-journal
45043    ** mode if the database file on disk is larger than the database image.
45044    ** At this point the journal has been finalized and the transaction
45045    ** successfully committed, but the EXCLUSIVE lock is still held on the
45046    ** file. So it is safe to truncate the database file to its minimum
45047    ** required size.  */
45048    assert( pPager->eLock==EXCLUSIVE_LOCK );
45049    rc = pager_truncate(pPager, pPager->dbSize);
45050  }
45051
45052  if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
45053    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
45054    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
45055  }
45056
45057  if( !pPager->exclusiveMode
45058   && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
45059  ){
45060    rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
45061    pPager->changeCountDone = 0;
45062  }
45063  pPager->eState = PAGER_READER;
45064  pPager->setMaster = 0;
45065
45066  return (rc==SQLITE_OK?rc2:rc);
45067}
45068
45069/*
45070** Execute a rollback if a transaction is active and unlock the
45071** database file.
45072**
45073** If the pager has already entered the ERROR state, do not attempt
45074** the rollback at this time. Instead, pager_unlock() is called. The
45075** call to pager_unlock() will discard all in-memory pages, unlock
45076** the database file and move the pager back to OPEN state. If this
45077** means that there is a hot-journal left in the file-system, the next
45078** connection to obtain a shared lock on the pager (which may be this one)
45079** will roll it back.
45080**
45081** If the pager has not already entered the ERROR state, but an IO or
45082** malloc error occurs during a rollback, then this will itself cause
45083** the pager to enter the ERROR state. Which will be cleared by the
45084** call to pager_unlock(), as described above.
45085*/
45086static void pagerUnlockAndRollback(Pager *pPager){
45087  if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
45088    assert( assert_pager_state(pPager) );
45089    if( pPager->eState>=PAGER_WRITER_LOCKED ){
45090      sqlite3BeginBenignMalloc();
45091      sqlite3PagerRollback(pPager);
45092      sqlite3EndBenignMalloc();
45093    }else if( !pPager->exclusiveMode ){
45094      assert( pPager->eState==PAGER_READER );
45095      pager_end_transaction(pPager, 0, 0);
45096    }
45097  }
45098  pager_unlock(pPager);
45099}
45100
45101/*
45102** Parameter aData must point to a buffer of pPager->pageSize bytes
45103** of data. Compute and return a checksum based ont the contents of the
45104** page of data and the current value of pPager->cksumInit.
45105**
45106** This is not a real checksum. It is really just the sum of the
45107** random initial value (pPager->cksumInit) and every 200th byte
45108** of the page data, starting with byte offset (pPager->pageSize%200).
45109** Each byte is interpreted as an 8-bit unsigned integer.
45110**
45111** Changing the formula used to compute this checksum results in an
45112** incompatible journal file format.
45113**
45114** If journal corruption occurs due to a power failure, the most likely
45115** scenario is that one end or the other of the record will be changed.
45116** It is much less likely that the two ends of the journal record will be
45117** correct and the middle be corrupt.  Thus, this "checksum" scheme,
45118** though fast and simple, catches the mostly likely kind of corruption.
45119*/
45120static u32 pager_cksum(Pager *pPager, const u8 *aData){
45121  u32 cksum = pPager->cksumInit;         /* Checksum value to return */
45122  int i = pPager->pageSize-200;          /* Loop counter */
45123  while( i>0 ){
45124    cksum += aData[i];
45125    i -= 200;
45126  }
45127  return cksum;
45128}
45129
45130/*
45131** Report the current page size and number of reserved bytes back
45132** to the codec.
45133*/
45134#ifdef SQLITE_HAS_CODEC
45135static void pagerReportSize(Pager *pPager){
45136  if( pPager->xCodecSizeChng ){
45137    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
45138                           (int)pPager->nReserve);
45139  }
45140}
45141#else
45142# define pagerReportSize(X)     /* No-op if we do not support a codec */
45143#endif
45144
45145#ifdef SQLITE_HAS_CODEC
45146/*
45147** Make sure the number of reserved bits is the same in the destination
45148** pager as it is in the source.  This comes up when a VACUUM changes the
45149** number of reserved bits to the "optimal" amount.
45150*/
45151SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
45152  if( pDest->nReserve!=pSrc->nReserve ){
45153    pDest->nReserve = pSrc->nReserve;
45154    pagerReportSize(pDest);
45155  }
45156}
45157#endif
45158
45159/*
45160** Read a single page from either the journal file (if isMainJrnl==1) or
45161** from the sub-journal (if isMainJrnl==0) and playback that page.
45162** The page begins at offset *pOffset into the file. The *pOffset
45163** value is increased to the start of the next page in the journal.
45164**
45165** The main rollback journal uses checksums - the statement journal does
45166** not.
45167**
45168** If the page number of the page record read from the (sub-)journal file
45169** is greater than the current value of Pager.dbSize, then playback is
45170** skipped and SQLITE_OK is returned.
45171**
45172** If pDone is not NULL, then it is a record of pages that have already
45173** been played back.  If the page at *pOffset has already been played back
45174** (if the corresponding pDone bit is set) then skip the playback.
45175** Make sure the pDone bit corresponding to the *pOffset page is set
45176** prior to returning.
45177**
45178** If the page record is successfully read from the (sub-)journal file
45179** and played back, then SQLITE_OK is returned. If an IO error occurs
45180** while reading the record from the (sub-)journal file or while writing
45181** to the database file, then the IO error code is returned. If data
45182** is successfully read from the (sub-)journal file but appears to be
45183** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
45184** two circumstances:
45185**
45186**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
45187**   * If the record is being rolled back from the main journal file
45188**     and the checksum field does not match the record content.
45189**
45190** Neither of these two scenarios are possible during a savepoint rollback.
45191**
45192** If this is a savepoint rollback, then memory may have to be dynamically
45193** allocated by this function. If this is the case and an allocation fails,
45194** SQLITE_NOMEM is returned.
45195*/
45196static int pager_playback_one_page(
45197  Pager *pPager,                /* The pager being played back */
45198  i64 *pOffset,                 /* Offset of record to playback */
45199  Bitvec *pDone,                /* Bitvec of pages already played back */
45200  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
45201  int isSavepnt                 /* True for a savepoint rollback */
45202){
45203  int rc;
45204  PgHdr *pPg;                   /* An existing page in the cache */
45205  Pgno pgno;                    /* The page number of a page in journal */
45206  u32 cksum;                    /* Checksum used for sanity checking */
45207  char *aData;                  /* Temporary storage for the page */
45208  sqlite3_file *jfd;            /* The file descriptor for the journal file */
45209  int isSynced;                 /* True if journal page is synced */
45210
45211  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
45212  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
45213  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
45214  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
45215
45216  aData = pPager->pTmpSpace;
45217  assert( aData );         /* Temp storage must have already been allocated */
45218  assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
45219
45220  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
45221  ** or savepoint rollback done at the request of the caller) or this is
45222  ** a hot-journal rollback. If it is a hot-journal rollback, the pager
45223  ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
45224  ** only reads from the main journal, not the sub-journal.
45225  */
45226  assert( pPager->eState>=PAGER_WRITER_CACHEMOD
45227       || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
45228  );
45229  assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
45230
45231  /* Read the page number and page data from the journal or sub-journal
45232  ** file. Return an error code to the caller if an IO error occurs.
45233  */
45234  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
45235  rc = read32bits(jfd, *pOffset, &pgno);
45236  if( rc!=SQLITE_OK ) return rc;
45237  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
45238  if( rc!=SQLITE_OK ) return rc;
45239  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
45240
45241  /* Sanity checking on the page.  This is more important that I originally
45242  ** thought.  If a power failure occurs while the journal is being written,
45243  ** it could cause invalid data to be written into the journal.  We need to
45244  ** detect this invalid data (with high probability) and ignore it.
45245  */
45246  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
45247    assert( !isSavepnt );
45248    return SQLITE_DONE;
45249  }
45250  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
45251    return SQLITE_OK;
45252  }
45253  if( isMainJrnl ){
45254    rc = read32bits(jfd, (*pOffset)-4, &cksum);
45255    if( rc ) return rc;
45256    if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
45257      return SQLITE_DONE;
45258    }
45259  }
45260
45261  /* If this page has already been played back before during the current
45262  ** rollback, then don't bother to play it back again.
45263  */
45264  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
45265    return rc;
45266  }
45267
45268  /* When playing back page 1, restore the nReserve setting
45269  */
45270  if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
45271    pPager->nReserve = ((u8*)aData)[20];
45272    pagerReportSize(pPager);
45273  }
45274
45275  /* If the pager is in CACHEMOD state, then there must be a copy of this
45276  ** page in the pager cache. In this case just update the pager cache,
45277  ** not the database file. The page is left marked dirty in this case.
45278  **
45279  ** An exception to the above rule: If the database is in no-sync mode
45280  ** and a page is moved during an incremental vacuum then the page may
45281  ** not be in the pager cache. Later: if a malloc() or IO error occurs
45282  ** during a Movepage() call, then the page may not be in the cache
45283  ** either. So the condition described in the above paragraph is not
45284  ** assert()able.
45285  **
45286  ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
45287  ** pager cache if it exists and the main file. The page is then marked
45288  ** not dirty. Since this code is only executed in PAGER_OPEN state for
45289  ** a hot-journal rollback, it is guaranteed that the page-cache is empty
45290  ** if the pager is in OPEN state.
45291  **
45292  ** Ticket #1171:  The statement journal might contain page content that is
45293  ** different from the page content at the start of the transaction.
45294  ** This occurs when a page is changed prior to the start of a statement
45295  ** then changed again within the statement.  When rolling back such a
45296  ** statement we must not write to the original database unless we know
45297  ** for certain that original page contents are synced into the main rollback
45298  ** journal.  Otherwise, a power loss might leave modified data in the
45299  ** database file without an entry in the rollback journal that can
45300  ** restore the database to its original form.  Two conditions must be
45301  ** met before writing to the database files. (1) the database must be
45302  ** locked.  (2) we know that the original page content is fully synced
45303  ** in the main journal either because the page is not in cache or else
45304  ** the page is marked as needSync==0.
45305  **
45306  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
45307  ** is possible to fail a statement on a database that does not yet exist.
45308  ** Do not attempt to write if database file has never been opened.
45309  */
45310  if( pagerUseWal(pPager) ){
45311    pPg = 0;
45312  }else{
45313    pPg = sqlite3PagerLookup(pPager, pgno);
45314  }
45315  assert( pPg || !MEMDB );
45316  assert( pPager->eState!=PAGER_OPEN || pPg==0 );
45317  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
45318           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
45319           (isMainJrnl?"main-journal":"sub-journal")
45320  ));
45321  if( isMainJrnl ){
45322    isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
45323  }else{
45324    isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
45325  }
45326  if( isOpen(pPager->fd)
45327   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
45328   && isSynced
45329  ){
45330    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
45331    testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
45332    assert( !pagerUseWal(pPager) );
45333    rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
45334    if( pgno>pPager->dbFileSize ){
45335      pPager->dbFileSize = pgno;
45336    }
45337    if( pPager->pBackup ){
45338      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
45339      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
45340      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
45341    }
45342  }else if( !isMainJrnl && pPg==0 ){
45343    /* If this is a rollback of a savepoint and data was not written to
45344    ** the database and the page is not in-memory, there is a potential
45345    ** problem. When the page is next fetched by the b-tree layer, it
45346    ** will be read from the database file, which may or may not be
45347    ** current.
45348    **
45349    ** There are a couple of different ways this can happen. All are quite
45350    ** obscure. When running in synchronous mode, this can only happen
45351    ** if the page is on the free-list at the start of the transaction, then
45352    ** populated, then moved using sqlite3PagerMovepage().
45353    **
45354    ** The solution is to add an in-memory page to the cache containing
45355    ** the data just read from the sub-journal. Mark the page as dirty
45356    ** and if the pager requires a journal-sync, then mark the page as
45357    ** requiring a journal-sync before it is written.
45358    */
45359    assert( isSavepnt );
45360    assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
45361    pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
45362    rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
45363    assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
45364    pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
45365    if( rc!=SQLITE_OK ) return rc;
45366    pPg->flags &= ~PGHDR_NEED_READ;
45367    sqlite3PcacheMakeDirty(pPg);
45368  }
45369  if( pPg ){
45370    /* No page should ever be explicitly rolled back that is in use, except
45371    ** for page 1 which is held in use in order to keep the lock on the
45372    ** database active. However such a page may be rolled back as a result
45373    ** of an internal error resulting in an automatic call to
45374    ** sqlite3PagerRollback().
45375    */
45376    void *pData;
45377    pData = pPg->pData;
45378    memcpy(pData, (u8*)aData, pPager->pageSize);
45379    pPager->xReiniter(pPg);
45380    if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
45381      /* If the contents of this page were just restored from the main
45382      ** journal file, then its content must be as they were when the
45383      ** transaction was first opened. In this case we can mark the page
45384      ** as clean, since there will be no need to write it out to the
45385      ** database.
45386      **
45387      ** There is one exception to this rule. If the page is being rolled
45388      ** back as part of a savepoint (or statement) rollback from an
45389      ** unsynced portion of the main journal file, then it is not safe
45390      ** to mark the page as clean. This is because marking the page as
45391      ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
45392      ** already in the journal file (recorded in Pager.pInJournal) and
45393      ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
45394      ** again within this transaction, it will be marked as dirty but
45395      ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
45396      ** be written out into the database file before its journal file
45397      ** segment is synced. If a crash occurs during or following this,
45398      ** database corruption may ensue.
45399      */
45400      assert( !pagerUseWal(pPager) );
45401      sqlite3PcacheMakeClean(pPg);
45402    }
45403    pager_set_pagehash(pPg);
45404
45405    /* If this was page 1, then restore the value of Pager.dbFileVers.
45406    ** Do this before any decoding. */
45407    if( pgno==1 ){
45408      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
45409    }
45410
45411    /* Decode the page just read from disk */
45412    CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
45413    sqlite3PcacheRelease(pPg);
45414  }
45415  return rc;
45416}
45417
45418/*
45419** Parameter zMaster is the name of a master journal file. A single journal
45420** file that referred to the master journal file has just been rolled back.
45421** This routine checks if it is possible to delete the master journal file,
45422** and does so if it is.
45423**
45424** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
45425** available for use within this function.
45426**
45427** When a master journal file is created, it is populated with the names
45428** of all of its child journals, one after another, formatted as utf-8
45429** encoded text. The end of each child journal file is marked with a
45430** nul-terminator byte (0x00). i.e. the entire contents of a master journal
45431** file for a transaction involving two databases might be:
45432**
45433**   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
45434**
45435** A master journal file may only be deleted once all of its child
45436** journals have been rolled back.
45437**
45438** This function reads the contents of the master-journal file into
45439** memory and loops through each of the child journal names. For
45440** each child journal, it checks if:
45441**
45442**   * if the child journal exists, and if so
45443**   * if the child journal contains a reference to master journal
45444**     file zMaster
45445**
45446** If a child journal can be found that matches both of the criteria
45447** above, this function returns without doing anything. Otherwise, if
45448** no such child journal can be found, file zMaster is deleted from
45449** the file-system using sqlite3OsDelete().
45450**
45451** If an IO error within this function, an error code is returned. This
45452** function allocates memory by calling sqlite3Malloc(). If an allocation
45453** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
45454** occur, SQLITE_OK is returned.
45455**
45456** TODO: This function allocates a single block of memory to load
45457** the entire contents of the master journal file. This could be
45458** a couple of kilobytes or so - potentially larger than the page
45459** size.
45460*/
45461static int pager_delmaster(Pager *pPager, const char *zMaster){
45462  sqlite3_vfs *pVfs = pPager->pVfs;
45463  int rc;                   /* Return code */
45464  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
45465  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
45466  char *zMasterJournal = 0; /* Contents of master journal file */
45467  i64 nMasterJournal;       /* Size of master journal file */
45468  char *zJournal;           /* Pointer to one journal within MJ file */
45469  char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
45470  int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
45471
45472  /* Allocate space for both the pJournal and pMaster file descriptors.
45473  ** If successful, open the master journal file for reading.
45474  */
45475  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
45476  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
45477  if( !pMaster ){
45478    rc = SQLITE_NOMEM;
45479  }else{
45480    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
45481    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
45482  }
45483  if( rc!=SQLITE_OK ) goto delmaster_out;
45484
45485  /* Load the entire master journal file into space obtained from
45486  ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
45487  ** sufficient space (in zMasterPtr) to hold the names of master
45488  ** journal files extracted from regular rollback-journals.
45489  */
45490  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
45491  if( rc!=SQLITE_OK ) goto delmaster_out;
45492  nMasterPtr = pVfs->mxPathname+1;
45493  zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
45494  if( !zMasterJournal ){
45495    rc = SQLITE_NOMEM;
45496    goto delmaster_out;
45497  }
45498  zMasterPtr = &zMasterJournal[nMasterJournal+1];
45499  rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
45500  if( rc!=SQLITE_OK ) goto delmaster_out;
45501  zMasterJournal[nMasterJournal] = 0;
45502
45503  zJournal = zMasterJournal;
45504  while( (zJournal-zMasterJournal)<nMasterJournal ){
45505    int exists;
45506    rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
45507    if( rc!=SQLITE_OK ){
45508      goto delmaster_out;
45509    }
45510    if( exists ){
45511      /* One of the journals pointed to by the master journal exists.
45512      ** Open it and check if it points at the master journal. If
45513      ** so, return without deleting the master journal file.
45514      */
45515      int c;
45516      int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
45517      rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
45518      if( rc!=SQLITE_OK ){
45519        goto delmaster_out;
45520      }
45521
45522      rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
45523      sqlite3OsClose(pJournal);
45524      if( rc!=SQLITE_OK ){
45525        goto delmaster_out;
45526      }
45527
45528      c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
45529      if( c ){
45530        /* We have a match. Do not delete the master journal file. */
45531        goto delmaster_out;
45532      }
45533    }
45534    zJournal += (sqlite3Strlen30(zJournal)+1);
45535  }
45536
45537  sqlite3OsClose(pMaster);
45538  rc = sqlite3OsDelete(pVfs, zMaster, 0);
45539
45540delmaster_out:
45541  sqlite3_free(zMasterJournal);
45542  if( pMaster ){
45543    sqlite3OsClose(pMaster);
45544    assert( !isOpen(pJournal) );
45545    sqlite3_free(pMaster);
45546  }
45547  return rc;
45548}
45549
45550
45551/*
45552** This function is used to change the actual size of the database
45553** file in the file-system. This only happens when committing a transaction,
45554** or rolling back a transaction (including rolling back a hot-journal).
45555**
45556** If the main database file is not open, or the pager is not in either
45557** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
45558** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
45559** If the file on disk is currently larger than nPage pages, then use the VFS
45560** xTruncate() method to truncate it.
45561**
45562** Or, it might be the case that the file on disk is smaller than
45563** nPage pages. Some operating system implementations can get confused if
45564** you try to truncate a file to some size that is larger than it
45565** currently is, so detect this case and write a single zero byte to
45566** the end of the new file instead.
45567**
45568** If successful, return SQLITE_OK. If an IO error occurs while modifying
45569** the database file, return the error code to the caller.
45570*/
45571static int pager_truncate(Pager *pPager, Pgno nPage){
45572  int rc = SQLITE_OK;
45573  assert( pPager->eState!=PAGER_ERROR );
45574  assert( pPager->eState!=PAGER_READER );
45575
45576  if( isOpen(pPager->fd)
45577   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
45578  ){
45579    i64 currentSize, newSize;
45580    int szPage = pPager->pageSize;
45581    assert( pPager->eLock==EXCLUSIVE_LOCK );
45582    /* TODO: Is it safe to use Pager.dbFileSize here? */
45583    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
45584    newSize = szPage*(i64)nPage;
45585    if( rc==SQLITE_OK && currentSize!=newSize ){
45586      if( currentSize>newSize ){
45587        rc = sqlite3OsTruncate(pPager->fd, newSize);
45588      }else if( (currentSize+szPage)<=newSize ){
45589        char *pTmp = pPager->pTmpSpace;
45590        memset(pTmp, 0, szPage);
45591        testcase( (newSize-szPage) == currentSize );
45592        testcase( (newSize-szPage) >  currentSize );
45593        rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
45594      }
45595      if( rc==SQLITE_OK ){
45596        pPager->dbFileSize = nPage;
45597      }
45598    }
45599  }
45600  return rc;
45601}
45602
45603/*
45604** Return a sanitized version of the sector-size of OS file pFile. The
45605** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
45606*/
45607SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
45608  int iRet = sqlite3OsSectorSize(pFile);
45609  if( iRet<32 ){
45610    iRet = 512;
45611  }else if( iRet>MAX_SECTOR_SIZE ){
45612    assert( MAX_SECTOR_SIZE>=512 );
45613    iRet = MAX_SECTOR_SIZE;
45614  }
45615  return iRet;
45616}
45617
45618/*
45619** Set the value of the Pager.sectorSize variable for the given
45620** pager based on the value returned by the xSectorSize method
45621** of the open database file. The sector size will be used
45622** to determine the size and alignment of journal header and
45623** master journal pointers within created journal files.
45624**
45625** For temporary files the effective sector size is always 512 bytes.
45626**
45627** Otherwise, for non-temporary files, the effective sector size is
45628** the value returned by the xSectorSize() method rounded up to 32 if
45629** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
45630** is greater than MAX_SECTOR_SIZE.
45631**
45632** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
45633** the effective sector size to its minimum value (512).  The purpose of
45634** pPager->sectorSize is to define the "blast radius" of bytes that
45635** might change if a crash occurs while writing to a single byte in
45636** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
45637** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
45638** size.  For backwards compatibility of the rollback journal file format,
45639** we cannot reduce the effective sector size below 512.
45640*/
45641static void setSectorSize(Pager *pPager){
45642  assert( isOpen(pPager->fd) || pPager->tempFile );
45643
45644  if( pPager->tempFile
45645   || (sqlite3OsDeviceCharacteristics(pPager->fd) &
45646              SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
45647  ){
45648    /* Sector size doesn't matter for temporary files. Also, the file
45649    ** may not have been opened yet, in which case the OsSectorSize()
45650    ** call will segfault. */
45651    pPager->sectorSize = 512;
45652  }else{
45653    pPager->sectorSize = sqlite3SectorSize(pPager->fd);
45654  }
45655}
45656
45657/*
45658** Playback the journal and thus restore the database file to
45659** the state it was in before we started making changes.
45660**
45661** The journal file format is as follows:
45662**
45663**  (1)  8 byte prefix.  A copy of aJournalMagic[].
45664**  (2)  4 byte big-endian integer which is the number of valid page records
45665**       in the journal.  If this value is 0xffffffff, then compute the
45666**       number of page records from the journal size.
45667**  (3)  4 byte big-endian integer which is the initial value for the
45668**       sanity checksum.
45669**  (4)  4 byte integer which is the number of pages to truncate the
45670**       database to during a rollback.
45671**  (5)  4 byte big-endian integer which is the sector size.  The header
45672**       is this many bytes in size.
45673**  (6)  4 byte big-endian integer which is the page size.
45674**  (7)  zero padding out to the next sector size.
45675**  (8)  Zero or more pages instances, each as follows:
45676**        +  4 byte page number.
45677**        +  pPager->pageSize bytes of data.
45678**        +  4 byte checksum
45679**
45680** When we speak of the journal header, we mean the first 7 items above.
45681** Each entry in the journal is an instance of the 8th item.
45682**
45683** Call the value from the second bullet "nRec".  nRec is the number of
45684** valid page entries in the journal.  In most cases, you can compute the
45685** value of nRec from the size of the journal file.  But if a power
45686** failure occurred while the journal was being written, it could be the
45687** case that the size of the journal file had already been increased but
45688** the extra entries had not yet made it safely to disk.  In such a case,
45689** the value of nRec computed from the file size would be too large.  For
45690** that reason, we always use the nRec value in the header.
45691**
45692** If the nRec value is 0xffffffff it means that nRec should be computed
45693** from the file size.  This value is used when the user selects the
45694** no-sync option for the journal.  A power failure could lead to corruption
45695** in this case.  But for things like temporary table (which will be
45696** deleted when the power is restored) we don't care.
45697**
45698** If the file opened as the journal file is not a well-formed
45699** journal file then all pages up to the first corrupted page are rolled
45700** back (or no pages if the journal header is corrupted). The journal file
45701** is then deleted and SQLITE_OK returned, just as if no corruption had
45702** been encountered.
45703**
45704** If an I/O or malloc() error occurs, the journal-file is not deleted
45705** and an error code is returned.
45706**
45707** The isHot parameter indicates that we are trying to rollback a journal
45708** that might be a hot journal.  Or, it could be that the journal is
45709** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
45710** If the journal really is hot, reset the pager cache prior rolling
45711** back any content.  If the journal is merely persistent, no reset is
45712** needed.
45713*/
45714static int pager_playback(Pager *pPager, int isHot){
45715  sqlite3_vfs *pVfs = pPager->pVfs;
45716  i64 szJ;                 /* Size of the journal file in bytes */
45717  u32 nRec;                /* Number of Records in the journal */
45718  u32 u;                   /* Unsigned loop counter */
45719  Pgno mxPg = 0;           /* Size of the original file in pages */
45720  int rc;                  /* Result code of a subroutine */
45721  int res = 1;             /* Value returned by sqlite3OsAccess() */
45722  char *zMaster = 0;       /* Name of master journal file if any */
45723  int needPagerReset;      /* True to reset page prior to first page rollback */
45724  int nPlayback = 0;       /* Total number of pages restored from journal */
45725
45726  /* Figure out how many records are in the journal.  Abort early if
45727  ** the journal is empty.
45728  */
45729  assert( isOpen(pPager->jfd) );
45730  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
45731  if( rc!=SQLITE_OK ){
45732    goto end_playback;
45733  }
45734
45735  /* Read the master journal name from the journal, if it is present.
45736  ** If a master journal file name is specified, but the file is not
45737  ** present on disk, then the journal is not hot and does not need to be
45738  ** played back.
45739  **
45740  ** TODO: Technically the following is an error because it assumes that
45741  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
45742  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
45743  **  mxPathname is 512, which is the same as the minimum allowable value
45744  ** for pageSize.
45745  */
45746  zMaster = pPager->pTmpSpace;
45747  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
45748  if( rc==SQLITE_OK && zMaster[0] ){
45749    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
45750  }
45751  zMaster = 0;
45752  if( rc!=SQLITE_OK || !res ){
45753    goto end_playback;
45754  }
45755  pPager->journalOff = 0;
45756  needPagerReset = isHot;
45757
45758  /* This loop terminates either when a readJournalHdr() or
45759  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
45760  ** occurs.
45761  */
45762  while( 1 ){
45763    /* Read the next journal header from the journal file.  If there are
45764    ** not enough bytes left in the journal file for a complete header, or
45765    ** it is corrupted, then a process must have failed while writing it.
45766    ** This indicates nothing more needs to be rolled back.
45767    */
45768    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
45769    if( rc!=SQLITE_OK ){
45770      if( rc==SQLITE_DONE ){
45771        rc = SQLITE_OK;
45772      }
45773      goto end_playback;
45774    }
45775
45776    /* If nRec is 0xffffffff, then this journal was created by a process
45777    ** working in no-sync mode. This means that the rest of the journal
45778    ** file consists of pages, there are no more journal headers. Compute
45779    ** the value of nRec based on this assumption.
45780    */
45781    if( nRec==0xffffffff ){
45782      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
45783      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
45784    }
45785
45786    /* If nRec is 0 and this rollback is of a transaction created by this
45787    ** process and if this is the final header in the journal, then it means
45788    ** that this part of the journal was being filled but has not yet been
45789    ** synced to disk.  Compute the number of pages based on the remaining
45790    ** size of the file.
45791    **
45792    ** The third term of the test was added to fix ticket #2565.
45793    ** When rolling back a hot journal, nRec==0 always means that the next
45794    ** chunk of the journal contains zero pages to be rolled back.  But
45795    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
45796    ** the journal, it means that the journal might contain additional
45797    ** pages that need to be rolled back and that the number of pages
45798    ** should be computed based on the journal file size.
45799    */
45800    if( nRec==0 && !isHot &&
45801        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
45802      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
45803    }
45804
45805    /* If this is the first header read from the journal, truncate the
45806    ** database file back to its original size.
45807    */
45808    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
45809      rc = pager_truncate(pPager, mxPg);
45810      if( rc!=SQLITE_OK ){
45811        goto end_playback;
45812      }
45813      pPager->dbSize = mxPg;
45814    }
45815
45816    /* Copy original pages out of the journal and back into the
45817    ** database file and/or page cache.
45818    */
45819    for(u=0; u<nRec; u++){
45820      if( needPagerReset ){
45821        pager_reset(pPager);
45822        needPagerReset = 0;
45823      }
45824      rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
45825      if( rc==SQLITE_OK ){
45826        nPlayback++;
45827      }else{
45828        if( rc==SQLITE_DONE ){
45829          pPager->journalOff = szJ;
45830          break;
45831        }else if( rc==SQLITE_IOERR_SHORT_READ ){
45832          /* If the journal has been truncated, simply stop reading and
45833          ** processing the journal. This might happen if the journal was
45834          ** not completely written and synced prior to a crash.  In that
45835          ** case, the database should have never been written in the
45836          ** first place so it is OK to simply abandon the rollback. */
45837          rc = SQLITE_OK;
45838          goto end_playback;
45839        }else{
45840          /* If we are unable to rollback, quit and return the error
45841          ** code.  This will cause the pager to enter the error state
45842          ** so that no further harm will be done.  Perhaps the next
45843          ** process to come along will be able to rollback the database.
45844          */
45845          goto end_playback;
45846        }
45847      }
45848    }
45849  }
45850  /*NOTREACHED*/
45851  assert( 0 );
45852
45853end_playback:
45854  /* Following a rollback, the database file should be back in its original
45855  ** state prior to the start of the transaction, so invoke the
45856  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
45857  ** assertion that the transaction counter was modified.
45858  */
45859#ifdef SQLITE_DEBUG
45860  if( pPager->fd->pMethods ){
45861    sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
45862  }
45863#endif
45864
45865  /* If this playback is happening automatically as a result of an IO or
45866  ** malloc error that occurred after the change-counter was updated but
45867  ** before the transaction was committed, then the change-counter
45868  ** modification may just have been reverted. If this happens in exclusive
45869  ** mode, then subsequent transactions performed by the connection will not
45870  ** update the change-counter at all. This may lead to cache inconsistency
45871  ** problems for other processes at some point in the future. So, just
45872  ** in case this has happened, clear the changeCountDone flag now.
45873  */
45874  pPager->changeCountDone = pPager->tempFile;
45875
45876  if( rc==SQLITE_OK ){
45877    zMaster = pPager->pTmpSpace;
45878    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
45879    testcase( rc!=SQLITE_OK );
45880  }
45881  if( rc==SQLITE_OK
45882   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
45883  ){
45884    rc = sqlite3PagerSync(pPager, 0);
45885  }
45886  if( rc==SQLITE_OK ){
45887    rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
45888    testcase( rc!=SQLITE_OK );
45889  }
45890  if( rc==SQLITE_OK && zMaster[0] && res ){
45891    /* If there was a master journal and this routine will return success,
45892    ** see if it is possible to delete the master journal.
45893    */
45894    rc = pager_delmaster(pPager, zMaster);
45895    testcase( rc!=SQLITE_OK );
45896  }
45897  if( isHot && nPlayback ){
45898    sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
45899                nPlayback, pPager->zJournal);
45900  }
45901
45902  /* The Pager.sectorSize variable may have been updated while rolling
45903  ** back a journal created by a process with a different sector size
45904  ** value. Reset it to the correct value for this process.
45905  */
45906  setSectorSize(pPager);
45907  return rc;
45908}
45909
45910
45911/*
45912** Read the content for page pPg out of the database file and into
45913** pPg->pData. A shared lock or greater must be held on the database
45914** file before this function is called.
45915**
45916** If page 1 is read, then the value of Pager.dbFileVers[] is set to
45917** the value read from the database file.
45918**
45919** If an IO error occurs, then the IO error is returned to the caller.
45920** Otherwise, SQLITE_OK is returned.
45921*/
45922static int readDbPage(PgHdr *pPg, u32 iFrame){
45923  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
45924  Pgno pgno = pPg->pgno;       /* Page number to read */
45925  int rc = SQLITE_OK;          /* Return code */
45926  int pgsz = pPager->pageSize; /* Number of bytes to read */
45927
45928  assert( pPager->eState>=PAGER_READER && !MEMDB );
45929  assert( isOpen(pPager->fd) );
45930
45931#ifndef SQLITE_OMIT_WAL
45932  if( iFrame ){
45933    /* Try to pull the page from the write-ahead log. */
45934    rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
45935  }else
45936#endif
45937  {
45938    i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
45939    rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
45940    if( rc==SQLITE_IOERR_SHORT_READ ){
45941      rc = SQLITE_OK;
45942    }
45943  }
45944
45945  if( pgno==1 ){
45946    if( rc ){
45947      /* If the read is unsuccessful, set the dbFileVers[] to something
45948      ** that will never be a valid file version.  dbFileVers[] is a copy
45949      ** of bytes 24..39 of the database.  Bytes 28..31 should always be
45950      ** zero or the size of the database in page. Bytes 32..35 and 35..39
45951      ** should be page numbers which are never 0xffffffff.  So filling
45952      ** pPager->dbFileVers[] with all 0xff bytes should suffice.
45953      **
45954      ** For an encrypted database, the situation is more complex:  bytes
45955      ** 24..39 of the database are white noise.  But the probability of
45956      ** white noise equaling 16 bytes of 0xff is vanishingly small so
45957      ** we should still be ok.
45958      */
45959      memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
45960    }else{
45961      u8 *dbFileVers = &((u8*)pPg->pData)[24];
45962      memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
45963    }
45964  }
45965  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
45966
45967  PAGER_INCR(sqlite3_pager_readdb_count);
45968  PAGER_INCR(pPager->nRead);
45969  IOTRACE(("PGIN %p %d\n", pPager, pgno));
45970  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
45971               PAGERID(pPager), pgno, pager_pagehash(pPg)));
45972
45973  return rc;
45974}
45975
45976/*
45977** Update the value of the change-counter at offsets 24 and 92 in
45978** the header and the sqlite version number at offset 96.
45979**
45980** This is an unconditional update.  See also the pager_incr_changecounter()
45981** routine which only updates the change-counter if the update is actually
45982** needed, as determined by the pPager->changeCountDone state variable.
45983*/
45984static void pager_write_changecounter(PgHdr *pPg){
45985  u32 change_counter;
45986
45987  /* Increment the value just read and write it back to byte 24. */
45988  change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
45989  put32bits(((char*)pPg->pData)+24, change_counter);
45990
45991  /* Also store the SQLite version number in bytes 96..99 and in
45992  ** bytes 92..95 store the change counter for which the version number
45993  ** is valid. */
45994  put32bits(((char*)pPg->pData)+92, change_counter);
45995  put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
45996}
45997
45998#ifndef SQLITE_OMIT_WAL
45999/*
46000** This function is invoked once for each page that has already been
46001** written into the log file when a WAL transaction is rolled back.
46002** Parameter iPg is the page number of said page. The pCtx argument
46003** is actually a pointer to the Pager structure.
46004**
46005** If page iPg is present in the cache, and has no outstanding references,
46006** it is discarded. Otherwise, if there are one or more outstanding
46007** references, the page content is reloaded from the database. If the
46008** attempt to reload content from the database is required and fails,
46009** return an SQLite error code. Otherwise, SQLITE_OK.
46010*/
46011static int pagerUndoCallback(void *pCtx, Pgno iPg){
46012  int rc = SQLITE_OK;
46013  Pager *pPager = (Pager *)pCtx;
46014  PgHdr *pPg;
46015
46016  assert( pagerUseWal(pPager) );
46017  pPg = sqlite3PagerLookup(pPager, iPg);
46018  if( pPg ){
46019    if( sqlite3PcachePageRefcount(pPg)==1 ){
46020      sqlite3PcacheDrop(pPg);
46021    }else{
46022      u32 iFrame = 0;
46023      rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
46024      if( rc==SQLITE_OK ){
46025        rc = readDbPage(pPg, iFrame);
46026      }
46027      if( rc==SQLITE_OK ){
46028        pPager->xReiniter(pPg);
46029      }
46030      sqlite3PagerUnrefNotNull(pPg);
46031    }
46032  }
46033
46034  /* Normally, if a transaction is rolled back, any backup processes are
46035  ** updated as data is copied out of the rollback journal and into the
46036  ** database. This is not generally possible with a WAL database, as
46037  ** rollback involves simply truncating the log file. Therefore, if one
46038  ** or more frames have already been written to the log (and therefore
46039  ** also copied into the backup databases) as part of this transaction,
46040  ** the backups must be restarted.
46041  */
46042  sqlite3BackupRestart(pPager->pBackup);
46043
46044  return rc;
46045}
46046
46047/*
46048** This function is called to rollback a transaction on a WAL database.
46049*/
46050static int pagerRollbackWal(Pager *pPager){
46051  int rc;                         /* Return Code */
46052  PgHdr *pList;                   /* List of dirty pages to revert */
46053
46054  /* For all pages in the cache that are currently dirty or have already
46055  ** been written (but not committed) to the log file, do one of the
46056  ** following:
46057  **
46058  **   + Discard the cached page (if refcount==0), or
46059  **   + Reload page content from the database (if refcount>0).
46060  */
46061  pPager->dbSize = pPager->dbOrigSize;
46062  rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
46063  pList = sqlite3PcacheDirtyList(pPager->pPCache);
46064  while( pList && rc==SQLITE_OK ){
46065    PgHdr *pNext = pList->pDirty;
46066    rc = pagerUndoCallback((void *)pPager, pList->pgno);
46067    pList = pNext;
46068  }
46069
46070  return rc;
46071}
46072
46073/*
46074** This function is a wrapper around sqlite3WalFrames(). As well as logging
46075** the contents of the list of pages headed by pList (connected by pDirty),
46076** this function notifies any active backup processes that the pages have
46077** changed.
46078**
46079** The list of pages passed into this routine is always sorted by page number.
46080** Hence, if page 1 appears anywhere on the list, it will be the first page.
46081*/
46082static int pagerWalFrames(
46083  Pager *pPager,                  /* Pager object */
46084  PgHdr *pList,                   /* List of frames to log */
46085  Pgno nTruncate,                 /* Database size after this commit */
46086  int isCommit                    /* True if this is a commit */
46087){
46088  int rc;                         /* Return code */
46089  int nList;                      /* Number of pages in pList */
46090  PgHdr *p;                       /* For looping over pages */
46091
46092  assert( pPager->pWal );
46093  assert( pList );
46094#ifdef SQLITE_DEBUG
46095  /* Verify that the page list is in accending order */
46096  for(p=pList; p && p->pDirty; p=p->pDirty){
46097    assert( p->pgno < p->pDirty->pgno );
46098  }
46099#endif
46100
46101  assert( pList->pDirty==0 || isCommit );
46102  if( isCommit ){
46103    /* If a WAL transaction is being committed, there is no point in writing
46104    ** any pages with page numbers greater than nTruncate into the WAL file.
46105    ** They will never be read by any client. So remove them from the pDirty
46106    ** list here. */
46107    PgHdr **ppNext = &pList;
46108    nList = 0;
46109    for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
46110      if( p->pgno<=nTruncate ){
46111        ppNext = &p->pDirty;
46112        nList++;
46113      }
46114    }
46115    assert( pList );
46116  }else{
46117    nList = 1;
46118  }
46119  pPager->aStat[PAGER_STAT_WRITE] += nList;
46120
46121  if( pList->pgno==1 ) pager_write_changecounter(pList);
46122  rc = sqlite3WalFrames(pPager->pWal,
46123      pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
46124  );
46125  if( rc==SQLITE_OK && pPager->pBackup ){
46126    for(p=pList; p; p=p->pDirty){
46127      sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
46128    }
46129  }
46130
46131#ifdef SQLITE_CHECK_PAGES
46132  pList = sqlite3PcacheDirtyList(pPager->pPCache);
46133  for(p=pList; p; p=p->pDirty){
46134    pager_set_pagehash(p);
46135  }
46136#endif
46137
46138  return rc;
46139}
46140
46141/*
46142** Begin a read transaction on the WAL.
46143**
46144** This routine used to be called "pagerOpenSnapshot()" because it essentially
46145** makes a snapshot of the database at the current point in time and preserves
46146** that snapshot for use by the reader in spite of concurrently changes by
46147** other writers or checkpointers.
46148*/
46149static int pagerBeginReadTransaction(Pager *pPager){
46150  int rc;                         /* Return code */
46151  int changed = 0;                /* True if cache must be reset */
46152
46153  assert( pagerUseWal(pPager) );
46154  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
46155
46156  /* sqlite3WalEndReadTransaction() was not called for the previous
46157  ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
46158  ** are in locking_mode=NORMAL and EndRead() was previously called,
46159  ** the duplicate call is harmless.
46160  */
46161  sqlite3WalEndReadTransaction(pPager->pWal);
46162
46163  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
46164  if( rc!=SQLITE_OK || changed ){
46165    pager_reset(pPager);
46166    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
46167  }
46168
46169  return rc;
46170}
46171#endif
46172
46173/*
46174** This function is called as part of the transition from PAGER_OPEN
46175** to PAGER_READER state to determine the size of the database file
46176** in pages (assuming the page size currently stored in Pager.pageSize).
46177**
46178** If no error occurs, SQLITE_OK is returned and the size of the database
46179** in pages is stored in *pnPage. Otherwise, an error code (perhaps
46180** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
46181*/
46182static int pagerPagecount(Pager *pPager, Pgno *pnPage){
46183  Pgno nPage;                     /* Value to return via *pnPage */
46184
46185  /* Query the WAL sub-system for the database size. The WalDbsize()
46186  ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
46187  ** if the database size is not available. The database size is not
46188  ** available from the WAL sub-system if the log file is empty or
46189  ** contains no valid committed transactions.
46190  */
46191  assert( pPager->eState==PAGER_OPEN );
46192  assert( pPager->eLock>=SHARED_LOCK );
46193  nPage = sqlite3WalDbsize(pPager->pWal);
46194
46195  /* If the number of pages in the database is not available from the
46196  ** WAL sub-system, determine the page counte based on the size of
46197  ** the database file.  If the size of the database file is not an
46198  ** integer multiple of the page-size, round up the result.
46199  */
46200  if( nPage==0 ){
46201    i64 n = 0;                    /* Size of db file in bytes */
46202    assert( isOpen(pPager->fd) || pPager->tempFile );
46203    if( isOpen(pPager->fd) ){
46204      int rc = sqlite3OsFileSize(pPager->fd, &n);
46205      if( rc!=SQLITE_OK ){
46206        return rc;
46207      }
46208    }
46209    nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
46210  }
46211
46212  /* If the current number of pages in the file is greater than the
46213  ** configured maximum pager number, increase the allowed limit so
46214  ** that the file can be read.
46215  */
46216  if( nPage>pPager->mxPgno ){
46217    pPager->mxPgno = (Pgno)nPage;
46218  }
46219
46220  *pnPage = nPage;
46221  return SQLITE_OK;
46222}
46223
46224#ifndef SQLITE_OMIT_WAL
46225/*
46226** Check if the *-wal file that corresponds to the database opened by pPager
46227** exists if the database is not empy, or verify that the *-wal file does
46228** not exist (by deleting it) if the database file is empty.
46229**
46230** If the database is not empty and the *-wal file exists, open the pager
46231** in WAL mode.  If the database is empty or if no *-wal file exists and
46232** if no error occurs, make sure Pager.journalMode is not set to
46233** PAGER_JOURNALMODE_WAL.
46234**
46235** Return SQLITE_OK or an error code.
46236**
46237** The caller must hold a SHARED lock on the database file to call this
46238** function. Because an EXCLUSIVE lock on the db file is required to delete
46239** a WAL on a none-empty database, this ensures there is no race condition
46240** between the xAccess() below and an xDelete() being executed by some
46241** other connection.
46242*/
46243static int pagerOpenWalIfPresent(Pager *pPager){
46244  int rc = SQLITE_OK;
46245  assert( pPager->eState==PAGER_OPEN );
46246  assert( pPager->eLock>=SHARED_LOCK );
46247
46248  if( !pPager->tempFile ){
46249    int isWal;                    /* True if WAL file exists */
46250    Pgno nPage;                   /* Size of the database file */
46251
46252    rc = pagerPagecount(pPager, &nPage);
46253    if( rc ) return rc;
46254    if( nPage==0 ){
46255      rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
46256      if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
46257      isWal = 0;
46258    }else{
46259      rc = sqlite3OsAccess(
46260          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
46261      );
46262    }
46263    if( rc==SQLITE_OK ){
46264      if( isWal ){
46265        testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
46266        rc = sqlite3PagerOpenWal(pPager, 0);
46267      }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
46268        pPager->journalMode = PAGER_JOURNALMODE_DELETE;
46269      }
46270    }
46271  }
46272  return rc;
46273}
46274#endif
46275
46276/*
46277** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
46278** the entire master journal file. The case pSavepoint==NULL occurs when
46279** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
46280** savepoint.
46281**
46282** When pSavepoint is not NULL (meaning a non-transaction savepoint is
46283** being rolled back), then the rollback consists of up to three stages,
46284** performed in the order specified:
46285**
46286**   * Pages are played back from the main journal starting at byte
46287**     offset PagerSavepoint.iOffset and continuing to
46288**     PagerSavepoint.iHdrOffset, or to the end of the main journal
46289**     file if PagerSavepoint.iHdrOffset is zero.
46290**
46291**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
46292**     back starting from the journal header immediately following
46293**     PagerSavepoint.iHdrOffset to the end of the main journal file.
46294**
46295**   * Pages are then played back from the sub-journal file, starting
46296**     with the PagerSavepoint.iSubRec and continuing to the end of
46297**     the journal file.
46298**
46299** Throughout the rollback process, each time a page is rolled back, the
46300** corresponding bit is set in a bitvec structure (variable pDone in the
46301** implementation below). This is used to ensure that a page is only
46302** rolled back the first time it is encountered in either journal.
46303**
46304** If pSavepoint is NULL, then pages are only played back from the main
46305** journal file. There is no need for a bitvec in this case.
46306**
46307** In either case, before playback commences the Pager.dbSize variable
46308** is reset to the value that it held at the start of the savepoint
46309** (or transaction). No page with a page-number greater than this value
46310** is played back. If one is encountered it is simply skipped.
46311*/
46312static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
46313  i64 szJ;                 /* Effective size of the main journal */
46314  i64 iHdrOff;             /* End of first segment of main-journal records */
46315  int rc = SQLITE_OK;      /* Return code */
46316  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
46317
46318  assert( pPager->eState!=PAGER_ERROR );
46319  assert( pPager->eState>=PAGER_WRITER_LOCKED );
46320
46321  /* Allocate a bitvec to use to store the set of pages rolled back */
46322  if( pSavepoint ){
46323    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
46324    if( !pDone ){
46325      return SQLITE_NOMEM;
46326    }
46327  }
46328
46329  /* Set the database size back to the value it was before the savepoint
46330  ** being reverted was opened.
46331  */
46332  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
46333  pPager->changeCountDone = pPager->tempFile;
46334
46335  if( !pSavepoint && pagerUseWal(pPager) ){
46336    return pagerRollbackWal(pPager);
46337  }
46338
46339  /* Use pPager->journalOff as the effective size of the main rollback
46340  ** journal.  The actual file might be larger than this in
46341  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
46342  ** past pPager->journalOff is off-limits to us.
46343  */
46344  szJ = pPager->journalOff;
46345  assert( pagerUseWal(pPager)==0 || szJ==0 );
46346
46347  /* Begin by rolling back records from the main journal starting at
46348  ** PagerSavepoint.iOffset and continuing to the next journal header.
46349  ** There might be records in the main journal that have a page number
46350  ** greater than the current database size (pPager->dbSize) but those
46351  ** will be skipped automatically.  Pages are added to pDone as they
46352  ** are played back.
46353  */
46354  if( pSavepoint && !pagerUseWal(pPager) ){
46355    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
46356    pPager->journalOff = pSavepoint->iOffset;
46357    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
46358      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
46359    }
46360    assert( rc!=SQLITE_DONE );
46361  }else{
46362    pPager->journalOff = 0;
46363  }
46364
46365  /* Continue rolling back records out of the main journal starting at
46366  ** the first journal header seen and continuing until the effective end
46367  ** of the main journal file.  Continue to skip out-of-range pages and
46368  ** continue adding pages rolled back to pDone.
46369  */
46370  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
46371    u32 ii;            /* Loop counter */
46372    u32 nJRec = 0;     /* Number of Journal Records */
46373    u32 dummy;
46374    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
46375    assert( rc!=SQLITE_DONE );
46376
46377    /*
46378    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
46379    ** test is related to ticket #2565.  See the discussion in the
46380    ** pager_playback() function for additional information.
46381    */
46382    if( nJRec==0
46383     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
46384    ){
46385      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
46386    }
46387    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
46388      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
46389    }
46390    assert( rc!=SQLITE_DONE );
46391  }
46392  assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
46393
46394  /* Finally,  rollback pages from the sub-journal.  Page that were
46395  ** previously rolled back out of the main journal (and are hence in pDone)
46396  ** will be skipped.  Out-of-range pages are also skipped.
46397  */
46398  if( pSavepoint ){
46399    u32 ii;            /* Loop counter */
46400    i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
46401
46402    if( pagerUseWal(pPager) ){
46403      rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
46404    }
46405    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
46406      assert( offset==(i64)ii*(4+pPager->pageSize) );
46407      rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
46408    }
46409    assert( rc!=SQLITE_DONE );
46410  }
46411
46412  sqlite3BitvecDestroy(pDone);
46413  if( rc==SQLITE_OK ){
46414    pPager->journalOff = szJ;
46415  }
46416
46417  return rc;
46418}
46419
46420/*
46421** Change the maximum number of in-memory pages that are allowed.
46422*/
46423SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
46424  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
46425}
46426
46427/*
46428** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
46429*/
46430static void pagerFixMaplimit(Pager *pPager){
46431#if SQLITE_MAX_MMAP_SIZE>0
46432  sqlite3_file *fd = pPager->fd;
46433  if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
46434    sqlite3_int64 sz;
46435    sz = pPager->szMmap;
46436    pPager->bUseFetch = (sz>0);
46437    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
46438  }
46439#endif
46440}
46441
46442/*
46443** Change the maximum size of any memory mapping made of the database file.
46444*/
46445SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
46446  pPager->szMmap = szMmap;
46447  pagerFixMaplimit(pPager);
46448}
46449
46450/*
46451** Free as much memory as possible from the pager.
46452*/
46453SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
46454  sqlite3PcacheShrink(pPager->pPCache);
46455}
46456
46457/*
46458** Adjust settings of the pager to those specified in the pgFlags parameter.
46459**
46460** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
46461** of the database to damage due to OS crashes or power failures by
46462** changing the number of syncs()s when writing the journals.
46463** There are three levels:
46464**
46465**    OFF       sqlite3OsSync() is never called.  This is the default
46466**              for temporary and transient files.
46467**
46468**    NORMAL    The journal is synced once before writes begin on the
46469**              database.  This is normally adequate protection, but
46470**              it is theoretically possible, though very unlikely,
46471**              that an inopertune power failure could leave the journal
46472**              in a state which would cause damage to the database
46473**              when it is rolled back.
46474**
46475**    FULL      The journal is synced twice before writes begin on the
46476**              database (with some additional information - the nRec field
46477**              of the journal header - being written in between the two
46478**              syncs).  If we assume that writing a
46479**              single disk sector is atomic, then this mode provides
46480**              assurance that the journal will not be corrupted to the
46481**              point of causing damage to the database during rollback.
46482**
46483** The above is for a rollback-journal mode.  For WAL mode, OFF continues
46484** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
46485** prior to the start of checkpoint and that the database file is synced
46486** at the conclusion of the checkpoint if the entire content of the WAL
46487** was written back into the database.  But no sync operations occur for
46488** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
46489** file is synced following each commit operation, in addition to the
46490** syncs associated with NORMAL.
46491**
46492** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
46493** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
46494** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
46495** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
46496** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
46497** synchronous=FULL versus synchronous=NORMAL setting determines when
46498** the xSync primitive is called and is relevant to all platforms.
46499**
46500** Numeric values associated with these states are OFF==1, NORMAL=2,
46501** and FULL=3.
46502*/
46503#ifndef SQLITE_OMIT_PAGER_PRAGMAS
46504SQLITE_PRIVATE void sqlite3PagerSetFlags(
46505  Pager *pPager,        /* The pager to set safety level for */
46506  unsigned pgFlags      /* Various flags */
46507){
46508  unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
46509  assert( level>=1 && level<=3 );
46510  pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
46511  pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
46512  if( pPager->noSync ){
46513    pPager->syncFlags = 0;
46514    pPager->ckptSyncFlags = 0;
46515  }else if( pgFlags & PAGER_FULLFSYNC ){
46516    pPager->syncFlags = SQLITE_SYNC_FULL;
46517    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
46518  }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
46519    pPager->syncFlags = SQLITE_SYNC_NORMAL;
46520    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
46521  }else{
46522    pPager->syncFlags = SQLITE_SYNC_NORMAL;
46523    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
46524  }
46525  pPager->walSyncFlags = pPager->syncFlags;
46526  if( pPager->fullSync ){
46527    pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
46528  }
46529  if( pgFlags & PAGER_CACHESPILL ){
46530    pPager->doNotSpill &= ~SPILLFLAG_OFF;
46531  }else{
46532    pPager->doNotSpill |= SPILLFLAG_OFF;
46533  }
46534}
46535#endif
46536
46537/*
46538** The following global variable is incremented whenever the library
46539** attempts to open a temporary file.  This information is used for
46540** testing and analysis only.
46541*/
46542#ifdef SQLITE_TEST
46543SQLITE_API int sqlite3_opentemp_count = 0;
46544#endif
46545
46546/*
46547** Open a temporary file.
46548**
46549** Write the file descriptor into *pFile. Return SQLITE_OK on success
46550** or some other error code if we fail. The OS will automatically
46551** delete the temporary file when it is closed.
46552**
46553** The flags passed to the VFS layer xOpen() call are those specified
46554** by parameter vfsFlags ORed with the following:
46555**
46556**     SQLITE_OPEN_READWRITE
46557**     SQLITE_OPEN_CREATE
46558**     SQLITE_OPEN_EXCLUSIVE
46559**     SQLITE_OPEN_DELETEONCLOSE
46560*/
46561static int pagerOpentemp(
46562  Pager *pPager,        /* The pager object */
46563  sqlite3_file *pFile,  /* Write the file descriptor here */
46564  int vfsFlags          /* Flags passed through to the VFS */
46565){
46566  int rc;               /* Return code */
46567
46568#ifdef SQLITE_TEST
46569  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
46570#endif
46571
46572  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
46573            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
46574  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
46575  assert( rc!=SQLITE_OK || isOpen(pFile) );
46576  return rc;
46577}
46578
46579/*
46580** Set the busy handler function.
46581**
46582** The pager invokes the busy-handler if sqlite3OsLock() returns
46583** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
46584** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
46585** lock. It does *not* invoke the busy handler when upgrading from
46586** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
46587** (which occurs during hot-journal rollback). Summary:
46588**
46589**   Transition                        | Invokes xBusyHandler
46590**   --------------------------------------------------------
46591**   NO_LOCK       -> SHARED_LOCK      | Yes
46592**   SHARED_LOCK   -> RESERVED_LOCK    | No
46593**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
46594**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
46595**
46596** If the busy-handler callback returns non-zero, the lock is
46597** retried. If it returns zero, then the SQLITE_BUSY error is
46598** returned to the caller of the pager API function.
46599*/
46600SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
46601  Pager *pPager,                       /* Pager object */
46602  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
46603  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
46604){
46605  pPager->xBusyHandler = xBusyHandler;
46606  pPager->pBusyHandlerArg = pBusyHandlerArg;
46607
46608  if( isOpen(pPager->fd) ){
46609    void **ap = (void **)&pPager->xBusyHandler;
46610    assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
46611    assert( ap[1]==pBusyHandlerArg );
46612    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
46613  }
46614}
46615
46616/*
46617** Change the page size used by the Pager object. The new page size
46618** is passed in *pPageSize.
46619**
46620** If the pager is in the error state when this function is called, it
46621** is a no-op. The value returned is the error state error code (i.e.
46622** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
46623**
46624** Otherwise, if all of the following are true:
46625**
46626**   * the new page size (value of *pPageSize) is valid (a power
46627**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
46628**
46629**   * there are no outstanding page references, and
46630**
46631**   * the database is either not an in-memory database or it is
46632**     an in-memory database that currently consists of zero pages.
46633**
46634** then the pager object page size is set to *pPageSize.
46635**
46636** If the page size is changed, then this function uses sqlite3PagerMalloc()
46637** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
46638** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
46639** In all other cases, SQLITE_OK is returned.
46640**
46641** If the page size is not changed, either because one of the enumerated
46642** conditions above is not true, the pager was in error state when this
46643** function was called, or because the memory allocation attempt failed,
46644** then *pPageSize is set to the old, retained page size before returning.
46645*/
46646SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
46647  int rc = SQLITE_OK;
46648
46649  /* It is not possible to do a full assert_pager_state() here, as this
46650  ** function may be called from within PagerOpen(), before the state
46651  ** of the Pager object is internally consistent.
46652  **
46653  ** At one point this function returned an error if the pager was in
46654  ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
46655  ** there is at least one outstanding page reference, this function
46656  ** is a no-op for that case anyhow.
46657  */
46658
46659  u32 pageSize = *pPageSize;
46660  assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
46661  if( (pPager->memDb==0 || pPager->dbSize==0)
46662   && sqlite3PcacheRefCount(pPager->pPCache)==0
46663   && pageSize && pageSize!=(u32)pPager->pageSize
46664  ){
46665    char *pNew = NULL;             /* New temp space */
46666    i64 nByte = 0;
46667
46668    if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
46669      rc = sqlite3OsFileSize(pPager->fd, &nByte);
46670    }
46671    if( rc==SQLITE_OK ){
46672      pNew = (char *)sqlite3PageMalloc(pageSize);
46673      if( !pNew ) rc = SQLITE_NOMEM;
46674    }
46675
46676    if( rc==SQLITE_OK ){
46677      pager_reset(pPager);
46678      rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
46679    }
46680    if( rc==SQLITE_OK ){
46681      sqlite3PageFree(pPager->pTmpSpace);
46682      pPager->pTmpSpace = pNew;
46683      pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
46684      pPager->pageSize = pageSize;
46685    }else{
46686      sqlite3PageFree(pNew);
46687    }
46688  }
46689
46690  *pPageSize = pPager->pageSize;
46691  if( rc==SQLITE_OK ){
46692    if( nReserve<0 ) nReserve = pPager->nReserve;
46693    assert( nReserve>=0 && nReserve<1000 );
46694    pPager->nReserve = (i16)nReserve;
46695    pagerReportSize(pPager);
46696    pagerFixMaplimit(pPager);
46697  }
46698  return rc;
46699}
46700
46701/*
46702** Return a pointer to the "temporary page" buffer held internally
46703** by the pager.  This is a buffer that is big enough to hold the
46704** entire content of a database page.  This buffer is used internally
46705** during rollback and will be overwritten whenever a rollback
46706** occurs.  But other modules are free to use it too, as long as
46707** no rollbacks are happening.
46708*/
46709SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
46710  return pPager->pTmpSpace;
46711}
46712
46713/*
46714** Attempt to set the maximum database page count if mxPage is positive.
46715** Make no changes if mxPage is zero or negative.  And never reduce the
46716** maximum page count below the current size of the database.
46717**
46718** Regardless of mxPage, return the current maximum page count.
46719*/
46720SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
46721  if( mxPage>0 ){
46722    pPager->mxPgno = mxPage;
46723  }
46724  assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
46725  assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
46726  return pPager->mxPgno;
46727}
46728
46729/*
46730** The following set of routines are used to disable the simulated
46731** I/O error mechanism.  These routines are used to avoid simulated
46732** errors in places where we do not care about errors.
46733**
46734** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
46735** and generate no code.
46736*/
46737#ifdef SQLITE_TEST
46738SQLITE_API extern int sqlite3_io_error_pending;
46739SQLITE_API extern int sqlite3_io_error_hit;
46740static int saved_cnt;
46741void disable_simulated_io_errors(void){
46742  saved_cnt = sqlite3_io_error_pending;
46743  sqlite3_io_error_pending = -1;
46744}
46745void enable_simulated_io_errors(void){
46746  sqlite3_io_error_pending = saved_cnt;
46747}
46748#else
46749# define disable_simulated_io_errors()
46750# define enable_simulated_io_errors()
46751#endif
46752
46753/*
46754** Read the first N bytes from the beginning of the file into memory
46755** that pDest points to.
46756**
46757** If the pager was opened on a transient file (zFilename==""), or
46758** opened on a file less than N bytes in size, the output buffer is
46759** zeroed and SQLITE_OK returned. The rationale for this is that this
46760** function is used to read database headers, and a new transient or
46761** zero sized database has a header than consists entirely of zeroes.
46762**
46763** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
46764** the error code is returned to the caller and the contents of the
46765** output buffer undefined.
46766*/
46767SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
46768  int rc = SQLITE_OK;
46769  memset(pDest, 0, N);
46770  assert( isOpen(pPager->fd) || pPager->tempFile );
46771
46772  /* This routine is only called by btree immediately after creating
46773  ** the Pager object.  There has not been an opportunity to transition
46774  ** to WAL mode yet.
46775  */
46776  assert( !pagerUseWal(pPager) );
46777
46778  if( isOpen(pPager->fd) ){
46779    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
46780    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
46781    if( rc==SQLITE_IOERR_SHORT_READ ){
46782      rc = SQLITE_OK;
46783    }
46784  }
46785  return rc;
46786}
46787
46788/*
46789** This function may only be called when a read-transaction is open on
46790** the pager. It returns the total number of pages in the database.
46791**
46792** However, if the file is between 1 and <page-size> bytes in size, then
46793** this is considered a 1 page file.
46794*/
46795SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
46796  assert( pPager->eState>=PAGER_READER );
46797  assert( pPager->eState!=PAGER_WRITER_FINISHED );
46798  *pnPage = (int)pPager->dbSize;
46799}
46800
46801
46802/*
46803** Try to obtain a lock of type locktype on the database file. If
46804** a similar or greater lock is already held, this function is a no-op
46805** (returning SQLITE_OK immediately).
46806**
46807** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
46808** the busy callback if the lock is currently not available. Repeat
46809** until the busy callback returns false or until the attempt to
46810** obtain the lock succeeds.
46811**
46812** Return SQLITE_OK on success and an error code if we cannot obtain
46813** the lock. If the lock is obtained successfully, set the Pager.state
46814** variable to locktype before returning.
46815*/
46816static int pager_wait_on_lock(Pager *pPager, int locktype){
46817  int rc;                              /* Return code */
46818
46819  /* Check that this is either a no-op (because the requested lock is
46820  ** already held), or one of the transitions that the busy-handler
46821  ** may be invoked during, according to the comment above
46822  ** sqlite3PagerSetBusyhandler().
46823  */
46824  assert( (pPager->eLock>=locktype)
46825       || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
46826       || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
46827  );
46828
46829  do {
46830    rc = pagerLockDb(pPager, locktype);
46831  }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
46832  return rc;
46833}
46834
46835/*
46836** Function assertTruncateConstraint(pPager) checks that one of the
46837** following is true for all dirty pages currently in the page-cache:
46838**
46839**   a) The page number is less than or equal to the size of the
46840**      current database image, in pages, OR
46841**
46842**   b) if the page content were written at this time, it would not
46843**      be necessary to write the current content out to the sub-journal
46844**      (as determined by function subjRequiresPage()).
46845**
46846** If the condition asserted by this function were not true, and the
46847** dirty page were to be discarded from the cache via the pagerStress()
46848** routine, pagerStress() would not write the current page content to
46849** the database file. If a savepoint transaction were rolled back after
46850** this happened, the correct behavior would be to restore the current
46851** content of the page. However, since this content is not present in either
46852** the database file or the portion of the rollback journal and
46853** sub-journal rolled back the content could not be restored and the
46854** database image would become corrupt. It is therefore fortunate that
46855** this circumstance cannot arise.
46856*/
46857#if defined(SQLITE_DEBUG)
46858static void assertTruncateConstraintCb(PgHdr *pPg){
46859  assert( pPg->flags&PGHDR_DIRTY );
46860  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
46861}
46862static void assertTruncateConstraint(Pager *pPager){
46863  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
46864}
46865#else
46866# define assertTruncateConstraint(pPager)
46867#endif
46868
46869/*
46870** Truncate the in-memory database file image to nPage pages. This
46871** function does not actually modify the database file on disk. It
46872** just sets the internal state of the pager object so that the
46873** truncation will be done when the current transaction is committed.
46874**
46875** This function is only called right before committing a transaction.
46876** Once this function has been called, the transaction must either be
46877** rolled back or committed. It is not safe to call this function and
46878** then continue writing to the database.
46879*/
46880SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
46881  assert( pPager->dbSize>=nPage );
46882  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
46883  pPager->dbSize = nPage;
46884
46885  /* At one point the code here called assertTruncateConstraint() to
46886  ** ensure that all pages being truncated away by this operation are,
46887  ** if one or more savepoints are open, present in the savepoint
46888  ** journal so that they can be restored if the savepoint is rolled
46889  ** back. This is no longer necessary as this function is now only
46890  ** called right before committing a transaction. So although the
46891  ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
46892  ** they cannot be rolled back. So the assertTruncateConstraint() call
46893  ** is no longer correct. */
46894}
46895
46896
46897/*
46898** This function is called before attempting a hot-journal rollback. It
46899** syncs the journal file to disk, then sets pPager->journalHdr to the
46900** size of the journal file so that the pager_playback() routine knows
46901** that the entire journal file has been synced.
46902**
46903** Syncing a hot-journal to disk before attempting to roll it back ensures
46904** that if a power-failure occurs during the rollback, the process that
46905** attempts rollback following system recovery sees the same journal
46906** content as this process.
46907**
46908** If everything goes as planned, SQLITE_OK is returned. Otherwise,
46909** an SQLite error code.
46910*/
46911static int pagerSyncHotJournal(Pager *pPager){
46912  int rc = SQLITE_OK;
46913  if( !pPager->noSync ){
46914    rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
46915  }
46916  if( rc==SQLITE_OK ){
46917    rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
46918  }
46919  return rc;
46920}
46921
46922/*
46923** Obtain a reference to a memory mapped page object for page number pgno.
46924** The new object will use the pointer pData, obtained from xFetch().
46925** If successful, set *ppPage to point to the new page reference
46926** and return SQLITE_OK. Otherwise, return an SQLite error code and set
46927** *ppPage to zero.
46928**
46929** Page references obtained by calling this function should be released
46930** by calling pagerReleaseMapPage().
46931*/
46932static int pagerAcquireMapPage(
46933  Pager *pPager,                  /* Pager object */
46934  Pgno pgno,                      /* Page number */
46935  void *pData,                    /* xFetch()'d data for this page */
46936  PgHdr **ppPage                  /* OUT: Acquired page object */
46937){
46938  PgHdr *p;                       /* Memory mapped page to return */
46939
46940  if( pPager->pMmapFreelist ){
46941    *ppPage = p = pPager->pMmapFreelist;
46942    pPager->pMmapFreelist = p->pDirty;
46943    p->pDirty = 0;
46944    memset(p->pExtra, 0, pPager->nExtra);
46945  }else{
46946    *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
46947    if( p==0 ){
46948      sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
46949      return SQLITE_NOMEM;
46950    }
46951    p->pExtra = (void *)&p[1];
46952    p->flags = PGHDR_MMAP;
46953    p->nRef = 1;
46954    p->pPager = pPager;
46955  }
46956
46957  assert( p->pExtra==(void *)&p[1] );
46958  assert( p->pPage==0 );
46959  assert( p->flags==PGHDR_MMAP );
46960  assert( p->pPager==pPager );
46961  assert( p->nRef==1 );
46962
46963  p->pgno = pgno;
46964  p->pData = pData;
46965  pPager->nMmapOut++;
46966
46967  return SQLITE_OK;
46968}
46969
46970/*
46971** Release a reference to page pPg. pPg must have been returned by an
46972** earlier call to pagerAcquireMapPage().
46973*/
46974static void pagerReleaseMapPage(PgHdr *pPg){
46975  Pager *pPager = pPg->pPager;
46976  pPager->nMmapOut--;
46977  pPg->pDirty = pPager->pMmapFreelist;
46978  pPager->pMmapFreelist = pPg;
46979
46980  assert( pPager->fd->pMethods->iVersion>=3 );
46981  sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
46982}
46983
46984/*
46985** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
46986*/
46987static void pagerFreeMapHdrs(Pager *pPager){
46988  PgHdr *p;
46989  PgHdr *pNext;
46990  for(p=pPager->pMmapFreelist; p; p=pNext){
46991    pNext = p->pDirty;
46992    sqlite3_free(p);
46993  }
46994}
46995
46996
46997/*
46998** Shutdown the page cache.  Free all memory and close all files.
46999**
47000** If a transaction was in progress when this routine is called, that
47001** transaction is rolled back.  All outstanding pages are invalidated
47002** and their memory is freed.  Any attempt to use a page associated
47003** with this page cache after this function returns will likely
47004** result in a coredump.
47005**
47006** This function always succeeds. If a transaction is active an attempt
47007** is made to roll it back. If an error occurs during the rollback
47008** a hot journal may be left in the filesystem but no error is returned
47009** to the caller.
47010*/
47011SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
47012  u8 *pTmp = (u8 *)pPager->pTmpSpace;
47013
47014  assert( assert_pager_state(pPager) );
47015  disable_simulated_io_errors();
47016  sqlite3BeginBenignMalloc();
47017  pagerFreeMapHdrs(pPager);
47018  /* pPager->errCode = 0; */
47019  pPager->exclusiveMode = 0;
47020#ifndef SQLITE_OMIT_WAL
47021  sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
47022  pPager->pWal = 0;
47023#endif
47024  pager_reset(pPager);
47025  if( MEMDB ){
47026    pager_unlock(pPager);
47027  }else{
47028    /* If it is open, sync the journal file before calling UnlockAndRollback.
47029    ** If this is not done, then an unsynced portion of the open journal
47030    ** file may be played back into the database. If a power failure occurs
47031    ** while this is happening, the database could become corrupt.
47032    **
47033    ** If an error occurs while trying to sync the journal, shift the pager
47034    ** into the ERROR state. This causes UnlockAndRollback to unlock the
47035    ** database and close the journal file without attempting to roll it
47036    ** back or finalize it. The next database user will have to do hot-journal
47037    ** rollback before accessing the database file.
47038    */
47039    if( isOpen(pPager->jfd) ){
47040      pager_error(pPager, pagerSyncHotJournal(pPager));
47041    }
47042    pagerUnlockAndRollback(pPager);
47043  }
47044  sqlite3EndBenignMalloc();
47045  enable_simulated_io_errors();
47046  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
47047  IOTRACE(("CLOSE %p\n", pPager))
47048  sqlite3OsClose(pPager->jfd);
47049  sqlite3OsClose(pPager->fd);
47050  sqlite3PageFree(pTmp);
47051  sqlite3PcacheClose(pPager->pPCache);
47052
47053#ifdef SQLITE_HAS_CODEC
47054  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
47055#endif
47056
47057  assert( !pPager->aSavepoint && !pPager->pInJournal );
47058  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
47059
47060  sqlite3_free(pPager);
47061  return SQLITE_OK;
47062}
47063
47064#if !defined(NDEBUG) || defined(SQLITE_TEST)
47065/*
47066** Return the page number for page pPg.
47067*/
47068SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
47069  return pPg->pgno;
47070}
47071#endif
47072
47073/*
47074** Increment the reference count for page pPg.
47075*/
47076SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
47077  sqlite3PcacheRef(pPg);
47078}
47079
47080/*
47081** Sync the journal. In other words, make sure all the pages that have
47082** been written to the journal have actually reached the surface of the
47083** disk and can be restored in the event of a hot-journal rollback.
47084**
47085** If the Pager.noSync flag is set, then this function is a no-op.
47086** Otherwise, the actions required depend on the journal-mode and the
47087** device characteristics of the file-system, as follows:
47088**
47089**   * If the journal file is an in-memory journal file, no action need
47090**     be taken.
47091**
47092**   * Otherwise, if the device does not support the SAFE_APPEND property,
47093**     then the nRec field of the most recently written journal header
47094**     is updated to contain the number of journal records that have
47095**     been written following it. If the pager is operating in full-sync
47096**     mode, then the journal file is synced before this field is updated.
47097**
47098**   * If the device does not support the SEQUENTIAL property, then
47099**     journal file is synced.
47100**
47101** Or, in pseudo-code:
47102**
47103**   if( NOT <in-memory journal> ){
47104**     if( NOT SAFE_APPEND ){
47105**       if( <full-sync mode> ) xSync(<journal file>);
47106**       <update nRec field>
47107**     }
47108**     if( NOT SEQUENTIAL ) xSync(<journal file>);
47109**   }
47110**
47111** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
47112** page currently held in memory before returning SQLITE_OK. If an IO
47113** error is encountered, then the IO error code is returned to the caller.
47114*/
47115static int syncJournal(Pager *pPager, int newHdr){
47116  int rc;                         /* Return code */
47117
47118  assert( pPager->eState==PAGER_WRITER_CACHEMOD
47119       || pPager->eState==PAGER_WRITER_DBMOD
47120  );
47121  assert( assert_pager_state(pPager) );
47122  assert( !pagerUseWal(pPager) );
47123
47124  rc = sqlite3PagerExclusiveLock(pPager);
47125  if( rc!=SQLITE_OK ) return rc;
47126
47127  if( !pPager->noSync ){
47128    assert( !pPager->tempFile );
47129    if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
47130      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
47131      assert( isOpen(pPager->jfd) );
47132
47133      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
47134        /* This block deals with an obscure problem. If the last connection
47135        ** that wrote to this database was operating in persistent-journal
47136        ** mode, then the journal file may at this point actually be larger
47137        ** than Pager.journalOff bytes. If the next thing in the journal
47138        ** file happens to be a journal-header (written as part of the
47139        ** previous connection's transaction), and a crash or power-failure
47140        ** occurs after nRec is updated but before this connection writes
47141        ** anything else to the journal file (or commits/rolls back its
47142        ** transaction), then SQLite may become confused when doing the
47143        ** hot-journal rollback following recovery. It may roll back all
47144        ** of this connections data, then proceed to rolling back the old,
47145        ** out-of-date data that follows it. Database corruption.
47146        **
47147        ** To work around this, if the journal file does appear to contain
47148        ** a valid header following Pager.journalOff, then write a 0x00
47149        ** byte to the start of it to prevent it from being recognized.
47150        **
47151        ** Variable iNextHdrOffset is set to the offset at which this
47152        ** problematic header will occur, if it exists. aMagic is used
47153        ** as a temporary buffer to inspect the first couple of bytes of
47154        ** the potential journal header.
47155        */
47156        i64 iNextHdrOffset;
47157        u8 aMagic[8];
47158        u8 zHeader[sizeof(aJournalMagic)+4];
47159
47160        memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
47161        put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
47162
47163        iNextHdrOffset = journalHdrOffset(pPager);
47164        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
47165        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
47166          static const u8 zerobyte = 0;
47167          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
47168        }
47169        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
47170          return rc;
47171        }
47172
47173        /* Write the nRec value into the journal file header. If in
47174        ** full-synchronous mode, sync the journal first. This ensures that
47175        ** all data has really hit the disk before nRec is updated to mark
47176        ** it as a candidate for rollback.
47177        **
47178        ** This is not required if the persistent media supports the
47179        ** SAFE_APPEND property. Because in this case it is not possible
47180        ** for garbage data to be appended to the file, the nRec field
47181        ** is populated with 0xFFFFFFFF when the journal header is written
47182        ** and never needs to be updated.
47183        */
47184        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
47185          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
47186          IOTRACE(("JSYNC %p\n", pPager))
47187          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
47188          if( rc!=SQLITE_OK ) return rc;
47189        }
47190        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
47191        rc = sqlite3OsWrite(
47192            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
47193        );
47194        if( rc!=SQLITE_OK ) return rc;
47195      }
47196      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
47197        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
47198        IOTRACE(("JSYNC %p\n", pPager))
47199        rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
47200          (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
47201        );
47202        if( rc!=SQLITE_OK ) return rc;
47203      }
47204
47205      pPager->journalHdr = pPager->journalOff;
47206      if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
47207        pPager->nRec = 0;
47208        rc = writeJournalHdr(pPager);
47209        if( rc!=SQLITE_OK ) return rc;
47210      }
47211    }else{
47212      pPager->journalHdr = pPager->journalOff;
47213    }
47214  }
47215
47216  /* Unless the pager is in noSync mode, the journal file was just
47217  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
47218  ** all pages.
47219  */
47220  sqlite3PcacheClearSyncFlags(pPager->pPCache);
47221  pPager->eState = PAGER_WRITER_DBMOD;
47222  assert( assert_pager_state(pPager) );
47223  return SQLITE_OK;
47224}
47225
47226/*
47227** The argument is the first in a linked list of dirty pages connected
47228** by the PgHdr.pDirty pointer. This function writes each one of the
47229** in-memory pages in the list to the database file. The argument may
47230** be NULL, representing an empty list. In this case this function is
47231** a no-op.
47232**
47233** The pager must hold at least a RESERVED lock when this function
47234** is called. Before writing anything to the database file, this lock
47235** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
47236** SQLITE_BUSY is returned and no data is written to the database file.
47237**
47238** If the pager is a temp-file pager and the actual file-system file
47239** is not yet open, it is created and opened before any data is
47240** written out.
47241**
47242** Once the lock has been upgraded and, if necessary, the file opened,
47243** the pages are written out to the database file in list order. Writing
47244** a page is skipped if it meets either of the following criteria:
47245**
47246**   * The page number is greater than Pager.dbSize, or
47247**   * The PGHDR_DONT_WRITE flag is set on the page.
47248**
47249** If writing out a page causes the database file to grow, Pager.dbFileSize
47250** is updated accordingly. If page 1 is written out, then the value cached
47251** in Pager.dbFileVers[] is updated to match the new value stored in
47252** the database file.
47253**
47254** If everything is successful, SQLITE_OK is returned. If an IO error
47255** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
47256** be obtained, SQLITE_BUSY is returned.
47257*/
47258static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
47259  int rc = SQLITE_OK;                  /* Return code */
47260
47261  /* This function is only called for rollback pagers in WRITER_DBMOD state. */
47262  assert( !pagerUseWal(pPager) );
47263  assert( pPager->eState==PAGER_WRITER_DBMOD );
47264  assert( pPager->eLock==EXCLUSIVE_LOCK );
47265
47266  /* If the file is a temp-file has not yet been opened, open it now. It
47267  ** is not possible for rc to be other than SQLITE_OK if this branch
47268  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
47269  */
47270  if( !isOpen(pPager->fd) ){
47271    assert( pPager->tempFile && rc==SQLITE_OK );
47272    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
47273  }
47274
47275  /* Before the first write, give the VFS a hint of what the final
47276  ** file size will be.
47277  */
47278  assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
47279  if( rc==SQLITE_OK
47280   && pPager->dbHintSize<pPager->dbSize
47281   && (pList->pDirty || pList->pgno>pPager->dbHintSize)
47282  ){
47283    sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
47284    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
47285    pPager->dbHintSize = pPager->dbSize;
47286  }
47287
47288  while( rc==SQLITE_OK && pList ){
47289    Pgno pgno = pList->pgno;
47290
47291    /* If there are dirty pages in the page cache with page numbers greater
47292    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
47293    ** make the file smaller (presumably by auto-vacuum code). Do not write
47294    ** any such pages to the file.
47295    **
47296    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
47297    ** set (set by sqlite3PagerDontWrite()).
47298    */
47299    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
47300      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
47301      char *pData;                                   /* Data to write */
47302
47303      assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
47304      if( pList->pgno==1 ) pager_write_changecounter(pList);
47305
47306      /* Encode the database */
47307      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
47308
47309      /* Write out the page data. */
47310      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
47311
47312      /* If page 1 was just written, update Pager.dbFileVers to match
47313      ** the value now stored in the database file. If writing this
47314      ** page caused the database file to grow, update dbFileSize.
47315      */
47316      if( pgno==1 ){
47317        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
47318      }
47319      if( pgno>pPager->dbFileSize ){
47320        pPager->dbFileSize = pgno;
47321      }
47322      pPager->aStat[PAGER_STAT_WRITE]++;
47323
47324      /* Update any backup objects copying the contents of this pager. */
47325      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
47326
47327      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
47328                   PAGERID(pPager), pgno, pager_pagehash(pList)));
47329      IOTRACE(("PGOUT %p %d\n", pPager, pgno));
47330      PAGER_INCR(sqlite3_pager_writedb_count);
47331    }else{
47332      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
47333    }
47334    pager_set_pagehash(pList);
47335    pList = pList->pDirty;
47336  }
47337
47338  return rc;
47339}
47340
47341/*
47342** Ensure that the sub-journal file is open. If it is already open, this
47343** function is a no-op.
47344**
47345** SQLITE_OK is returned if everything goes according to plan. An
47346** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
47347** fails.
47348*/
47349static int openSubJournal(Pager *pPager){
47350  int rc = SQLITE_OK;
47351  if( !isOpen(pPager->sjfd) ){
47352    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
47353      sqlite3MemJournalOpen(pPager->sjfd);
47354    }else{
47355      rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
47356    }
47357  }
47358  return rc;
47359}
47360
47361/*
47362** Append a record of the current state of page pPg to the sub-journal.
47363**
47364** If successful, set the bit corresponding to pPg->pgno in the bitvecs
47365** for all open savepoints before returning.
47366**
47367** This function returns SQLITE_OK if everything is successful, an IO
47368** error code if the attempt to write to the sub-journal fails, or
47369** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
47370** bitvec.
47371*/
47372static int subjournalPage(PgHdr *pPg){
47373  int rc = SQLITE_OK;
47374  Pager *pPager = pPg->pPager;
47375  if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
47376
47377    /* Open the sub-journal, if it has not already been opened */
47378    assert( pPager->useJournal );
47379    assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
47380    assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
47381    assert( pagerUseWal(pPager)
47382         || pageInJournal(pPager, pPg)
47383         || pPg->pgno>pPager->dbOrigSize
47384    );
47385    rc = openSubJournal(pPager);
47386
47387    /* If the sub-journal was opened successfully (or was already open),
47388    ** write the journal record into the file.  */
47389    if( rc==SQLITE_OK ){
47390      void *pData = pPg->pData;
47391      i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
47392      char *pData2;
47393
47394      CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
47395      PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
47396      rc = write32bits(pPager->sjfd, offset, pPg->pgno);
47397      if( rc==SQLITE_OK ){
47398        rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
47399      }
47400    }
47401  }
47402  if( rc==SQLITE_OK ){
47403    pPager->nSubRec++;
47404    assert( pPager->nSavepoint>0 );
47405    rc = addToSavepointBitvecs(pPager, pPg->pgno);
47406  }
47407  return rc;
47408}
47409static int subjournalPageIfRequired(PgHdr *pPg){
47410  if( subjRequiresPage(pPg) ){
47411    return subjournalPage(pPg);
47412  }else{
47413    return SQLITE_OK;
47414  }
47415}
47416
47417/*
47418** This function is called by the pcache layer when it has reached some
47419** soft memory limit. The first argument is a pointer to a Pager object
47420** (cast as a void*). The pager is always 'purgeable' (not an in-memory
47421** database). The second argument is a reference to a page that is
47422** currently dirty but has no outstanding references. The page
47423** is always associated with the Pager object passed as the first
47424** argument.
47425**
47426** The job of this function is to make pPg clean by writing its contents
47427** out to the database file, if possible. This may involve syncing the
47428** journal file.
47429**
47430** If successful, sqlite3PcacheMakeClean() is called on the page and
47431** SQLITE_OK returned. If an IO error occurs while trying to make the
47432** page clean, the IO error code is returned. If the page cannot be
47433** made clean for some other reason, but no error occurs, then SQLITE_OK
47434** is returned by sqlite3PcacheMakeClean() is not called.
47435*/
47436static int pagerStress(void *p, PgHdr *pPg){
47437  Pager *pPager = (Pager *)p;
47438  int rc = SQLITE_OK;
47439
47440  assert( pPg->pPager==pPager );
47441  assert( pPg->flags&PGHDR_DIRTY );
47442
47443  /* The doNotSpill NOSYNC bit is set during times when doing a sync of
47444  ** journal (and adding a new header) is not allowed.  This occurs
47445  ** during calls to sqlite3PagerWrite() while trying to journal multiple
47446  ** pages belonging to the same sector.
47447  **
47448  ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
47449  ** regardless of whether or not a sync is required.  This is set during
47450  ** a rollback or by user request, respectively.
47451  **
47452  ** Spilling is also prohibited when in an error state since that could
47453  ** lead to database corruption.   In the current implementation it
47454  ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
47455  ** while in the error state, hence it is impossible for this routine to
47456  ** be called in the error state.  Nevertheless, we include a NEVER()
47457  ** test for the error state as a safeguard against future changes.
47458  */
47459  if( NEVER(pPager->errCode) ) return SQLITE_OK;
47460  testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
47461  testcase( pPager->doNotSpill & SPILLFLAG_OFF );
47462  testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
47463  if( pPager->doNotSpill
47464   && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
47465      || (pPg->flags & PGHDR_NEED_SYNC)!=0)
47466  ){
47467    return SQLITE_OK;
47468  }
47469
47470  pPg->pDirty = 0;
47471  if( pagerUseWal(pPager) ){
47472    /* Write a single frame for this page to the log. */
47473    rc = subjournalPageIfRequired(pPg);
47474    if( rc==SQLITE_OK ){
47475      rc = pagerWalFrames(pPager, pPg, 0, 0);
47476    }
47477  }else{
47478
47479    /* Sync the journal file if required. */
47480    if( pPg->flags&PGHDR_NEED_SYNC
47481     || pPager->eState==PAGER_WRITER_CACHEMOD
47482    ){
47483      rc = syncJournal(pPager, 1);
47484    }
47485
47486    /* Write the contents of the page out to the database file. */
47487    if( rc==SQLITE_OK ){
47488      assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
47489      rc = pager_write_pagelist(pPager, pPg);
47490    }
47491  }
47492
47493  /* Mark the page as clean. */
47494  if( rc==SQLITE_OK ){
47495    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
47496    sqlite3PcacheMakeClean(pPg);
47497  }
47498
47499  return pager_error(pPager, rc);
47500}
47501
47502
47503/*
47504** Allocate and initialize a new Pager object and put a pointer to it
47505** in *ppPager. The pager should eventually be freed by passing it
47506** to sqlite3PagerClose().
47507**
47508** The zFilename argument is the path to the database file to open.
47509** If zFilename is NULL then a randomly-named temporary file is created
47510** and used as the file to be cached. Temporary files are be deleted
47511** automatically when they are closed. If zFilename is ":memory:" then
47512** all information is held in cache. It is never written to disk.
47513** This can be used to implement an in-memory database.
47514**
47515** The nExtra parameter specifies the number of bytes of space allocated
47516** along with each page reference. This space is available to the user
47517** via the sqlite3PagerGetExtra() API.
47518**
47519** The flags argument is used to specify properties that affect the
47520** operation of the pager. It should be passed some bitwise combination
47521** of the PAGER_* flags.
47522**
47523** The vfsFlags parameter is a bitmask to pass to the flags parameter
47524** of the xOpen() method of the supplied VFS when opening files.
47525**
47526** If the pager object is allocated and the specified file opened
47527** successfully, SQLITE_OK is returned and *ppPager set to point to
47528** the new pager object. If an error occurs, *ppPager is set to NULL
47529** and error code returned. This function may return SQLITE_NOMEM
47530** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
47531** various SQLITE_IO_XXX errors.
47532*/
47533SQLITE_PRIVATE int sqlite3PagerOpen(
47534  sqlite3_vfs *pVfs,       /* The virtual file system to use */
47535  Pager **ppPager,         /* OUT: Return the Pager structure here */
47536  const char *zFilename,   /* Name of the database file to open */
47537  int nExtra,              /* Extra bytes append to each in-memory page */
47538  int flags,               /* flags controlling this file */
47539  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
47540  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
47541){
47542  u8 *pPtr;
47543  Pager *pPager = 0;       /* Pager object to allocate and return */
47544  int rc = SQLITE_OK;      /* Return code */
47545  int tempFile = 0;        /* True for temp files (incl. in-memory files) */
47546  int memDb = 0;           /* True if this is an in-memory file */
47547  int readOnly = 0;        /* True if this is a read-only file */
47548  int journalFileSize;     /* Bytes to allocate for each journal fd */
47549  char *zPathname = 0;     /* Full path to database file */
47550  int nPathname = 0;       /* Number of bytes in zPathname */
47551  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
47552  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
47553  u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
47554  const char *zUri = 0;    /* URI args to copy */
47555  int nUri = 0;            /* Number of bytes of URI args at *zUri */
47556
47557  /* Figure out how much space is required for each journal file-handle
47558  ** (there are two of them, the main journal and the sub-journal). This
47559  ** is the maximum space required for an in-memory journal file handle
47560  ** and a regular journal file-handle. Note that a "regular journal-handle"
47561  ** may be a wrapper capable of caching the first portion of the journal
47562  ** file in memory to implement the atomic-write optimization (see
47563  ** source file journal.c).
47564  */
47565  if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
47566    journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
47567  }else{
47568    journalFileSize = ROUND8(sqlite3MemJournalSize());
47569  }
47570
47571  /* Set the output variable to NULL in case an error occurs. */
47572  *ppPager = 0;
47573
47574#ifndef SQLITE_OMIT_MEMORYDB
47575  if( flags & PAGER_MEMORY ){
47576    memDb = 1;
47577    if( zFilename && zFilename[0] ){
47578      zPathname = sqlite3DbStrDup(0, zFilename);
47579      if( zPathname==0  ) return SQLITE_NOMEM;
47580      nPathname = sqlite3Strlen30(zPathname);
47581      zFilename = 0;
47582    }
47583  }
47584#endif
47585
47586  /* Compute and store the full pathname in an allocated buffer pointed
47587  ** to by zPathname, length nPathname. Or, if this is a temporary file,
47588  ** leave both nPathname and zPathname set to 0.
47589  */
47590  if( zFilename && zFilename[0] ){
47591    const char *z;
47592    nPathname = pVfs->mxPathname+1;
47593    zPathname = sqlite3DbMallocRaw(0, nPathname*2);
47594    if( zPathname==0 ){
47595      return SQLITE_NOMEM;
47596    }
47597    zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
47598    rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
47599    nPathname = sqlite3Strlen30(zPathname);
47600    z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
47601    while( *z ){
47602      z += sqlite3Strlen30(z)+1;
47603      z += sqlite3Strlen30(z)+1;
47604    }
47605    nUri = (int)(&z[1] - zUri);
47606    assert( nUri>=0 );
47607    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
47608      /* This branch is taken when the journal path required by
47609      ** the database being opened will be more than pVfs->mxPathname
47610      ** bytes in length. This means the database cannot be opened,
47611      ** as it will not be possible to open the journal file or even
47612      ** check for a hot-journal before reading.
47613      */
47614      rc = SQLITE_CANTOPEN_BKPT;
47615    }
47616    if( rc!=SQLITE_OK ){
47617      sqlite3DbFree(0, zPathname);
47618      return rc;
47619    }
47620  }
47621
47622  /* Allocate memory for the Pager structure, PCache object, the
47623  ** three file descriptors, the database file name and the journal
47624  ** file name. The layout in memory is as follows:
47625  **
47626  **     Pager object                    (sizeof(Pager) bytes)
47627  **     PCache object                   (sqlite3PcacheSize() bytes)
47628  **     Database file handle            (pVfs->szOsFile bytes)
47629  **     Sub-journal file handle         (journalFileSize bytes)
47630  **     Main journal file handle        (journalFileSize bytes)
47631  **     Database file name              (nPathname+1 bytes)
47632  **     Journal file name               (nPathname+8+1 bytes)
47633  */
47634  pPtr = (u8 *)sqlite3MallocZero(
47635    ROUND8(sizeof(*pPager)) +      /* Pager structure */
47636    ROUND8(pcacheSize) +           /* PCache object */
47637    ROUND8(pVfs->szOsFile) +       /* The main db file */
47638    journalFileSize * 2 +          /* The two journal files */
47639    nPathname + 1 + nUri +         /* zFilename */
47640    nPathname + 8 + 2              /* zJournal */
47641#ifndef SQLITE_OMIT_WAL
47642    + nPathname + 4 + 2            /* zWal */
47643#endif
47644  );
47645  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
47646  if( !pPtr ){
47647    sqlite3DbFree(0, zPathname);
47648    return SQLITE_NOMEM;
47649  }
47650  pPager =              (Pager*)(pPtr);
47651  pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
47652  pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
47653  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
47654  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
47655  pPager->zFilename =    (char*)(pPtr += journalFileSize);
47656  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
47657
47658  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
47659  if( zPathname ){
47660    assert( nPathname>0 );
47661    pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
47662    memcpy(pPager->zFilename, zPathname, nPathname);
47663    if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
47664    memcpy(pPager->zJournal, zPathname, nPathname);
47665    memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
47666    sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
47667#ifndef SQLITE_OMIT_WAL
47668    pPager->zWal = &pPager->zJournal[nPathname+8+1];
47669    memcpy(pPager->zWal, zPathname, nPathname);
47670    memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
47671    sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
47672#endif
47673    sqlite3DbFree(0, zPathname);
47674  }
47675  pPager->pVfs = pVfs;
47676  pPager->vfsFlags = vfsFlags;
47677
47678  /* Open the pager file.
47679  */
47680  if( zFilename && zFilename[0] ){
47681    int fout = 0;                    /* VFS flags returned by xOpen() */
47682    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
47683    assert( !memDb );
47684    readOnly = (fout&SQLITE_OPEN_READONLY);
47685
47686    /* If the file was successfully opened for read/write access,
47687    ** choose a default page size in case we have to create the
47688    ** database file. The default page size is the maximum of:
47689    **
47690    **    + SQLITE_DEFAULT_PAGE_SIZE,
47691    **    + The value returned by sqlite3OsSectorSize()
47692    **    + The largest page size that can be written atomically.
47693    */
47694    if( rc==SQLITE_OK ){
47695      int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
47696      if( !readOnly ){
47697        setSectorSize(pPager);
47698        assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
47699        if( szPageDflt<pPager->sectorSize ){
47700          if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
47701            szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
47702          }else{
47703            szPageDflt = (u32)pPager->sectorSize;
47704          }
47705        }
47706#ifdef SQLITE_ENABLE_ATOMIC_WRITE
47707        {
47708          int ii;
47709          assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
47710          assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
47711          assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
47712          for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
47713            if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
47714              szPageDflt = ii;
47715            }
47716          }
47717        }
47718#endif
47719      }
47720      pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
47721      if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
47722       || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
47723          vfsFlags |= SQLITE_OPEN_READONLY;
47724          goto act_like_temp_file;
47725      }
47726    }
47727  }else{
47728    /* If a temporary file is requested, it is not opened immediately.
47729    ** In this case we accept the default page size and delay actually
47730    ** opening the file until the first call to OsWrite().
47731    **
47732    ** This branch is also run for an in-memory database. An in-memory
47733    ** database is the same as a temp-file that is never written out to
47734    ** disk and uses an in-memory rollback journal.
47735    **
47736    ** This branch also runs for files marked as immutable.
47737    */
47738act_like_temp_file:
47739    tempFile = 1;
47740    pPager->eState = PAGER_READER;     /* Pretend we already have a lock */
47741    pPager->eLock = EXCLUSIVE_LOCK;    /* Pretend we are in EXCLUSIVE mode */
47742    pPager->noLock = 1;                /* Do no locking */
47743    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
47744  }
47745
47746  /* The following call to PagerSetPagesize() serves to set the value of
47747  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
47748  */
47749  if( rc==SQLITE_OK ){
47750    assert( pPager->memDb==0 );
47751    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
47752    testcase( rc!=SQLITE_OK );
47753  }
47754
47755  /* Initialize the PCache object. */
47756  if( rc==SQLITE_OK ){
47757    assert( nExtra<1000 );
47758    nExtra = ROUND8(nExtra);
47759    rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
47760                       !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
47761  }
47762
47763  /* If an error occurred above, free the  Pager structure and close the file.
47764  */
47765  if( rc!=SQLITE_OK ){
47766    sqlite3OsClose(pPager->fd);
47767    sqlite3PageFree(pPager->pTmpSpace);
47768    sqlite3_free(pPager);
47769    return rc;
47770  }
47771
47772  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
47773  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
47774
47775  pPager->useJournal = (u8)useJournal;
47776  /* pPager->stmtOpen = 0; */
47777  /* pPager->stmtInUse = 0; */
47778  /* pPager->nRef = 0; */
47779  /* pPager->stmtSize = 0; */
47780  /* pPager->stmtJSize = 0; */
47781  /* pPager->nPage = 0; */
47782  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
47783  /* pPager->state = PAGER_UNLOCK; */
47784  /* pPager->errMask = 0; */
47785  pPager->tempFile = (u8)tempFile;
47786  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
47787          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
47788  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
47789  pPager->exclusiveMode = (u8)tempFile;
47790  pPager->changeCountDone = pPager->tempFile;
47791  pPager->memDb = (u8)memDb;
47792  pPager->readOnly = (u8)readOnly;
47793  assert( useJournal || pPager->tempFile );
47794  pPager->noSync = pPager->tempFile;
47795  if( pPager->noSync ){
47796    assert( pPager->fullSync==0 );
47797    assert( pPager->syncFlags==0 );
47798    assert( pPager->walSyncFlags==0 );
47799    assert( pPager->ckptSyncFlags==0 );
47800  }else{
47801    pPager->fullSync = 1;
47802    pPager->syncFlags = SQLITE_SYNC_NORMAL;
47803    pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
47804    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
47805  }
47806  /* pPager->pFirst = 0; */
47807  /* pPager->pFirstSynced = 0; */
47808  /* pPager->pLast = 0; */
47809  pPager->nExtra = (u16)nExtra;
47810  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
47811  assert( isOpen(pPager->fd) || tempFile );
47812  setSectorSize(pPager);
47813  if( !useJournal ){
47814    pPager->journalMode = PAGER_JOURNALMODE_OFF;
47815  }else if( memDb ){
47816    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
47817  }
47818  /* pPager->xBusyHandler = 0; */
47819  /* pPager->pBusyHandlerArg = 0; */
47820  pPager->xReiniter = xReinit;
47821  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
47822  /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
47823
47824  *ppPager = pPager;
47825  return SQLITE_OK;
47826}
47827
47828
47829/* Verify that the database file has not be deleted or renamed out from
47830** under the pager.  Return SQLITE_OK if the database is still were it ought
47831** to be on disk.  Return non-zero (SQLITE_READONLY_DBMOVED or some other error
47832** code from sqlite3OsAccess()) if the database has gone missing.
47833*/
47834static int databaseIsUnmoved(Pager *pPager){
47835  int bHasMoved = 0;
47836  int rc;
47837
47838  if( pPager->tempFile ) return SQLITE_OK;
47839  if( pPager->dbSize==0 ) return SQLITE_OK;
47840  assert( pPager->zFilename && pPager->zFilename[0] );
47841  rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
47842  if( rc==SQLITE_NOTFOUND ){
47843    /* If the HAS_MOVED file-control is unimplemented, assume that the file
47844    ** has not been moved.  That is the historical behavior of SQLite: prior to
47845    ** version 3.8.3, it never checked */
47846    rc = SQLITE_OK;
47847  }else if( rc==SQLITE_OK && bHasMoved ){
47848    rc = SQLITE_READONLY_DBMOVED;
47849  }
47850  return rc;
47851}
47852
47853
47854/*
47855** This function is called after transitioning from PAGER_UNLOCK to
47856** PAGER_SHARED state. It tests if there is a hot journal present in
47857** the file-system for the given pager. A hot journal is one that
47858** needs to be played back. According to this function, a hot-journal
47859** file exists if the following criteria are met:
47860**
47861**   * The journal file exists in the file system, and
47862**   * No process holds a RESERVED or greater lock on the database file, and
47863**   * The database file itself is greater than 0 bytes in size, and
47864**   * The first byte of the journal file exists and is not 0x00.
47865**
47866** If the current size of the database file is 0 but a journal file
47867** exists, that is probably an old journal left over from a prior
47868** database with the same name. In this case the journal file is
47869** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
47870** is returned.
47871**
47872** This routine does not check if there is a master journal filename
47873** at the end of the file. If there is, and that master journal file
47874** does not exist, then the journal file is not really hot. In this
47875** case this routine will return a false-positive. The pager_playback()
47876** routine will discover that the journal file is not really hot and
47877** will not roll it back.
47878**
47879** If a hot-journal file is found to exist, *pExists is set to 1 and
47880** SQLITE_OK returned. If no hot-journal file is present, *pExists is
47881** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
47882** to determine whether or not a hot-journal file exists, the IO error
47883** code is returned and the value of *pExists is undefined.
47884*/
47885static int hasHotJournal(Pager *pPager, int *pExists){
47886  sqlite3_vfs * const pVfs = pPager->pVfs;
47887  int rc = SQLITE_OK;           /* Return code */
47888  int exists = 1;               /* True if a journal file is present */
47889  int jrnlOpen = !!isOpen(pPager->jfd);
47890
47891  assert( pPager->useJournal );
47892  assert( isOpen(pPager->fd) );
47893  assert( pPager->eState==PAGER_OPEN );
47894
47895  assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
47896    SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
47897  ));
47898
47899  *pExists = 0;
47900  if( !jrnlOpen ){
47901    rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
47902  }
47903  if( rc==SQLITE_OK && exists ){
47904    int locked = 0;             /* True if some process holds a RESERVED lock */
47905
47906    /* Race condition here:  Another process might have been holding the
47907    ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
47908    ** call above, but then delete the journal and drop the lock before
47909    ** we get to the following sqlite3OsCheckReservedLock() call.  If that
47910    ** is the case, this routine might think there is a hot journal when
47911    ** in fact there is none.  This results in a false-positive which will
47912    ** be dealt with by the playback routine.  Ticket #3883.
47913    */
47914    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
47915    if( rc==SQLITE_OK && !locked ){
47916      Pgno nPage;                 /* Number of pages in database file */
47917
47918      rc = pagerPagecount(pPager, &nPage);
47919      if( rc==SQLITE_OK ){
47920        /* If the database is zero pages in size, that means that either (1) the
47921        ** journal is a remnant from a prior database with the same name where
47922        ** the database file but not the journal was deleted, or (2) the initial
47923        ** transaction that populates a new database is being rolled back.
47924        ** In either case, the journal file can be deleted.  However, take care
47925        ** not to delete the journal file if it is already open due to
47926        ** journal_mode=PERSIST.
47927        */
47928        if( nPage==0 && !jrnlOpen ){
47929          sqlite3BeginBenignMalloc();
47930          if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
47931            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
47932            if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
47933          }
47934          sqlite3EndBenignMalloc();
47935        }else{
47936          /* The journal file exists and no other connection has a reserved
47937          ** or greater lock on the database file. Now check that there is
47938          ** at least one non-zero bytes at the start of the journal file.
47939          ** If there is, then we consider this journal to be hot. If not,
47940          ** it can be ignored.
47941          */
47942          if( !jrnlOpen ){
47943            int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
47944            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
47945          }
47946          if( rc==SQLITE_OK ){
47947            u8 first = 0;
47948            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
47949            if( rc==SQLITE_IOERR_SHORT_READ ){
47950              rc = SQLITE_OK;
47951            }
47952            if( !jrnlOpen ){
47953              sqlite3OsClose(pPager->jfd);
47954            }
47955            *pExists = (first!=0);
47956          }else if( rc==SQLITE_CANTOPEN ){
47957            /* If we cannot open the rollback journal file in order to see if
47958            ** it has a zero header, that might be due to an I/O error, or
47959            ** it might be due to the race condition described above and in
47960            ** ticket #3883.  Either way, assume that the journal is hot.
47961            ** This might be a false positive.  But if it is, then the
47962            ** automatic journal playback and recovery mechanism will deal
47963            ** with it under an EXCLUSIVE lock where we do not need to
47964            ** worry so much with race conditions.
47965            */
47966            *pExists = 1;
47967            rc = SQLITE_OK;
47968          }
47969        }
47970      }
47971    }
47972  }
47973
47974  return rc;
47975}
47976
47977/*
47978** This function is called to obtain a shared lock on the database file.
47979** It is illegal to call sqlite3PagerAcquire() until after this function
47980** has been successfully called. If a shared-lock is already held when
47981** this function is called, it is a no-op.
47982**
47983** The following operations are also performed by this function.
47984**
47985**   1) If the pager is currently in PAGER_OPEN state (no lock held
47986**      on the database file), then an attempt is made to obtain a
47987**      SHARED lock on the database file. Immediately after obtaining
47988**      the SHARED lock, the file-system is checked for a hot-journal,
47989**      which is played back if present. Following any hot-journal
47990**      rollback, the contents of the cache are validated by checking
47991**      the 'change-counter' field of the database file header and
47992**      discarded if they are found to be invalid.
47993**
47994**   2) If the pager is running in exclusive-mode, and there are currently
47995**      no outstanding references to any pages, and is in the error state,
47996**      then an attempt is made to clear the error state by discarding
47997**      the contents of the page cache and rolling back any open journal
47998**      file.
47999**
48000** If everything is successful, SQLITE_OK is returned. If an IO error
48001** occurs while locking the database, checking for a hot-journal file or
48002** rolling back a journal file, the IO error code is returned.
48003*/
48004SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
48005  int rc = SQLITE_OK;                /* Return code */
48006
48007  /* This routine is only called from b-tree and only when there are no
48008  ** outstanding pages. This implies that the pager state should either
48009  ** be OPEN or READER. READER is only possible if the pager is or was in
48010  ** exclusive access mode.
48011  */
48012  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
48013  assert( assert_pager_state(pPager) );
48014  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
48015  if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
48016
48017  if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
48018    int bHotJournal = 1;          /* True if there exists a hot journal-file */
48019
48020    assert( !MEMDB );
48021
48022    rc = pager_wait_on_lock(pPager, SHARED_LOCK);
48023    if( rc!=SQLITE_OK ){
48024      assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
48025      goto failed;
48026    }
48027
48028    /* If a journal file exists, and there is no RESERVED lock on the
48029    ** database file, then it either needs to be played back or deleted.
48030    */
48031    if( pPager->eLock<=SHARED_LOCK ){
48032      rc = hasHotJournal(pPager, &bHotJournal);
48033    }
48034    if( rc!=SQLITE_OK ){
48035      goto failed;
48036    }
48037    if( bHotJournal ){
48038      if( pPager->readOnly ){
48039        rc = SQLITE_READONLY_ROLLBACK;
48040        goto failed;
48041      }
48042
48043      /* Get an EXCLUSIVE lock on the database file. At this point it is
48044      ** important that a RESERVED lock is not obtained on the way to the
48045      ** EXCLUSIVE lock. If it were, another process might open the
48046      ** database file, detect the RESERVED lock, and conclude that the
48047      ** database is safe to read while this process is still rolling the
48048      ** hot-journal back.
48049      **
48050      ** Because the intermediate RESERVED lock is not requested, any
48051      ** other process attempting to access the database file will get to
48052      ** this point in the code and fail to obtain its own EXCLUSIVE lock
48053      ** on the database file.
48054      **
48055      ** Unless the pager is in locking_mode=exclusive mode, the lock is
48056      ** downgraded to SHARED_LOCK before this function returns.
48057      */
48058      rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
48059      if( rc!=SQLITE_OK ){
48060        goto failed;
48061      }
48062
48063      /* If it is not already open and the file exists on disk, open the
48064      ** journal for read/write access. Write access is required because
48065      ** in exclusive-access mode the file descriptor will be kept open
48066      ** and possibly used for a transaction later on. Also, write-access
48067      ** is usually required to finalize the journal in journal_mode=persist
48068      ** mode (and also for journal_mode=truncate on some systems).
48069      **
48070      ** If the journal does not exist, it usually means that some
48071      ** other connection managed to get in and roll it back before
48072      ** this connection obtained the exclusive lock above. Or, it
48073      ** may mean that the pager was in the error-state when this
48074      ** function was called and the journal file does not exist.
48075      */
48076      if( !isOpen(pPager->jfd) ){
48077        sqlite3_vfs * const pVfs = pPager->pVfs;
48078        int bExists;              /* True if journal file exists */
48079        rc = sqlite3OsAccess(
48080            pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
48081        if( rc==SQLITE_OK && bExists ){
48082          int fout = 0;
48083          int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
48084          assert( !pPager->tempFile );
48085          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
48086          assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
48087          if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
48088            rc = SQLITE_CANTOPEN_BKPT;
48089            sqlite3OsClose(pPager->jfd);
48090          }
48091        }
48092      }
48093
48094      /* Playback and delete the journal.  Drop the database write
48095      ** lock and reacquire the read lock. Purge the cache before
48096      ** playing back the hot-journal so that we don't end up with
48097      ** an inconsistent cache.  Sync the hot journal before playing
48098      ** it back since the process that crashed and left the hot journal
48099      ** probably did not sync it and we are required to always sync
48100      ** the journal before playing it back.
48101      */
48102      if( isOpen(pPager->jfd) ){
48103        assert( rc==SQLITE_OK );
48104        rc = pagerSyncHotJournal(pPager);
48105        if( rc==SQLITE_OK ){
48106          rc = pager_playback(pPager, 1);
48107          pPager->eState = PAGER_OPEN;
48108        }
48109      }else if( !pPager->exclusiveMode ){
48110        pagerUnlockDb(pPager, SHARED_LOCK);
48111      }
48112
48113      if( rc!=SQLITE_OK ){
48114        /* This branch is taken if an error occurs while trying to open
48115        ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
48116        ** pager_unlock() routine will be called before returning to unlock
48117        ** the file. If the unlock attempt fails, then Pager.eLock must be
48118        ** set to UNKNOWN_LOCK (see the comment above the #define for
48119        ** UNKNOWN_LOCK above for an explanation).
48120        **
48121        ** In order to get pager_unlock() to do this, set Pager.eState to
48122        ** PAGER_ERROR now. This is not actually counted as a transition
48123        ** to ERROR state in the state diagram at the top of this file,
48124        ** since we know that the same call to pager_unlock() will very
48125        ** shortly transition the pager object to the OPEN state. Calling
48126        ** assert_pager_state() would fail now, as it should not be possible
48127        ** to be in ERROR state when there are zero outstanding page
48128        ** references.
48129        */
48130        pager_error(pPager, rc);
48131        goto failed;
48132      }
48133
48134      assert( pPager->eState==PAGER_OPEN );
48135      assert( (pPager->eLock==SHARED_LOCK)
48136           || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
48137      );
48138    }
48139
48140    if( !pPager->tempFile && pPager->hasHeldSharedLock ){
48141      /* The shared-lock has just been acquired then check to
48142      ** see if the database has been modified.  If the database has changed,
48143      ** flush the cache.  The hasHeldSharedLock flag prevents this from
48144      ** occurring on the very first access to a file, in order to save a
48145      ** single unnecessary sqlite3OsRead() call at the start-up.
48146      **
48147      ** Database changes are detected by looking at 15 bytes beginning
48148      ** at offset 24 into the file.  The first 4 of these 16 bytes are
48149      ** a 32-bit counter that is incremented with each change.  The
48150      ** other bytes change randomly with each file change when
48151      ** a codec is in use.
48152      **
48153      ** There is a vanishingly small chance that a change will not be
48154      ** detected.  The chance of an undetected change is so small that
48155      ** it can be neglected.
48156      */
48157      Pgno nPage = 0;
48158      char dbFileVers[sizeof(pPager->dbFileVers)];
48159
48160      rc = pagerPagecount(pPager, &nPage);
48161      if( rc ) goto failed;
48162
48163      if( nPage>0 ){
48164        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
48165        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
48166        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
48167          goto failed;
48168        }
48169      }else{
48170        memset(dbFileVers, 0, sizeof(dbFileVers));
48171      }
48172
48173      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
48174        pager_reset(pPager);
48175
48176        /* Unmap the database file. It is possible that external processes
48177        ** may have truncated the database file and then extended it back
48178        ** to its original size while this process was not holding a lock.
48179        ** In this case there may exist a Pager.pMap mapping that appears
48180        ** to be the right size but is not actually valid. Avoid this
48181        ** possibility by unmapping the db here. */
48182        if( USEFETCH(pPager) ){
48183          sqlite3OsUnfetch(pPager->fd, 0, 0);
48184        }
48185      }
48186    }
48187
48188    /* If there is a WAL file in the file-system, open this database in WAL
48189    ** mode. Otherwise, the following function call is a no-op.
48190    */
48191    rc = pagerOpenWalIfPresent(pPager);
48192#ifndef SQLITE_OMIT_WAL
48193    assert( pPager->pWal==0 || rc==SQLITE_OK );
48194#endif
48195  }
48196
48197  if( pagerUseWal(pPager) ){
48198    assert( rc==SQLITE_OK );
48199    rc = pagerBeginReadTransaction(pPager);
48200  }
48201
48202  if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
48203    rc = pagerPagecount(pPager, &pPager->dbSize);
48204  }
48205
48206 failed:
48207  if( rc!=SQLITE_OK ){
48208    assert( !MEMDB );
48209    pager_unlock(pPager);
48210    assert( pPager->eState==PAGER_OPEN );
48211  }else{
48212    pPager->eState = PAGER_READER;
48213    pPager->hasHeldSharedLock = 1;
48214  }
48215  return rc;
48216}
48217
48218/*
48219** If the reference count has reached zero, rollback any active
48220** transaction and unlock the pager.
48221**
48222** Except, in locking_mode=EXCLUSIVE when there is nothing to in
48223** the rollback journal, the unlock is not performed and there is
48224** nothing to rollback, so this routine is a no-op.
48225*/
48226static void pagerUnlockIfUnused(Pager *pPager){
48227  if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
48228    pagerUnlockAndRollback(pPager);
48229  }
48230}
48231
48232/*
48233** Acquire a reference to page number pgno in pager pPager (a page
48234** reference has type DbPage*). If the requested reference is
48235** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
48236**
48237** If the requested page is already in the cache, it is returned.
48238** Otherwise, a new page object is allocated and populated with data
48239** read from the database file. In some cases, the pcache module may
48240** choose not to allocate a new page object and may reuse an existing
48241** object with no outstanding references.
48242**
48243** The extra data appended to a page is always initialized to zeros the
48244** first time a page is loaded into memory. If the page requested is
48245** already in the cache when this function is called, then the extra
48246** data is left as it was when the page object was last used.
48247**
48248** If the database image is smaller than the requested page or if a
48249** non-zero value is passed as the noContent parameter and the
48250** requested page is not already stored in the cache, then no
48251** actual disk read occurs. In this case the memory image of the
48252** page is initialized to all zeros.
48253**
48254** If noContent is true, it means that we do not care about the contents
48255** of the page. This occurs in two scenarios:
48256**
48257**   a) When reading a free-list leaf page from the database, and
48258**
48259**   b) When a savepoint is being rolled back and we need to load
48260**      a new page into the cache to be filled with the data read
48261**      from the savepoint journal.
48262**
48263** If noContent is true, then the data returned is zeroed instead of
48264** being read from the database. Additionally, the bits corresponding
48265** to pgno in Pager.pInJournal (bitvec of pages already written to the
48266** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
48267** savepoints are set. This means if the page is made writable at any
48268** point in the future, using a call to sqlite3PagerWrite(), its contents
48269** will not be journaled. This saves IO.
48270**
48271** The acquisition might fail for several reasons.  In all cases,
48272** an appropriate error code is returned and *ppPage is set to NULL.
48273**
48274** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
48275** to find a page in the in-memory cache first.  If the page is not already
48276** in memory, this routine goes to disk to read it in whereas Lookup()
48277** just returns 0.  This routine acquires a read-lock the first time it
48278** has to go to disk, and could also playback an old journal if necessary.
48279** Since Lookup() never goes to disk, it never has to deal with locks
48280** or journal files.
48281*/
48282SQLITE_PRIVATE int sqlite3PagerAcquire(
48283  Pager *pPager,      /* The pager open on the database file */
48284  Pgno pgno,          /* Page number to fetch */
48285  DbPage **ppPage,    /* Write a pointer to the page here */
48286  int flags           /* PAGER_GET_XXX flags */
48287){
48288  int rc = SQLITE_OK;
48289  PgHdr *pPg = 0;
48290  u32 iFrame = 0;                 /* Frame to read from WAL file */
48291  const int noContent = (flags & PAGER_GET_NOCONTENT);
48292
48293  /* It is acceptable to use a read-only (mmap) page for any page except
48294  ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
48295  ** flag was specified by the caller. And so long as the db is not a
48296  ** temporary or in-memory database.  */
48297  const int bMmapOk = (pgno>1 && USEFETCH(pPager)
48298   && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
48299#ifdef SQLITE_HAS_CODEC
48300   && pPager->xCodec==0
48301#endif
48302  );
48303
48304  /* Optimization note:  Adding the "pgno<=1" term before "pgno==0" here
48305  ** allows the compiler optimizer to reuse the results of the "pgno>1"
48306  ** test in the previous statement, and avoid testing pgno==0 in the
48307  ** common case where pgno is large. */
48308  if( pgno<=1 && pgno==0 ){
48309    return SQLITE_CORRUPT_BKPT;
48310  }
48311  assert( pPager->eState>=PAGER_READER );
48312  assert( assert_pager_state(pPager) );
48313  assert( noContent==0 || bMmapOk==0 );
48314
48315  assert( pPager->hasHeldSharedLock==1 );
48316
48317  /* If the pager is in the error state, return an error immediately.
48318  ** Otherwise, request the page from the PCache layer. */
48319  if( pPager->errCode!=SQLITE_OK ){
48320    rc = pPager->errCode;
48321  }else{
48322    if( bMmapOk && pagerUseWal(pPager) ){
48323      rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
48324      if( rc!=SQLITE_OK ) goto pager_acquire_err;
48325    }
48326
48327    if( bMmapOk && iFrame==0 ){
48328      void *pData = 0;
48329
48330      rc = sqlite3OsFetch(pPager->fd,
48331          (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
48332      );
48333
48334      if( rc==SQLITE_OK && pData ){
48335        if( pPager->eState>PAGER_READER ){
48336          pPg = sqlite3PagerLookup(pPager, pgno);
48337        }
48338        if( pPg==0 ){
48339          rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
48340        }else{
48341          sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
48342        }
48343        if( pPg ){
48344          assert( rc==SQLITE_OK );
48345          *ppPage = pPg;
48346          return SQLITE_OK;
48347        }
48348      }
48349      if( rc!=SQLITE_OK ){
48350        goto pager_acquire_err;
48351      }
48352    }
48353
48354    {
48355      sqlite3_pcache_page *pBase;
48356      pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
48357      if( pBase==0 ){
48358        rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
48359        if( rc!=SQLITE_OK ) goto pager_acquire_err;
48360        if( pBase==0 ){
48361          pPg = *ppPage = 0;
48362          rc = SQLITE_NOMEM;
48363          goto pager_acquire_err;
48364        }
48365      }
48366      pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
48367      assert( pPg!=0 );
48368    }
48369  }
48370
48371  if( rc!=SQLITE_OK ){
48372    /* Either the call to sqlite3PcacheFetch() returned an error or the
48373    ** pager was already in the error-state when this function was called.
48374    ** Set pPg to 0 and jump to the exception handler.  */
48375    pPg = 0;
48376    goto pager_acquire_err;
48377  }
48378  assert( pPg==(*ppPage) );
48379  assert( pPg->pgno==pgno );
48380  assert( pPg->pPager==pPager || pPg->pPager==0 );
48381
48382  if( pPg->pPager && !noContent ){
48383    /* In this case the pcache already contains an initialized copy of
48384    ** the page. Return without further ado.  */
48385    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
48386    pPager->aStat[PAGER_STAT_HIT]++;
48387    return SQLITE_OK;
48388
48389  }else{
48390    /* The pager cache has created a new page. Its content needs to
48391    ** be initialized.  */
48392
48393    pPg->pPager = pPager;
48394
48395    /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
48396    ** number greater than this, or the unused locking-page, is requested. */
48397    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
48398      rc = SQLITE_CORRUPT_BKPT;
48399      goto pager_acquire_err;
48400    }
48401
48402    if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
48403      if( pgno>pPager->mxPgno ){
48404        rc = SQLITE_FULL;
48405        goto pager_acquire_err;
48406      }
48407      if( noContent ){
48408        /* Failure to set the bits in the InJournal bit-vectors is benign.
48409        ** It merely means that we might do some extra work to journal a
48410        ** page that does not need to be journaled.  Nevertheless, be sure
48411        ** to test the case where a malloc error occurs while trying to set
48412        ** a bit in a bit vector.
48413        */
48414        sqlite3BeginBenignMalloc();
48415        if( pgno<=pPager->dbOrigSize ){
48416          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
48417          testcase( rc==SQLITE_NOMEM );
48418        }
48419        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
48420        testcase( rc==SQLITE_NOMEM );
48421        sqlite3EndBenignMalloc();
48422      }
48423      memset(pPg->pData, 0, pPager->pageSize);
48424      IOTRACE(("ZERO %p %d\n", pPager, pgno));
48425    }else{
48426      if( pagerUseWal(pPager) && bMmapOk==0 ){
48427        rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
48428        if( rc!=SQLITE_OK ) goto pager_acquire_err;
48429      }
48430      assert( pPg->pPager==pPager );
48431      pPager->aStat[PAGER_STAT_MISS]++;
48432      rc = readDbPage(pPg, iFrame);
48433      if( rc!=SQLITE_OK ){
48434        goto pager_acquire_err;
48435      }
48436    }
48437    pager_set_pagehash(pPg);
48438  }
48439
48440  return SQLITE_OK;
48441
48442pager_acquire_err:
48443  assert( rc!=SQLITE_OK );
48444  if( pPg ){
48445    sqlite3PcacheDrop(pPg);
48446  }
48447  pagerUnlockIfUnused(pPager);
48448
48449  *ppPage = 0;
48450  return rc;
48451}
48452
48453/*
48454** Acquire a page if it is already in the in-memory cache.  Do
48455** not read the page from disk.  Return a pointer to the page,
48456** or 0 if the page is not in cache.
48457**
48458** See also sqlite3PagerGet().  The difference between this routine
48459** and sqlite3PagerGet() is that _get() will go to the disk and read
48460** in the page if the page is not already in cache.  This routine
48461** returns NULL if the page is not in cache or if a disk I/O error
48462** has ever happened.
48463*/
48464SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
48465  sqlite3_pcache_page *pPage;
48466  assert( pPager!=0 );
48467  assert( pgno!=0 );
48468  assert( pPager->pPCache!=0 );
48469  pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
48470  assert( pPage==0 || pPager->hasHeldSharedLock );
48471  if( pPage==0 ) return 0;
48472  return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
48473}
48474
48475/*
48476** Release a page reference.
48477**
48478** If the number of references to the page drop to zero, then the
48479** page is added to the LRU list.  When all references to all pages
48480** are released, a rollback occurs and the lock on the database is
48481** removed.
48482*/
48483SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
48484  Pager *pPager;
48485  assert( pPg!=0 );
48486  pPager = pPg->pPager;
48487  if( pPg->flags & PGHDR_MMAP ){
48488    pagerReleaseMapPage(pPg);
48489  }else{
48490    sqlite3PcacheRelease(pPg);
48491  }
48492  pagerUnlockIfUnused(pPager);
48493}
48494SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
48495  if( pPg ) sqlite3PagerUnrefNotNull(pPg);
48496}
48497
48498/*
48499** This function is called at the start of every write transaction.
48500** There must already be a RESERVED or EXCLUSIVE lock on the database
48501** file when this routine is called.
48502**
48503** Open the journal file for pager pPager and write a journal header
48504** to the start of it. If there are active savepoints, open the sub-journal
48505** as well. This function is only used when the journal file is being
48506** opened to write a rollback log for a transaction. It is not used
48507** when opening a hot journal file to roll it back.
48508**
48509** If the journal file is already open (as it may be in exclusive mode),
48510** then this function just writes a journal header to the start of the
48511** already open file.
48512**
48513** Whether or not the journal file is opened by this function, the
48514** Pager.pInJournal bitvec structure is allocated.
48515**
48516** Return SQLITE_OK if everything is successful. Otherwise, return
48517** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
48518** an IO error code if opening or writing the journal file fails.
48519*/
48520static int pager_open_journal(Pager *pPager){
48521  int rc = SQLITE_OK;                        /* Return code */
48522  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
48523
48524  assert( pPager->eState==PAGER_WRITER_LOCKED );
48525  assert( assert_pager_state(pPager) );
48526  assert( pPager->pInJournal==0 );
48527
48528  /* If already in the error state, this function is a no-op.  But on
48529  ** the other hand, this routine is never called if we are already in
48530  ** an error state. */
48531  if( NEVER(pPager->errCode) ) return pPager->errCode;
48532
48533  if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
48534    pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
48535    if( pPager->pInJournal==0 ){
48536      return SQLITE_NOMEM;
48537    }
48538
48539    /* Open the journal file if it is not already open. */
48540    if( !isOpen(pPager->jfd) ){
48541      if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
48542        sqlite3MemJournalOpen(pPager->jfd);
48543      }else{
48544        const int flags =                   /* VFS flags to open journal file */
48545          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
48546          (pPager->tempFile ?
48547            (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
48548            (SQLITE_OPEN_MAIN_JOURNAL)
48549          );
48550
48551        /* Verify that the database still has the same name as it did when
48552        ** it was originally opened. */
48553        rc = databaseIsUnmoved(pPager);
48554        if( rc==SQLITE_OK ){
48555#ifdef SQLITE_ENABLE_ATOMIC_WRITE
48556          rc = sqlite3JournalOpen(
48557              pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
48558          );
48559#else
48560          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
48561#endif
48562        }
48563      }
48564      assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
48565    }
48566
48567
48568    /* Write the first journal header to the journal file and open
48569    ** the sub-journal if necessary.
48570    */
48571    if( rc==SQLITE_OK ){
48572      /* TODO: Check if all of these are really required. */
48573      pPager->nRec = 0;
48574      pPager->journalOff = 0;
48575      pPager->setMaster = 0;
48576      pPager->journalHdr = 0;
48577      rc = writeJournalHdr(pPager);
48578    }
48579  }
48580
48581  if( rc!=SQLITE_OK ){
48582    sqlite3BitvecDestroy(pPager->pInJournal);
48583    pPager->pInJournal = 0;
48584  }else{
48585    assert( pPager->eState==PAGER_WRITER_LOCKED );
48586    pPager->eState = PAGER_WRITER_CACHEMOD;
48587  }
48588
48589  return rc;
48590}
48591
48592/*
48593** Begin a write-transaction on the specified pager object. If a
48594** write-transaction has already been opened, this function is a no-op.
48595**
48596** If the exFlag argument is false, then acquire at least a RESERVED
48597** lock on the database file. If exFlag is true, then acquire at least
48598** an EXCLUSIVE lock. If such a lock is already held, no locking
48599** functions need be called.
48600**
48601** If the subjInMemory argument is non-zero, then any sub-journal opened
48602** within this transaction will be opened as an in-memory file. This
48603** has no effect if the sub-journal is already opened (as it may be when
48604** running in exclusive mode) or if the transaction does not require a
48605** sub-journal. If the subjInMemory argument is zero, then any required
48606** sub-journal is implemented in-memory if pPager is an in-memory database,
48607** or using a temporary file otherwise.
48608*/
48609SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
48610  int rc = SQLITE_OK;
48611
48612  if( pPager->errCode ) return pPager->errCode;
48613  assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
48614  pPager->subjInMemory = (u8)subjInMemory;
48615
48616  if( ALWAYS(pPager->eState==PAGER_READER) ){
48617    assert( pPager->pInJournal==0 );
48618
48619    if( pagerUseWal(pPager) ){
48620      /* If the pager is configured to use locking_mode=exclusive, and an
48621      ** exclusive lock on the database is not already held, obtain it now.
48622      */
48623      if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
48624        rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
48625        if( rc!=SQLITE_OK ){
48626          return rc;
48627        }
48628        sqlite3WalExclusiveMode(pPager->pWal, 1);
48629      }
48630
48631      /* Grab the write lock on the log file. If successful, upgrade to
48632      ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
48633      ** The busy-handler is not invoked if another connection already
48634      ** holds the write-lock. If possible, the upper layer will call it.
48635      */
48636      rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
48637    }else{
48638      /* Obtain a RESERVED lock on the database file. If the exFlag parameter
48639      ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
48640      ** busy-handler callback can be used when upgrading to the EXCLUSIVE
48641      ** lock, but not when obtaining the RESERVED lock.
48642      */
48643      rc = pagerLockDb(pPager, RESERVED_LOCK);
48644      if( rc==SQLITE_OK && exFlag ){
48645        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
48646      }
48647    }
48648
48649    if( rc==SQLITE_OK ){
48650      /* Change to WRITER_LOCKED state.
48651      **
48652      ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
48653      ** when it has an open transaction, but never to DBMOD or FINISHED.
48654      ** This is because in those states the code to roll back savepoint
48655      ** transactions may copy data from the sub-journal into the database
48656      ** file as well as into the page cache. Which would be incorrect in
48657      ** WAL mode.
48658      */
48659      pPager->eState = PAGER_WRITER_LOCKED;
48660      pPager->dbHintSize = pPager->dbSize;
48661      pPager->dbFileSize = pPager->dbSize;
48662      pPager->dbOrigSize = pPager->dbSize;
48663      pPager->journalOff = 0;
48664    }
48665
48666    assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
48667    assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
48668    assert( assert_pager_state(pPager) );
48669  }
48670
48671  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
48672  return rc;
48673}
48674
48675/*
48676** Write page pPg onto the end of the rollback journal.
48677*/
48678static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
48679  Pager *pPager = pPg->pPager;
48680  int rc;
48681  u32 cksum;
48682  char *pData2;
48683  i64 iOff = pPager->journalOff;
48684
48685  /* We should never write to the journal file the page that
48686  ** contains the database locks.  The following assert verifies
48687  ** that we do not. */
48688  assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
48689
48690  assert( pPager->journalHdr<=pPager->journalOff );
48691  CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
48692  cksum = pager_cksum(pPager, (u8*)pData2);
48693
48694  /* Even if an IO or diskfull error occurs while journalling the
48695  ** page in the block above, set the need-sync flag for the page.
48696  ** Otherwise, when the transaction is rolled back, the logic in
48697  ** playback_one_page() will think that the page needs to be restored
48698  ** in the database file. And if an IO error occurs while doing so,
48699  ** then corruption may follow.
48700  */
48701  pPg->flags |= PGHDR_NEED_SYNC;
48702
48703  rc = write32bits(pPager->jfd, iOff, pPg->pgno);
48704  if( rc!=SQLITE_OK ) return rc;
48705  rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
48706  if( rc!=SQLITE_OK ) return rc;
48707  rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
48708  if( rc!=SQLITE_OK ) return rc;
48709
48710  IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
48711           pPager->journalOff, pPager->pageSize));
48712  PAGER_INCR(sqlite3_pager_writej_count);
48713  PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
48714       PAGERID(pPager), pPg->pgno,
48715       ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
48716
48717  pPager->journalOff += 8 + pPager->pageSize;
48718  pPager->nRec++;
48719  assert( pPager->pInJournal!=0 );
48720  rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
48721  testcase( rc==SQLITE_NOMEM );
48722  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
48723  rc |= addToSavepointBitvecs(pPager, pPg->pgno);
48724  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
48725  return rc;
48726}
48727
48728/*
48729** Mark a single data page as writeable. The page is written into the
48730** main journal or sub-journal as required. If the page is written into
48731** one of the journals, the corresponding bit is set in the
48732** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
48733** of any open savepoints as appropriate.
48734*/
48735static int pager_write(PgHdr *pPg){
48736  Pager *pPager = pPg->pPager;
48737  int rc = SQLITE_OK;
48738
48739  /* This routine is not called unless a write-transaction has already
48740  ** been started. The journal file may or may not be open at this point.
48741  ** It is never called in the ERROR state.
48742  */
48743  assert( pPager->eState==PAGER_WRITER_LOCKED
48744       || pPager->eState==PAGER_WRITER_CACHEMOD
48745       || pPager->eState==PAGER_WRITER_DBMOD
48746  );
48747  assert( assert_pager_state(pPager) );
48748  assert( pPager->errCode==0 );
48749  assert( pPager->readOnly==0 );
48750  CHECK_PAGE(pPg);
48751
48752  /* The journal file needs to be opened. Higher level routines have already
48753  ** obtained the necessary locks to begin the write-transaction, but the
48754  ** rollback journal might not yet be open. Open it now if this is the case.
48755  **
48756  ** This is done before calling sqlite3PcacheMakeDirty() on the page.
48757  ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
48758  ** an error might occur and the pager would end up in WRITER_LOCKED state
48759  ** with pages marked as dirty in the cache.
48760  */
48761  if( pPager->eState==PAGER_WRITER_LOCKED ){
48762    rc = pager_open_journal(pPager);
48763    if( rc!=SQLITE_OK ) return rc;
48764  }
48765  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
48766  assert( assert_pager_state(pPager) );
48767
48768  /* Mark the page that is about to be modified as dirty. */
48769  sqlite3PcacheMakeDirty(pPg);
48770
48771  /* If a rollback journal is in use, them make sure the page that is about
48772  ** to change is in the rollback journal, or if the page is a new page off
48773  ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
48774  */
48775  assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
48776  if( pPager->pInJournal!=0
48777   && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
48778  ){
48779    assert( pagerUseWal(pPager)==0 );
48780    if( pPg->pgno<=pPager->dbOrigSize ){
48781      rc = pagerAddPageToRollbackJournal(pPg);
48782      if( rc!=SQLITE_OK ){
48783        return rc;
48784      }
48785    }else{
48786      if( pPager->eState!=PAGER_WRITER_DBMOD ){
48787        pPg->flags |= PGHDR_NEED_SYNC;
48788      }
48789      PAGERTRACE(("APPEND %d page %d needSync=%d\n",
48790              PAGERID(pPager), pPg->pgno,
48791             ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
48792    }
48793  }
48794
48795  /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
48796  ** and before writing the page into the rollback journal.  Wait until now,
48797  ** after the page has been successfully journalled, before setting the
48798  ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
48799  */
48800  pPg->flags |= PGHDR_WRITEABLE;
48801
48802  /* If the statement journal is open and the page is not in it,
48803  ** then write the page into the statement journal.
48804  */
48805  if( pPager->nSavepoint>0 ){
48806    rc = subjournalPageIfRequired(pPg);
48807  }
48808
48809  /* Update the database size and return. */
48810  if( pPager->dbSize<pPg->pgno ){
48811    pPager->dbSize = pPg->pgno;
48812  }
48813  return rc;
48814}
48815
48816/*
48817** This is a variant of sqlite3PagerWrite() that runs when the sector size
48818** is larger than the page size.  SQLite makes the (reasonable) assumption that
48819** all bytes of a sector are written together by hardware.  Hence, all bytes of
48820** a sector need to be journalled in case of a power loss in the middle of
48821** a write.
48822**
48823** Usually, the sector size is less than or equal to the page size, in which
48824** case pages can be individually written.  This routine only runs in the
48825** exceptional case where the page size is smaller than the sector size.
48826*/
48827static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
48828  int rc = SQLITE_OK;          /* Return code */
48829  Pgno nPageCount;             /* Total number of pages in database file */
48830  Pgno pg1;                    /* First page of the sector pPg is located on. */
48831  int nPage = 0;               /* Number of pages starting at pg1 to journal */
48832  int ii;                      /* Loop counter */
48833  int needSync = 0;            /* True if any page has PGHDR_NEED_SYNC */
48834  Pager *pPager = pPg->pPager; /* The pager that owns pPg */
48835  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
48836
48837  /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
48838  ** a journal header to be written between the pages journaled by
48839  ** this function.
48840  */
48841  assert( !MEMDB );
48842  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
48843  pPager->doNotSpill |= SPILLFLAG_NOSYNC;
48844
48845  /* This trick assumes that both the page-size and sector-size are
48846  ** an integer power of 2. It sets variable pg1 to the identifier
48847  ** of the first page of the sector pPg is located on.
48848  */
48849  pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
48850
48851  nPageCount = pPager->dbSize;
48852  if( pPg->pgno>nPageCount ){
48853    nPage = (pPg->pgno - pg1)+1;
48854  }else if( (pg1+nPagePerSector-1)>nPageCount ){
48855    nPage = nPageCount+1-pg1;
48856  }else{
48857    nPage = nPagePerSector;
48858  }
48859  assert(nPage>0);
48860  assert(pg1<=pPg->pgno);
48861  assert((pg1+nPage)>pPg->pgno);
48862
48863  for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
48864    Pgno pg = pg1+ii;
48865    PgHdr *pPage;
48866    if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
48867      if( pg!=PAGER_MJ_PGNO(pPager) ){
48868        rc = sqlite3PagerGet(pPager, pg, &pPage);
48869        if( rc==SQLITE_OK ){
48870          rc = pager_write(pPage);
48871          if( pPage->flags&PGHDR_NEED_SYNC ){
48872            needSync = 1;
48873          }
48874          sqlite3PagerUnrefNotNull(pPage);
48875        }
48876      }
48877    }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
48878      if( pPage->flags&PGHDR_NEED_SYNC ){
48879        needSync = 1;
48880      }
48881      sqlite3PagerUnrefNotNull(pPage);
48882    }
48883  }
48884
48885  /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
48886  ** starting at pg1, then it needs to be set for all of them. Because
48887  ** writing to any of these nPage pages may damage the others, the
48888  ** journal file must contain sync()ed copies of all of them
48889  ** before any of them can be written out to the database file.
48890  */
48891  if( rc==SQLITE_OK && needSync ){
48892    assert( !MEMDB );
48893    for(ii=0; ii<nPage; ii++){
48894      PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
48895      if( pPage ){
48896        pPage->flags |= PGHDR_NEED_SYNC;
48897        sqlite3PagerUnrefNotNull(pPage);
48898      }
48899    }
48900  }
48901
48902  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
48903  pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
48904  return rc;
48905}
48906
48907/*
48908** Mark a data page as writeable. This routine must be called before
48909** making changes to a page. The caller must check the return value
48910** of this function and be careful not to change any page data unless
48911** this routine returns SQLITE_OK.
48912**
48913** The difference between this function and pager_write() is that this
48914** function also deals with the special case where 2 or more pages
48915** fit on a single disk sector. In this case all co-resident pages
48916** must have been written to the journal file before returning.
48917**
48918** If an error occurs, SQLITE_NOMEM or an IO error code is returned
48919** as appropriate. Otherwise, SQLITE_OK.
48920*/
48921SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
48922  Pager *pPager = pPg->pPager;
48923  assert( (pPg->flags & PGHDR_MMAP)==0 );
48924  assert( pPager->eState>=PAGER_WRITER_LOCKED );
48925  assert( pPager->eState!=PAGER_ERROR );
48926  assert( assert_pager_state(pPager) );
48927  if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
48928    if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
48929    return SQLITE_OK;
48930  }else if( pPager->sectorSize > (u32)pPager->pageSize ){
48931    return pagerWriteLargeSector(pPg);
48932  }else{
48933    return pager_write(pPg);
48934  }
48935}
48936
48937/*
48938** Return TRUE if the page given in the argument was previously passed
48939** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
48940** to change the content of the page.
48941*/
48942#ifndef NDEBUG
48943SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
48944  return pPg->flags & PGHDR_WRITEABLE;
48945}
48946#endif
48947
48948/*
48949** A call to this routine tells the pager that it is not necessary to
48950** write the information on page pPg back to the disk, even though
48951** that page might be marked as dirty.  This happens, for example, when
48952** the page has been added as a leaf of the freelist and so its
48953** content no longer matters.
48954**
48955** The overlying software layer calls this routine when all of the data
48956** on the given page is unused. The pager marks the page as clean so
48957** that it does not get written to disk.
48958**
48959** Tests show that this optimization can quadruple the speed of large
48960** DELETE operations.
48961*/
48962SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
48963  Pager *pPager = pPg->pPager;
48964  if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
48965    PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
48966    IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
48967    pPg->flags |= PGHDR_DONT_WRITE;
48968    pPg->flags &= ~PGHDR_WRITEABLE;
48969    pager_set_pagehash(pPg);
48970  }
48971}
48972
48973/*
48974** This routine is called to increment the value of the database file
48975** change-counter, stored as a 4-byte big-endian integer starting at
48976** byte offset 24 of the pager file.  The secondary change counter at
48977** 92 is also updated, as is the SQLite version number at offset 96.
48978**
48979** But this only happens if the pPager->changeCountDone flag is false.
48980** To avoid excess churning of page 1, the update only happens once.
48981** See also the pager_write_changecounter() routine that does an
48982** unconditional update of the change counters.
48983**
48984** If the isDirectMode flag is zero, then this is done by calling
48985** sqlite3PagerWrite() on page 1, then modifying the contents of the
48986** page data. In this case the file will be updated when the current
48987** transaction is committed.
48988**
48989** The isDirectMode flag may only be non-zero if the library was compiled
48990** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
48991** if isDirect is non-zero, then the database file is updated directly
48992** by writing an updated version of page 1 using a call to the
48993** sqlite3OsWrite() function.
48994*/
48995static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
48996  int rc = SQLITE_OK;
48997
48998  assert( pPager->eState==PAGER_WRITER_CACHEMOD
48999       || pPager->eState==PAGER_WRITER_DBMOD
49000  );
49001  assert( assert_pager_state(pPager) );
49002
49003  /* Declare and initialize constant integer 'isDirect'. If the
49004  ** atomic-write optimization is enabled in this build, then isDirect
49005  ** is initialized to the value passed as the isDirectMode parameter
49006  ** to this function. Otherwise, it is always set to zero.
49007  **
49008  ** The idea is that if the atomic-write optimization is not
49009  ** enabled at compile time, the compiler can omit the tests of
49010  ** 'isDirect' below, as well as the block enclosed in the
49011  ** "if( isDirect )" condition.
49012  */
49013#ifndef SQLITE_ENABLE_ATOMIC_WRITE
49014# define DIRECT_MODE 0
49015  assert( isDirectMode==0 );
49016  UNUSED_PARAMETER(isDirectMode);
49017#else
49018# define DIRECT_MODE isDirectMode
49019#endif
49020
49021  if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
49022    PgHdr *pPgHdr;                /* Reference to page 1 */
49023
49024    assert( !pPager->tempFile && isOpen(pPager->fd) );
49025
49026    /* Open page 1 of the file for writing. */
49027    rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
49028    assert( pPgHdr==0 || rc==SQLITE_OK );
49029
49030    /* If page one was fetched successfully, and this function is not
49031    ** operating in direct-mode, make page 1 writable.  When not in
49032    ** direct mode, page 1 is always held in cache and hence the PagerGet()
49033    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
49034    */
49035    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
49036      rc = sqlite3PagerWrite(pPgHdr);
49037    }
49038
49039    if( rc==SQLITE_OK ){
49040      /* Actually do the update of the change counter */
49041      pager_write_changecounter(pPgHdr);
49042
49043      /* If running in direct mode, write the contents of page 1 to the file. */
49044      if( DIRECT_MODE ){
49045        const void *zBuf;
49046        assert( pPager->dbFileSize>0 );
49047        CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
49048        if( rc==SQLITE_OK ){
49049          rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
49050          pPager->aStat[PAGER_STAT_WRITE]++;
49051        }
49052        if( rc==SQLITE_OK ){
49053          /* Update the pager's copy of the change-counter. Otherwise, the
49054          ** next time a read transaction is opened the cache will be
49055          ** flushed (as the change-counter values will not match).  */
49056          const void *pCopy = (const void *)&((const char *)zBuf)[24];
49057          memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
49058          pPager->changeCountDone = 1;
49059        }
49060      }else{
49061        pPager->changeCountDone = 1;
49062      }
49063    }
49064
49065    /* Release the page reference. */
49066    sqlite3PagerUnref(pPgHdr);
49067  }
49068  return rc;
49069}
49070
49071/*
49072** Sync the database file to disk. This is a no-op for in-memory databases
49073** or pages with the Pager.noSync flag set.
49074**
49075** If successful, or if called on a pager for which it is a no-op, this
49076** function returns SQLITE_OK. Otherwise, an IO error code is returned.
49077*/
49078SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
49079  int rc = SQLITE_OK;
49080
49081  if( isOpen(pPager->fd) ){
49082    void *pArg = (void*)zMaster;
49083    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
49084    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
49085  }
49086  if( rc==SQLITE_OK && !pPager->noSync ){
49087    assert( !MEMDB );
49088    rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
49089  }
49090  return rc;
49091}
49092
49093/*
49094** This function may only be called while a write-transaction is active in
49095** rollback. If the connection is in WAL mode, this call is a no-op.
49096** Otherwise, if the connection does not already have an EXCLUSIVE lock on
49097** the database file, an attempt is made to obtain one.
49098**
49099** If the EXCLUSIVE lock is already held or the attempt to obtain it is
49100** successful, or the connection is in WAL mode, SQLITE_OK is returned.
49101** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
49102** returned.
49103*/
49104SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
49105  int rc = SQLITE_OK;
49106  assert( pPager->eState==PAGER_WRITER_CACHEMOD
49107       || pPager->eState==PAGER_WRITER_DBMOD
49108       || pPager->eState==PAGER_WRITER_LOCKED
49109  );
49110  assert( assert_pager_state(pPager) );
49111  if( 0==pagerUseWal(pPager) ){
49112    rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
49113  }
49114  return rc;
49115}
49116
49117/*
49118** Sync the database file for the pager pPager. zMaster points to the name
49119** of a master journal file that should be written into the individual
49120** journal file. zMaster may be NULL, which is interpreted as no master
49121** journal (a single database transaction).
49122**
49123** This routine ensures that:
49124**
49125**   * The database file change-counter is updated,
49126**   * the journal is synced (unless the atomic-write optimization is used),
49127**   * all dirty pages are written to the database file,
49128**   * the database file is truncated (if required), and
49129**   * the database file synced.
49130**
49131** The only thing that remains to commit the transaction is to finalize
49132** (delete, truncate or zero the first part of) the journal file (or
49133** delete the master journal file if specified).
49134**
49135** Note that if zMaster==NULL, this does not overwrite a previous value
49136** passed to an sqlite3PagerCommitPhaseOne() call.
49137**
49138** If the final parameter - noSync - is true, then the database file itself
49139** is not synced. The caller must call sqlite3PagerSync() directly to
49140** sync the database file before calling CommitPhaseTwo() to delete the
49141** journal file in this case.
49142*/
49143SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
49144  Pager *pPager,                  /* Pager object */
49145  const char *zMaster,            /* If not NULL, the master journal name */
49146  int noSync                      /* True to omit the xSync on the db file */
49147){
49148  int rc = SQLITE_OK;             /* Return code */
49149
49150  assert( pPager->eState==PAGER_WRITER_LOCKED
49151       || pPager->eState==PAGER_WRITER_CACHEMOD
49152       || pPager->eState==PAGER_WRITER_DBMOD
49153       || pPager->eState==PAGER_ERROR
49154  );
49155  assert( assert_pager_state(pPager) );
49156
49157  /* If a prior error occurred, report that error again. */
49158  if( NEVER(pPager->errCode) ) return pPager->errCode;
49159
49160  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
49161      pPager->zFilename, zMaster, pPager->dbSize));
49162
49163  /* If no database changes have been made, return early. */
49164  if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
49165
49166  if( MEMDB ){
49167    /* If this is an in-memory db, or no pages have been written to, or this
49168    ** function has already been called, it is mostly a no-op.  However, any
49169    ** backup in progress needs to be restarted.
49170    */
49171    sqlite3BackupRestart(pPager->pBackup);
49172  }else{
49173    if( pagerUseWal(pPager) ){
49174      PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
49175      PgHdr *pPageOne = 0;
49176      if( pList==0 ){
49177        /* Must have at least one page for the WAL commit flag.
49178        ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
49179        rc = sqlite3PagerGet(pPager, 1, &pPageOne);
49180        pList = pPageOne;
49181        pList->pDirty = 0;
49182      }
49183      assert( rc==SQLITE_OK );
49184      if( ALWAYS(pList) ){
49185        rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
49186      }
49187      sqlite3PagerUnref(pPageOne);
49188      if( rc==SQLITE_OK ){
49189        sqlite3PcacheCleanAll(pPager->pPCache);
49190      }
49191    }else{
49192      /* The following block updates the change-counter. Exactly how it
49193      ** does this depends on whether or not the atomic-update optimization
49194      ** was enabled at compile time, and if this transaction meets the
49195      ** runtime criteria to use the operation:
49196      **
49197      **    * The file-system supports the atomic-write property for
49198      **      blocks of size page-size, and
49199      **    * This commit is not part of a multi-file transaction, and
49200      **    * Exactly one page has been modified and store in the journal file.
49201      **
49202      ** If the optimization was not enabled at compile time, then the
49203      ** pager_incr_changecounter() function is called to update the change
49204      ** counter in 'indirect-mode'. If the optimization is compiled in but
49205      ** is not applicable to this transaction, call sqlite3JournalCreate()
49206      ** to make sure the journal file has actually been created, then call
49207      ** pager_incr_changecounter() to update the change-counter in indirect
49208      ** mode.
49209      **
49210      ** Otherwise, if the optimization is both enabled and applicable,
49211      ** then call pager_incr_changecounter() to update the change-counter
49212      ** in 'direct' mode. In this case the journal file will never be
49213      ** created for this transaction.
49214      */
49215  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
49216      PgHdr *pPg;
49217      assert( isOpen(pPager->jfd)
49218           || pPager->journalMode==PAGER_JOURNALMODE_OFF
49219           || pPager->journalMode==PAGER_JOURNALMODE_WAL
49220      );
49221      if( !zMaster && isOpen(pPager->jfd)
49222       && pPager->journalOff==jrnlBufferSize(pPager)
49223       && pPager->dbSize>=pPager->dbOrigSize
49224       && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
49225      ){
49226        /* Update the db file change counter via the direct-write method. The
49227        ** following call will modify the in-memory representation of page 1
49228        ** to include the updated change counter and then write page 1
49229        ** directly to the database file. Because of the atomic-write
49230        ** property of the host file-system, this is safe.
49231        */
49232        rc = pager_incr_changecounter(pPager, 1);
49233      }else{
49234        rc = sqlite3JournalCreate(pPager->jfd);
49235        if( rc==SQLITE_OK ){
49236          rc = pager_incr_changecounter(pPager, 0);
49237        }
49238      }
49239  #else
49240      rc = pager_incr_changecounter(pPager, 0);
49241  #endif
49242      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
49243
49244      /* Write the master journal name into the journal file. If a master
49245      ** journal file name has already been written to the journal file,
49246      ** or if zMaster is NULL (no master journal), then this call is a no-op.
49247      */
49248      rc = writeMasterJournal(pPager, zMaster);
49249      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
49250
49251      /* Sync the journal file and write all dirty pages to the database.
49252      ** If the atomic-update optimization is being used, this sync will not
49253      ** create the journal file or perform any real IO.
49254      **
49255      ** Because the change-counter page was just modified, unless the
49256      ** atomic-update optimization is used it is almost certain that the
49257      ** journal requires a sync here. However, in locking_mode=exclusive
49258      ** on a system under memory pressure it is just possible that this is
49259      ** not the case. In this case it is likely enough that the redundant
49260      ** xSync() call will be changed to a no-op by the OS anyhow.
49261      */
49262      rc = syncJournal(pPager, 0);
49263      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
49264
49265      rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
49266      if( rc!=SQLITE_OK ){
49267        assert( rc!=SQLITE_IOERR_BLOCKED );
49268        goto commit_phase_one_exit;
49269      }
49270      sqlite3PcacheCleanAll(pPager->pPCache);
49271
49272      /* If the file on disk is smaller than the database image, use
49273      ** pager_truncate to grow the file here. This can happen if the database
49274      ** image was extended as part of the current transaction and then the
49275      ** last page in the db image moved to the free-list. In this case the
49276      ** last page is never written out to disk, leaving the database file
49277      ** undersized. Fix this now if it is the case.  */
49278      if( pPager->dbSize>pPager->dbFileSize ){
49279        Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
49280        assert( pPager->eState==PAGER_WRITER_DBMOD );
49281        rc = pager_truncate(pPager, nNew);
49282        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
49283      }
49284
49285      /* Finally, sync the database file. */
49286      if( !noSync ){
49287        rc = sqlite3PagerSync(pPager, zMaster);
49288      }
49289      IOTRACE(("DBSYNC %p\n", pPager))
49290    }
49291  }
49292
49293commit_phase_one_exit:
49294  if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
49295    pPager->eState = PAGER_WRITER_FINISHED;
49296  }
49297  return rc;
49298}
49299
49300
49301/*
49302** When this function is called, the database file has been completely
49303** updated to reflect the changes made by the current transaction and
49304** synced to disk. The journal file still exists in the file-system
49305** though, and if a failure occurs at this point it will eventually
49306** be used as a hot-journal and the current transaction rolled back.
49307**
49308** This function finalizes the journal file, either by deleting,
49309** truncating or partially zeroing it, so that it cannot be used
49310** for hot-journal rollback. Once this is done the transaction is
49311** irrevocably committed.
49312**
49313** If an error occurs, an IO error code is returned and the pager
49314** moves into the error state. Otherwise, SQLITE_OK is returned.
49315*/
49316SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
49317  int rc = SQLITE_OK;                  /* Return code */
49318
49319  /* This routine should not be called if a prior error has occurred.
49320  ** But if (due to a coding error elsewhere in the system) it does get
49321  ** called, just return the same error code without doing anything. */
49322  if( NEVER(pPager->errCode) ) return pPager->errCode;
49323
49324  assert( pPager->eState==PAGER_WRITER_LOCKED
49325       || pPager->eState==PAGER_WRITER_FINISHED
49326       || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
49327  );
49328  assert( assert_pager_state(pPager) );
49329
49330  /* An optimization. If the database was not actually modified during
49331  ** this transaction, the pager is running in exclusive-mode and is
49332  ** using persistent journals, then this function is a no-op.
49333  **
49334  ** The start of the journal file currently contains a single journal
49335  ** header with the nRec field set to 0. If such a journal is used as
49336  ** a hot-journal during hot-journal rollback, 0 changes will be made
49337  ** to the database file. So there is no need to zero the journal
49338  ** header. Since the pager is in exclusive mode, there is no need
49339  ** to drop any locks either.
49340  */
49341  if( pPager->eState==PAGER_WRITER_LOCKED
49342   && pPager->exclusiveMode
49343   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
49344  ){
49345    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
49346    pPager->eState = PAGER_READER;
49347    return SQLITE_OK;
49348  }
49349
49350  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
49351  pPager->iDataVersion++;
49352  rc = pager_end_transaction(pPager, pPager->setMaster, 1);
49353  return pager_error(pPager, rc);
49354}
49355
49356/*
49357** If a write transaction is open, then all changes made within the
49358** transaction are reverted and the current write-transaction is closed.
49359** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
49360** state if an error occurs.
49361**
49362** If the pager is already in PAGER_ERROR state when this function is called,
49363** it returns Pager.errCode immediately. No work is performed in this case.
49364**
49365** Otherwise, in rollback mode, this function performs two functions:
49366**
49367**   1) It rolls back the journal file, restoring all database file and
49368**      in-memory cache pages to the state they were in when the transaction
49369**      was opened, and
49370**
49371**   2) It finalizes the journal file, so that it is not used for hot
49372**      rollback at any point in the future.
49373**
49374** Finalization of the journal file (task 2) is only performed if the
49375** rollback is successful.
49376**
49377** In WAL mode, all cache-entries containing data modified within the
49378** current transaction are either expelled from the cache or reverted to
49379** their pre-transaction state by re-reading data from the database or
49380** WAL files. The WAL transaction is then closed.
49381*/
49382SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
49383  int rc = SQLITE_OK;                  /* Return code */
49384  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
49385
49386  /* PagerRollback() is a no-op if called in READER or OPEN state. If
49387  ** the pager is already in the ERROR state, the rollback is not
49388  ** attempted here. Instead, the error code is returned to the caller.
49389  */
49390  assert( assert_pager_state(pPager) );
49391  if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
49392  if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
49393
49394  if( pagerUseWal(pPager) ){
49395    int rc2;
49396    rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
49397    rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
49398    if( rc==SQLITE_OK ) rc = rc2;
49399  }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
49400    int eState = pPager->eState;
49401    rc = pager_end_transaction(pPager, 0, 0);
49402    if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
49403      /* This can happen using journal_mode=off. Move the pager to the error
49404      ** state to indicate that the contents of the cache may not be trusted.
49405      ** Any active readers will get SQLITE_ABORT.
49406      */
49407      pPager->errCode = SQLITE_ABORT;
49408      pPager->eState = PAGER_ERROR;
49409      return rc;
49410    }
49411  }else{
49412    rc = pager_playback(pPager, 0);
49413  }
49414
49415  assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
49416  assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
49417          || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
49418          || rc==SQLITE_CANTOPEN
49419  );
49420
49421  /* If an error occurs during a ROLLBACK, we can no longer trust the pager
49422  ** cache. So call pager_error() on the way out to make any error persistent.
49423  */
49424  return pager_error(pPager, rc);
49425}
49426
49427/*
49428** Return TRUE if the database file is opened read-only.  Return FALSE
49429** if the database is (in theory) writable.
49430*/
49431SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
49432  return pPager->readOnly;
49433}
49434
49435#ifdef SQLITE_DEBUG
49436/*
49437** Return the sum of the reference counts for all pages held by pPager.
49438*/
49439SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
49440  return sqlite3PcacheRefCount(pPager->pPCache);
49441}
49442#endif
49443
49444/*
49445** Return the approximate number of bytes of memory currently
49446** used by the pager and its associated cache.
49447*/
49448SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
49449  int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
49450                                     + 5*sizeof(void*);
49451  return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
49452           + sqlite3MallocSize(pPager)
49453           + pPager->pageSize;
49454}
49455
49456/*
49457** Return the number of references to the specified page.
49458*/
49459SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
49460  return sqlite3PcachePageRefcount(pPage);
49461}
49462
49463#ifdef SQLITE_TEST
49464/*
49465** This routine is used for testing and analysis only.
49466*/
49467SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
49468  static int a[11];
49469  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
49470  a[1] = sqlite3PcachePagecount(pPager->pPCache);
49471  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
49472  a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
49473  a[4] = pPager->eState;
49474  a[5] = pPager->errCode;
49475  a[6] = pPager->aStat[PAGER_STAT_HIT];
49476  a[7] = pPager->aStat[PAGER_STAT_MISS];
49477  a[8] = 0;  /* Used to be pPager->nOvfl */
49478  a[9] = pPager->nRead;
49479  a[10] = pPager->aStat[PAGER_STAT_WRITE];
49480  return a;
49481}
49482#endif
49483
49484/*
49485** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
49486** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
49487** current cache hit or miss count, according to the value of eStat. If the
49488** reset parameter is non-zero, the cache hit or miss count is zeroed before
49489** returning.
49490*/
49491SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
49492
49493  assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
49494       || eStat==SQLITE_DBSTATUS_CACHE_MISS
49495       || eStat==SQLITE_DBSTATUS_CACHE_WRITE
49496  );
49497
49498  assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
49499  assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
49500  assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
49501
49502  *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
49503  if( reset ){
49504    pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
49505  }
49506}
49507
49508/*
49509** Return true if this is an in-memory pager.
49510*/
49511SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
49512  return MEMDB;
49513}
49514
49515/*
49516** Check that there are at least nSavepoint savepoints open. If there are
49517** currently less than nSavepoints open, then open one or more savepoints
49518** to make up the difference. If the number of savepoints is already
49519** equal to nSavepoint, then this function is a no-op.
49520**
49521** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
49522** occurs while opening the sub-journal file, then an IO error code is
49523** returned. Otherwise, SQLITE_OK.
49524*/
49525static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
49526  int rc = SQLITE_OK;                       /* Return code */
49527  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
49528  int ii;                                   /* Iterator variable */
49529  PagerSavepoint *aNew;                     /* New Pager.aSavepoint array */
49530
49531  assert( pPager->eState>=PAGER_WRITER_LOCKED );
49532  assert( assert_pager_state(pPager) );
49533  assert( nSavepoint>nCurrent && pPager->useJournal );
49534
49535  /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
49536  ** if the allocation fails. Otherwise, zero the new portion in case a
49537  ** malloc failure occurs while populating it in the for(...) loop below.
49538  */
49539  aNew = (PagerSavepoint *)sqlite3Realloc(
49540      pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
49541  );
49542  if( !aNew ){
49543    return SQLITE_NOMEM;
49544  }
49545  memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
49546  pPager->aSavepoint = aNew;
49547
49548  /* Populate the PagerSavepoint structures just allocated. */
49549  for(ii=nCurrent; ii<nSavepoint; ii++){
49550    aNew[ii].nOrig = pPager->dbSize;
49551    if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
49552      aNew[ii].iOffset = pPager->journalOff;
49553    }else{
49554      aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
49555    }
49556    aNew[ii].iSubRec = pPager->nSubRec;
49557    aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
49558    if( !aNew[ii].pInSavepoint ){
49559      return SQLITE_NOMEM;
49560    }
49561    if( pagerUseWal(pPager) ){
49562      sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
49563    }
49564    pPager->nSavepoint = ii+1;
49565  }
49566  assert( pPager->nSavepoint==nSavepoint );
49567  assertTruncateConstraint(pPager);
49568  return rc;
49569}
49570SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
49571  assert( pPager->eState>=PAGER_WRITER_LOCKED );
49572  assert( assert_pager_state(pPager) );
49573
49574  if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
49575    return pagerOpenSavepoint(pPager, nSavepoint);
49576  }else{
49577    return SQLITE_OK;
49578  }
49579}
49580
49581
49582/*
49583** This function is called to rollback or release (commit) a savepoint.
49584** The savepoint to release or rollback need not be the most recently
49585** created savepoint.
49586**
49587** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
49588** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
49589** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
49590** that have occurred since the specified savepoint was created.
49591**
49592** The savepoint to rollback or release is identified by parameter
49593** iSavepoint. A value of 0 means to operate on the outermost savepoint
49594** (the first created). A value of (Pager.nSavepoint-1) means operate
49595** on the most recently created savepoint. If iSavepoint is greater than
49596** (Pager.nSavepoint-1), then this function is a no-op.
49597**
49598** If a negative value is passed to this function, then the current
49599** transaction is rolled back. This is different to calling
49600** sqlite3PagerRollback() because this function does not terminate
49601** the transaction or unlock the database, it just restores the
49602** contents of the database to its original state.
49603**
49604** In any case, all savepoints with an index greater than iSavepoint
49605** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
49606** then savepoint iSavepoint is also destroyed.
49607**
49608** This function may return SQLITE_NOMEM if a memory allocation fails,
49609** or an IO error code if an IO error occurs while rolling back a
49610** savepoint. If no errors occur, SQLITE_OK is returned.
49611*/
49612SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
49613  int rc = pPager->errCode;       /* Return code */
49614
49615  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
49616  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
49617
49618  if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
49619    int ii;            /* Iterator variable */
49620    int nNew;          /* Number of remaining savepoints after this op. */
49621
49622    /* Figure out how many savepoints will still be active after this
49623    ** operation. Store this value in nNew. Then free resources associated
49624    ** with any savepoints that are destroyed by this operation.
49625    */
49626    nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
49627    for(ii=nNew; ii<pPager->nSavepoint; ii++){
49628      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
49629    }
49630    pPager->nSavepoint = nNew;
49631
49632    /* If this is a release of the outermost savepoint, truncate
49633    ** the sub-journal to zero bytes in size. */
49634    if( op==SAVEPOINT_RELEASE ){
49635      if( nNew==0 && isOpen(pPager->sjfd) ){
49636        /* Only truncate if it is an in-memory sub-journal. */
49637        if( sqlite3IsMemJournal(pPager->sjfd) ){
49638          rc = sqlite3OsTruncate(pPager->sjfd, 0);
49639          assert( rc==SQLITE_OK );
49640        }
49641        pPager->nSubRec = 0;
49642      }
49643    }
49644    /* Else this is a rollback operation, playback the specified savepoint.
49645    ** If this is a temp-file, it is possible that the journal file has
49646    ** not yet been opened. In this case there have been no changes to
49647    ** the database file, so the playback operation can be skipped.
49648    */
49649    else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
49650      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
49651      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
49652      assert(rc!=SQLITE_DONE);
49653    }
49654  }
49655
49656  return rc;
49657}
49658
49659/*
49660** Return the full pathname of the database file.
49661**
49662** Except, if the pager is in-memory only, then return an empty string if
49663** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
49664** used to report the filename to the user, for compatibility with legacy
49665** behavior.  But when the Btree needs to know the filename for matching to
49666** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
49667** participate in shared-cache.
49668*/
49669SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
49670  return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
49671}
49672
49673/*
49674** Return the VFS structure for the pager.
49675*/
49676SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
49677  return pPager->pVfs;
49678}
49679
49680/*
49681** Return the file handle for the database file associated
49682** with the pager.  This might return NULL if the file has
49683** not yet been opened.
49684*/
49685SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
49686  return pPager->fd;
49687}
49688
49689/*
49690** Return the full pathname of the journal file.
49691*/
49692SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
49693  return pPager->zJournal;
49694}
49695
49696/*
49697** Return true if fsync() calls are disabled for this pager.  Return FALSE
49698** if fsync()s are executed normally.
49699*/
49700SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
49701  return pPager->noSync;
49702}
49703
49704#ifdef SQLITE_HAS_CODEC
49705/*
49706** Set or retrieve the codec for this pager
49707*/
49708SQLITE_PRIVATE void sqlite3PagerSetCodec(
49709  Pager *pPager,
49710  void *(*xCodec)(void*,void*,Pgno,int),
49711  void (*xCodecSizeChng)(void*,int,int),
49712  void (*xCodecFree)(void*),
49713  void *pCodec
49714){
49715  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
49716  pPager->xCodec = pPager->memDb ? 0 : xCodec;
49717  pPager->xCodecSizeChng = xCodecSizeChng;
49718  pPager->xCodecFree = xCodecFree;
49719  pPager->pCodec = pCodec;
49720  pagerReportSize(pPager);
49721}
49722SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
49723  return pPager->pCodec;
49724}
49725
49726/*
49727** This function is called by the wal module when writing page content
49728** into the log file.
49729**
49730** This function returns a pointer to a buffer containing the encrypted
49731** page content. If a malloc fails, this function may return NULL.
49732*/
49733SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
49734  void *aData = 0;
49735  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
49736  return aData;
49737}
49738
49739/*
49740** Return the current pager state
49741*/
49742SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
49743  return pPager->eState;
49744}
49745#endif /* SQLITE_HAS_CODEC */
49746
49747#ifndef SQLITE_OMIT_AUTOVACUUM
49748/*
49749** Move the page pPg to location pgno in the file.
49750**
49751** There must be no references to the page previously located at
49752** pgno (which we call pPgOld) though that page is allowed to be
49753** in cache.  If the page previously located at pgno is not already
49754** in the rollback journal, it is not put there by by this routine.
49755**
49756** References to the page pPg remain valid. Updating any
49757** meta-data associated with pPg (i.e. data stored in the nExtra bytes
49758** allocated along with the page) is the responsibility of the caller.
49759**
49760** A transaction must be active when this routine is called. It used to be
49761** required that a statement transaction was not active, but this restriction
49762** has been removed (CREATE INDEX needs to move a page when a statement
49763** transaction is active).
49764**
49765** If the fourth argument, isCommit, is non-zero, then this page is being
49766** moved as part of a database reorganization just before the transaction
49767** is being committed. In this case, it is guaranteed that the database page
49768** pPg refers to will not be written to again within this transaction.
49769**
49770** This function may return SQLITE_NOMEM or an IO error code if an error
49771** occurs. Otherwise, it returns SQLITE_OK.
49772*/
49773SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
49774  PgHdr *pPgOld;               /* The page being overwritten. */
49775  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
49776  int rc;                      /* Return code */
49777  Pgno origPgno;               /* The original page number */
49778
49779  assert( pPg->nRef>0 );
49780  assert( pPager->eState==PAGER_WRITER_CACHEMOD
49781       || pPager->eState==PAGER_WRITER_DBMOD
49782  );
49783  assert( assert_pager_state(pPager) );
49784
49785  /* In order to be able to rollback, an in-memory database must journal
49786  ** the page we are moving from.
49787  */
49788  if( MEMDB ){
49789    rc = sqlite3PagerWrite(pPg);
49790    if( rc ) return rc;
49791  }
49792
49793  /* If the page being moved is dirty and has not been saved by the latest
49794  ** savepoint, then save the current contents of the page into the
49795  ** sub-journal now. This is required to handle the following scenario:
49796  **
49797  **   BEGIN;
49798  **     <journal page X, then modify it in memory>
49799  **     SAVEPOINT one;
49800  **       <Move page X to location Y>
49801  **     ROLLBACK TO one;
49802  **
49803  ** If page X were not written to the sub-journal here, it would not
49804  ** be possible to restore its contents when the "ROLLBACK TO one"
49805  ** statement were is processed.
49806  **
49807  ** subjournalPage() may need to allocate space to store pPg->pgno into
49808  ** one or more savepoint bitvecs. This is the reason this function
49809  ** may return SQLITE_NOMEM.
49810  */
49811  if( (pPg->flags & PGHDR_DIRTY)!=0
49812   && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
49813  ){
49814    return rc;
49815  }
49816
49817  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
49818      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
49819  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
49820
49821  /* If the journal needs to be sync()ed before page pPg->pgno can
49822  ** be written to, store pPg->pgno in local variable needSyncPgno.
49823  **
49824  ** If the isCommit flag is set, there is no need to remember that
49825  ** the journal needs to be sync()ed before database page pPg->pgno
49826  ** can be written to. The caller has already promised not to write to it.
49827  */
49828  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
49829    needSyncPgno = pPg->pgno;
49830    assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
49831            pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
49832    assert( pPg->flags&PGHDR_DIRTY );
49833  }
49834
49835  /* If the cache contains a page with page-number pgno, remove it
49836  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
49837  ** page pgno before the 'move' operation, it needs to be retained
49838  ** for the page moved there.
49839  */
49840  pPg->flags &= ~PGHDR_NEED_SYNC;
49841  pPgOld = sqlite3PagerLookup(pPager, pgno);
49842  assert( !pPgOld || pPgOld->nRef==1 );
49843  if( pPgOld ){
49844    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
49845    if( MEMDB ){
49846      /* Do not discard pages from an in-memory database since we might
49847      ** need to rollback later.  Just move the page out of the way. */
49848      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
49849    }else{
49850      sqlite3PcacheDrop(pPgOld);
49851    }
49852  }
49853
49854  origPgno = pPg->pgno;
49855  sqlite3PcacheMove(pPg, pgno);
49856  sqlite3PcacheMakeDirty(pPg);
49857
49858  /* For an in-memory database, make sure the original page continues
49859  ** to exist, in case the transaction needs to roll back.  Use pPgOld
49860  ** as the original page since it has already been allocated.
49861  */
49862  if( MEMDB ){
49863    assert( pPgOld );
49864    sqlite3PcacheMove(pPgOld, origPgno);
49865    sqlite3PagerUnrefNotNull(pPgOld);
49866  }
49867
49868  if( needSyncPgno ){
49869    /* If needSyncPgno is non-zero, then the journal file needs to be
49870    ** sync()ed before any data is written to database file page needSyncPgno.
49871    ** Currently, no such page exists in the page-cache and the
49872    ** "is journaled" bitvec flag has been set. This needs to be remedied by
49873    ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
49874    ** flag.
49875    **
49876    ** If the attempt to load the page into the page-cache fails, (due
49877    ** to a malloc() or IO failure), clear the bit in the pInJournal[]
49878    ** array. Otherwise, if the page is loaded and written again in
49879    ** this transaction, it may be written to the database file before
49880    ** it is synced into the journal file. This way, it may end up in
49881    ** the journal file twice, but that is not a problem.
49882    */
49883    PgHdr *pPgHdr;
49884    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
49885    if( rc!=SQLITE_OK ){
49886      if( needSyncPgno<=pPager->dbOrigSize ){
49887        assert( pPager->pTmpSpace!=0 );
49888        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
49889      }
49890      return rc;
49891    }
49892    pPgHdr->flags |= PGHDR_NEED_SYNC;
49893    sqlite3PcacheMakeDirty(pPgHdr);
49894    sqlite3PagerUnrefNotNull(pPgHdr);
49895  }
49896
49897  return SQLITE_OK;
49898}
49899#endif
49900
49901/*
49902** The page handle passed as the first argument refers to a dirty page
49903** with a page number other than iNew. This function changes the page's
49904** page number to iNew and sets the value of the PgHdr.flags field to
49905** the value passed as the third parameter.
49906*/
49907SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
49908  assert( pPg->pgno!=iNew );
49909  pPg->flags = flags;
49910  sqlite3PcacheMove(pPg, iNew);
49911}
49912
49913/*
49914** Return a pointer to the data for the specified page.
49915*/
49916SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
49917  assert( pPg->nRef>0 || pPg->pPager->memDb );
49918  return pPg->pData;
49919}
49920
49921/*
49922** Return a pointer to the Pager.nExtra bytes of "extra" space
49923** allocated along with the specified page.
49924*/
49925SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
49926  return pPg->pExtra;
49927}
49928
49929/*
49930** Get/set the locking-mode for this pager. Parameter eMode must be one
49931** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
49932** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
49933** the locking-mode is set to the value specified.
49934**
49935** The returned value is either PAGER_LOCKINGMODE_NORMAL or
49936** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
49937** locking-mode.
49938*/
49939SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
49940  assert( eMode==PAGER_LOCKINGMODE_QUERY
49941            || eMode==PAGER_LOCKINGMODE_NORMAL
49942            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
49943  assert( PAGER_LOCKINGMODE_QUERY<0 );
49944  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
49945  assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
49946  if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
49947    pPager->exclusiveMode = (u8)eMode;
49948  }
49949  return (int)pPager->exclusiveMode;
49950}
49951
49952/*
49953** Set the journal-mode for this pager. Parameter eMode must be one of:
49954**
49955**    PAGER_JOURNALMODE_DELETE
49956**    PAGER_JOURNALMODE_TRUNCATE
49957**    PAGER_JOURNALMODE_PERSIST
49958**    PAGER_JOURNALMODE_OFF
49959**    PAGER_JOURNALMODE_MEMORY
49960**    PAGER_JOURNALMODE_WAL
49961**
49962** The journalmode is set to the value specified if the change is allowed.
49963** The change may be disallowed for the following reasons:
49964**
49965**   *  An in-memory database can only have its journal_mode set to _OFF
49966**      or _MEMORY.
49967**
49968**   *  Temporary databases cannot have _WAL journalmode.
49969**
49970** The returned indicate the current (possibly updated) journal-mode.
49971*/
49972SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
49973  u8 eOld = pPager->journalMode;    /* Prior journalmode */
49974
49975#ifdef SQLITE_DEBUG
49976  /* The print_pager_state() routine is intended to be used by the debugger
49977  ** only.  We invoke it once here to suppress a compiler warning. */
49978  print_pager_state(pPager);
49979#endif
49980
49981
49982  /* The eMode parameter is always valid */
49983  assert(      eMode==PAGER_JOURNALMODE_DELETE
49984            || eMode==PAGER_JOURNALMODE_TRUNCATE
49985            || eMode==PAGER_JOURNALMODE_PERSIST
49986            || eMode==PAGER_JOURNALMODE_OFF
49987            || eMode==PAGER_JOURNALMODE_WAL
49988            || eMode==PAGER_JOURNALMODE_MEMORY );
49989
49990  /* This routine is only called from the OP_JournalMode opcode, and
49991  ** the logic there will never allow a temporary file to be changed
49992  ** to WAL mode.
49993  */
49994  assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
49995
49996  /* Do allow the journalmode of an in-memory database to be set to
49997  ** anything other than MEMORY or OFF
49998  */
49999  if( MEMDB ){
50000    assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
50001    if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
50002      eMode = eOld;
50003    }
50004  }
50005
50006  if( eMode!=eOld ){
50007
50008    /* Change the journal mode. */
50009    assert( pPager->eState!=PAGER_ERROR );
50010    pPager->journalMode = (u8)eMode;
50011
50012    /* When transistioning from TRUNCATE or PERSIST to any other journal
50013    ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
50014    ** delete the journal file.
50015    */
50016    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
50017    assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
50018    assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
50019    assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
50020    assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
50021    assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
50022
50023    assert( isOpen(pPager->fd) || pPager->exclusiveMode );
50024    if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
50025
50026      /* In this case we would like to delete the journal file. If it is
50027      ** not possible, then that is not a problem. Deleting the journal file
50028      ** here is an optimization only.
50029      **
50030      ** Before deleting the journal file, obtain a RESERVED lock on the
50031      ** database file. This ensures that the journal file is not deleted
50032      ** while it is in use by some other client.
50033      */
50034      sqlite3OsClose(pPager->jfd);
50035      if( pPager->eLock>=RESERVED_LOCK ){
50036        sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
50037      }else{
50038        int rc = SQLITE_OK;
50039        int state = pPager->eState;
50040        assert( state==PAGER_OPEN || state==PAGER_READER );
50041        if( state==PAGER_OPEN ){
50042          rc = sqlite3PagerSharedLock(pPager);
50043        }
50044        if( pPager->eState==PAGER_READER ){
50045          assert( rc==SQLITE_OK );
50046          rc = pagerLockDb(pPager, RESERVED_LOCK);
50047        }
50048        if( rc==SQLITE_OK ){
50049          sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
50050        }
50051        if( rc==SQLITE_OK && state==PAGER_READER ){
50052          pagerUnlockDb(pPager, SHARED_LOCK);
50053        }else if( state==PAGER_OPEN ){
50054          pager_unlock(pPager);
50055        }
50056        assert( state==pPager->eState );
50057      }
50058    }else if( eMode==PAGER_JOURNALMODE_OFF ){
50059      sqlite3OsClose(pPager->jfd);
50060    }
50061  }
50062
50063  /* Return the new journal mode */
50064  return (int)pPager->journalMode;
50065}
50066
50067/*
50068** Return the current journal mode.
50069*/
50070SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
50071  return (int)pPager->journalMode;
50072}
50073
50074/*
50075** Return TRUE if the pager is in a state where it is OK to change the
50076** journalmode.  Journalmode changes can only happen when the database
50077** is unmodified.
50078*/
50079SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
50080  assert( assert_pager_state(pPager) );
50081  if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
50082  if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
50083  return 1;
50084}
50085
50086/*
50087** Get/set the size-limit used for persistent journal files.
50088**
50089** Setting the size limit to -1 means no limit is enforced.
50090** An attempt to set a limit smaller than -1 is a no-op.
50091*/
50092SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
50093  if( iLimit>=-1 ){
50094    pPager->journalSizeLimit = iLimit;
50095    sqlite3WalLimit(pPager->pWal, iLimit);
50096  }
50097  return pPager->journalSizeLimit;
50098}
50099
50100/*
50101** Return a pointer to the pPager->pBackup variable. The backup module
50102** in backup.c maintains the content of this variable. This module
50103** uses it opaquely as an argument to sqlite3BackupRestart() and
50104** sqlite3BackupUpdate() only.
50105*/
50106SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
50107  return &pPager->pBackup;
50108}
50109
50110#ifndef SQLITE_OMIT_VACUUM
50111/*
50112** Unless this is an in-memory or temporary database, clear the pager cache.
50113*/
50114SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
50115  if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
50116}
50117#endif
50118
50119#ifndef SQLITE_OMIT_WAL
50120/*
50121** This function is called when the user invokes "PRAGMA wal_checkpoint",
50122** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
50123** or wal_blocking_checkpoint() API functions.
50124**
50125** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
50126*/
50127SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
50128  int rc = SQLITE_OK;
50129  if( pPager->pWal ){
50130    rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
50131        (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
50132        pPager->pBusyHandlerArg,
50133        pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
50134        pnLog, pnCkpt
50135    );
50136  }
50137  return rc;
50138}
50139
50140SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
50141  return sqlite3WalCallback(pPager->pWal);
50142}
50143
50144/*
50145** Return true if the underlying VFS for the given pager supports the
50146** primitives necessary for write-ahead logging.
50147*/
50148SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
50149  const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
50150  return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
50151}
50152
50153/*
50154** Attempt to take an exclusive lock on the database file. If a PENDING lock
50155** is obtained instead, immediately release it.
50156*/
50157static int pagerExclusiveLock(Pager *pPager){
50158  int rc;                         /* Return code */
50159
50160  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
50161  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
50162  if( rc!=SQLITE_OK ){
50163    /* If the attempt to grab the exclusive lock failed, release the
50164    ** pending lock that may have been obtained instead.  */
50165    pagerUnlockDb(pPager, SHARED_LOCK);
50166  }
50167
50168  return rc;
50169}
50170
50171/*
50172** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
50173** exclusive-locking mode when this function is called, take an EXCLUSIVE
50174** lock on the database file and use heap-memory to store the wal-index
50175** in. Otherwise, use the normal shared-memory.
50176*/
50177static int pagerOpenWal(Pager *pPager){
50178  int rc = SQLITE_OK;
50179
50180  assert( pPager->pWal==0 && pPager->tempFile==0 );
50181  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
50182
50183  /* If the pager is already in exclusive-mode, the WAL module will use
50184  ** heap-memory for the wal-index instead of the VFS shared-memory
50185  ** implementation. Take the exclusive lock now, before opening the WAL
50186  ** file, to make sure this is safe.
50187  */
50188  if( pPager->exclusiveMode ){
50189    rc = pagerExclusiveLock(pPager);
50190  }
50191
50192  /* Open the connection to the log file. If this operation fails,
50193  ** (e.g. due to malloc() failure), return an error code.
50194  */
50195  if( rc==SQLITE_OK ){
50196    rc = sqlite3WalOpen(pPager->pVfs,
50197        pPager->fd, pPager->zWal, pPager->exclusiveMode,
50198        pPager->journalSizeLimit, &pPager->pWal
50199    );
50200  }
50201  pagerFixMaplimit(pPager);
50202
50203  return rc;
50204}
50205
50206
50207/*
50208** The caller must be holding a SHARED lock on the database file to call
50209** this function.
50210**
50211** If the pager passed as the first argument is open on a real database
50212** file (not a temp file or an in-memory database), and the WAL file
50213** is not already open, make an attempt to open it now. If successful,
50214** return SQLITE_OK. If an error occurs or the VFS used by the pager does
50215** not support the xShmXXX() methods, return an error code. *pbOpen is
50216** not modified in either case.
50217**
50218** If the pager is open on a temp-file (or in-memory database), or if
50219** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
50220** without doing anything.
50221*/
50222SQLITE_PRIVATE int sqlite3PagerOpenWal(
50223  Pager *pPager,                  /* Pager object */
50224  int *pbOpen                     /* OUT: Set to true if call is a no-op */
50225){
50226  int rc = SQLITE_OK;             /* Return code */
50227
50228  assert( assert_pager_state(pPager) );
50229  assert( pPager->eState==PAGER_OPEN   || pbOpen );
50230  assert( pPager->eState==PAGER_READER || !pbOpen );
50231  assert( pbOpen==0 || *pbOpen==0 );
50232  assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
50233
50234  if( !pPager->tempFile && !pPager->pWal ){
50235    if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
50236
50237    /* Close any rollback journal previously open */
50238    sqlite3OsClose(pPager->jfd);
50239
50240    rc = pagerOpenWal(pPager);
50241    if( rc==SQLITE_OK ){
50242      pPager->journalMode = PAGER_JOURNALMODE_WAL;
50243      pPager->eState = PAGER_OPEN;
50244    }
50245  }else{
50246    *pbOpen = 1;
50247  }
50248
50249  return rc;
50250}
50251
50252/*
50253** This function is called to close the connection to the log file prior
50254** to switching from WAL to rollback mode.
50255**
50256** Before closing the log file, this function attempts to take an
50257** EXCLUSIVE lock on the database file. If this cannot be obtained, an
50258** error (SQLITE_BUSY) is returned and the log connection is not closed.
50259** If successful, the EXCLUSIVE lock is not released before returning.
50260*/
50261SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
50262  int rc = SQLITE_OK;
50263
50264  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
50265
50266  /* If the log file is not already open, but does exist in the file-system,
50267  ** it may need to be checkpointed before the connection can switch to
50268  ** rollback mode. Open it now so this can happen.
50269  */
50270  if( !pPager->pWal ){
50271    int logexists = 0;
50272    rc = pagerLockDb(pPager, SHARED_LOCK);
50273    if( rc==SQLITE_OK ){
50274      rc = sqlite3OsAccess(
50275          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
50276      );
50277    }
50278    if( rc==SQLITE_OK && logexists ){
50279      rc = pagerOpenWal(pPager);
50280    }
50281  }
50282
50283  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
50284  ** the database file, the log and log-summary files will be deleted.
50285  */
50286  if( rc==SQLITE_OK && pPager->pWal ){
50287    rc = pagerExclusiveLock(pPager);
50288    if( rc==SQLITE_OK ){
50289      rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
50290                           pPager->pageSize, (u8*)pPager->pTmpSpace);
50291      pPager->pWal = 0;
50292      pagerFixMaplimit(pPager);
50293    }
50294  }
50295  return rc;
50296}
50297
50298#endif /* !SQLITE_OMIT_WAL */
50299
50300#ifdef SQLITE_ENABLE_ZIPVFS
50301/*
50302** A read-lock must be held on the pager when this function is called. If
50303** the pager is in WAL mode and the WAL file currently contains one or more
50304** frames, return the size in bytes of the page images stored within the
50305** WAL frames. Otherwise, if this is not a WAL database or the WAL file
50306** is empty, return 0.
50307*/
50308SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
50309  assert( pPager->eState>=PAGER_READER );
50310  return sqlite3WalFramesize(pPager->pWal);
50311}
50312#endif
50313
50314
50315#endif /* SQLITE_OMIT_DISKIO */
50316
50317/************** End of pager.c ***********************************************/
50318/************** Begin file wal.c *********************************************/
50319/*
50320** 2010 February 1
50321**
50322** The author disclaims copyright to this source code.  In place of
50323** a legal notice, here is a blessing:
50324**
50325**    May you do good and not evil.
50326**    May you find forgiveness for yourself and forgive others.
50327**    May you share freely, never taking more than you give.
50328**
50329*************************************************************************
50330**
50331** This file contains the implementation of a write-ahead log (WAL) used in
50332** "journal_mode=WAL" mode.
50333**
50334** WRITE-AHEAD LOG (WAL) FILE FORMAT
50335**
50336** A WAL file consists of a header followed by zero or more "frames".
50337** Each frame records the revised content of a single page from the
50338** database file.  All changes to the database are recorded by writing
50339** frames into the WAL.  Transactions commit when a frame is written that
50340** contains a commit marker.  A single WAL can and usually does record
50341** multiple transactions.  Periodically, the content of the WAL is
50342** transferred back into the database file in an operation called a
50343** "checkpoint".
50344**
50345** A single WAL file can be used multiple times.  In other words, the
50346** WAL can fill up with frames and then be checkpointed and then new
50347** frames can overwrite the old ones.  A WAL always grows from beginning
50348** toward the end.  Checksums and counters attached to each frame are
50349** used to determine which frames within the WAL are valid and which
50350** are leftovers from prior checkpoints.
50351**
50352** The WAL header is 32 bytes in size and consists of the following eight
50353** big-endian 32-bit unsigned integer values:
50354**
50355**     0: Magic number.  0x377f0682 or 0x377f0683
50356**     4: File format version.  Currently 3007000
50357**     8: Database page size.  Example: 1024
50358**    12: Checkpoint sequence number
50359**    16: Salt-1, random integer incremented with each checkpoint
50360**    20: Salt-2, a different random integer changing with each ckpt
50361**    24: Checksum-1 (first part of checksum for first 24 bytes of header).
50362**    28: Checksum-2 (second part of checksum for first 24 bytes of header).
50363**
50364** Immediately following the wal-header are zero or more frames. Each
50365** frame consists of a 24-byte frame-header followed by a <page-size> bytes
50366** of page data. The frame-header is six big-endian 32-bit unsigned
50367** integer values, as follows:
50368**
50369**     0: Page number.
50370**     4: For commit records, the size of the database image in pages
50371**        after the commit. For all other records, zero.
50372**     8: Salt-1 (copied from the header)
50373**    12: Salt-2 (copied from the header)
50374**    16: Checksum-1.
50375**    20: Checksum-2.
50376**
50377** A frame is considered valid if and only if the following conditions are
50378** true:
50379**
50380**    (1) The salt-1 and salt-2 values in the frame-header match
50381**        salt values in the wal-header
50382**
50383**    (2) The checksum values in the final 8 bytes of the frame-header
50384**        exactly match the checksum computed consecutively on the
50385**        WAL header and the first 8 bytes and the content of all frames
50386**        up to and including the current frame.
50387**
50388** The checksum is computed using 32-bit big-endian integers if the
50389** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
50390** is computed using little-endian if the magic number is 0x377f0682.
50391** The checksum values are always stored in the frame header in a
50392** big-endian format regardless of which byte order is used to compute
50393** the checksum.  The checksum is computed by interpreting the input as
50394** an even number of unsigned 32-bit integers: x[0] through x[N].  The
50395** algorithm used for the checksum is as follows:
50396**
50397**   for i from 0 to n-1 step 2:
50398**     s0 += x[i] + s1;
50399**     s1 += x[i+1] + s0;
50400**   endfor
50401**
50402** Note that s0 and s1 are both weighted checksums using fibonacci weights
50403** in reverse order (the largest fibonacci weight occurs on the first element
50404** of the sequence being summed.)  The s1 value spans all 32-bit
50405** terms of the sequence whereas s0 omits the final term.
50406**
50407** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
50408** WAL is transferred into the database, then the database is VFS.xSync-ed.
50409** The VFS.xSync operations serve as write barriers - all writes launched
50410** before the xSync must complete before any write that launches after the
50411** xSync begins.
50412**
50413** After each checkpoint, the salt-1 value is incremented and the salt-2
50414** value is randomized.  This prevents old and new frames in the WAL from
50415** being considered valid at the same time and being checkpointing together
50416** following a crash.
50417**
50418** READER ALGORITHM
50419**
50420** To read a page from the database (call it page number P), a reader
50421** first checks the WAL to see if it contains page P.  If so, then the
50422** last valid instance of page P that is a followed by a commit frame
50423** or is a commit frame itself becomes the value read.  If the WAL
50424** contains no copies of page P that are valid and which are a commit
50425** frame or are followed by a commit frame, then page P is read from
50426** the database file.
50427**
50428** To start a read transaction, the reader records the index of the last
50429** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
50430** for all subsequent read operations.  New transactions can be appended
50431** to the WAL, but as long as the reader uses its original mxFrame value
50432** and ignores the newly appended content, it will see a consistent snapshot
50433** of the database from a single point in time.  This technique allows
50434** multiple concurrent readers to view different versions of the database
50435** content simultaneously.
50436**
50437** The reader algorithm in the previous paragraphs works correctly, but
50438** because frames for page P can appear anywhere within the WAL, the
50439** reader has to scan the entire WAL looking for page P frames.  If the
50440** WAL is large (multiple megabytes is typical) that scan can be slow,
50441** and read performance suffers.  To overcome this problem, a separate
50442** data structure called the wal-index is maintained to expedite the
50443** search for frames of a particular page.
50444**
50445** WAL-INDEX FORMAT
50446**
50447** Conceptually, the wal-index is shared memory, though VFS implementations
50448** might choose to implement the wal-index using a mmapped file.  Because
50449** the wal-index is shared memory, SQLite does not support journal_mode=WAL
50450** on a network filesystem.  All users of the database must be able to
50451** share memory.
50452**
50453** The wal-index is transient.  After a crash, the wal-index can (and should
50454** be) reconstructed from the original WAL file.  In fact, the VFS is required
50455** to either truncate or zero the header of the wal-index when the last
50456** connection to it closes.  Because the wal-index is transient, it can
50457** use an architecture-specific format; it does not have to be cross-platform.
50458** Hence, unlike the database and WAL file formats which store all values
50459** as big endian, the wal-index can store multi-byte values in the native
50460** byte order of the host computer.
50461**
50462** The purpose of the wal-index is to answer this question quickly:  Given
50463** a page number P and a maximum frame index M, return the index of the
50464** last frame in the wal before frame M for page P in the WAL, or return
50465** NULL if there are no frames for page P in the WAL prior to M.
50466**
50467** The wal-index consists of a header region, followed by an one or
50468** more index blocks.
50469**
50470** The wal-index header contains the total number of frames within the WAL
50471** in the mxFrame field.
50472**
50473** Each index block except for the first contains information on
50474** HASHTABLE_NPAGE frames. The first index block contains information on
50475** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
50476** HASHTABLE_NPAGE are selected so that together the wal-index header and
50477** first index block are the same size as all other index blocks in the
50478** wal-index.
50479**
50480** Each index block contains two sections, a page-mapping that contains the
50481** database page number associated with each wal frame, and a hash-table
50482** that allows readers to query an index block for a specific page number.
50483** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
50484** for the first index block) 32-bit page numbers. The first entry in the
50485** first index-block contains the database page number corresponding to the
50486** first frame in the WAL file. The first entry in the second index block
50487** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
50488** the log, and so on.
50489**
50490** The last index block in a wal-index usually contains less than the full
50491** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
50492** depending on the contents of the WAL file. This does not change the
50493** allocated size of the page-mapping array - the page-mapping array merely
50494** contains unused entries.
50495**
50496** Even without using the hash table, the last frame for page P
50497** can be found by scanning the page-mapping sections of each index block
50498** starting with the last index block and moving toward the first, and
50499** within each index block, starting at the end and moving toward the
50500** beginning.  The first entry that equals P corresponds to the frame
50501** holding the content for that page.
50502**
50503** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
50504** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
50505** hash table for each page number in the mapping section, so the hash
50506** table is never more than half full.  The expected number of collisions
50507** prior to finding a match is 1.  Each entry of the hash table is an
50508** 1-based index of an entry in the mapping section of the same
50509** index block.   Let K be the 1-based index of the largest entry in
50510** the mapping section.  (For index blocks other than the last, K will
50511** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
50512** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
50513** contain a value of 0.
50514**
50515** To look for page P in the hash table, first compute a hash iKey on
50516** P as follows:
50517**
50518**      iKey = (P * 383) % HASHTABLE_NSLOT
50519**
50520** Then start scanning entries of the hash table, starting with iKey
50521** (wrapping around to the beginning when the end of the hash table is
50522** reached) until an unused hash slot is found. Let the first unused slot
50523** be at index iUnused.  (iUnused might be less than iKey if there was
50524** wrap-around.) Because the hash table is never more than half full,
50525** the search is guaranteed to eventually hit an unused entry.  Let
50526** iMax be the value between iKey and iUnused, closest to iUnused,
50527** where aHash[iMax]==P.  If there is no iMax entry (if there exists
50528** no hash slot such that aHash[i]==p) then page P is not in the
50529** current index block.  Otherwise the iMax-th mapping entry of the
50530** current index block corresponds to the last entry that references
50531** page P.
50532**
50533** A hash search begins with the last index block and moves toward the
50534** first index block, looking for entries corresponding to page P.  On
50535** average, only two or three slots in each index block need to be
50536** examined in order to either find the last entry for page P, or to
50537** establish that no such entry exists in the block.  Each index block
50538** holds over 4000 entries.  So two or three index blocks are sufficient
50539** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
50540** comparisons (on average) suffice to either locate a frame in the
50541** WAL or to establish that the frame does not exist in the WAL.  This
50542** is much faster than scanning the entire 10MB WAL.
50543**
50544** Note that entries are added in order of increasing K.  Hence, one
50545** reader might be using some value K0 and a second reader that started
50546** at a later time (after additional transactions were added to the WAL
50547** and to the wal-index) might be using a different value K1, where K1>K0.
50548** Both readers can use the same hash table and mapping section to get
50549** the correct result.  There may be entries in the hash table with
50550** K>K0 but to the first reader, those entries will appear to be unused
50551** slots in the hash table and so the first reader will get an answer as
50552** if no values greater than K0 had ever been inserted into the hash table
50553** in the first place - which is what reader one wants.  Meanwhile, the
50554** second reader using K1 will see additional values that were inserted
50555** later, which is exactly what reader two wants.
50556**
50557** When a rollback occurs, the value of K is decreased. Hash table entries
50558** that correspond to frames greater than the new K value are removed
50559** from the hash table at this point.
50560*/
50561#ifndef SQLITE_OMIT_WAL
50562
50563/* #include "wal.h" */
50564
50565/*
50566** Trace output macros
50567*/
50568#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
50569SQLITE_PRIVATE int sqlite3WalTrace = 0;
50570# define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
50571#else
50572# define WALTRACE(X)
50573#endif
50574
50575/*
50576** The maximum (and only) versions of the wal and wal-index formats
50577** that may be interpreted by this version of SQLite.
50578**
50579** If a client begins recovering a WAL file and finds that (a) the checksum
50580** values in the wal-header are correct and (b) the version field is not
50581** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
50582**
50583** Similarly, if a client successfully reads a wal-index header (i.e. the
50584** checksum test is successful) and finds that the version field is not
50585** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
50586** returns SQLITE_CANTOPEN.
50587*/
50588#define WAL_MAX_VERSION      3007000
50589#define WALINDEX_MAX_VERSION 3007000
50590
50591/*
50592** Indices of various locking bytes.   WAL_NREADER is the number
50593** of available reader locks and should be at least 3.
50594*/
50595#define WAL_WRITE_LOCK         0
50596#define WAL_ALL_BUT_WRITE      1
50597#define WAL_CKPT_LOCK          1
50598#define WAL_RECOVER_LOCK       2
50599#define WAL_READ_LOCK(I)       (3+(I))
50600#define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
50601
50602
50603/* Object declarations */
50604typedef struct WalIndexHdr WalIndexHdr;
50605typedef struct WalIterator WalIterator;
50606typedef struct WalCkptInfo WalCkptInfo;
50607
50608
50609/*
50610** The following object holds a copy of the wal-index header content.
50611**
50612** The actual header in the wal-index consists of two copies of this
50613** object.
50614**
50615** The szPage value can be any power of 2 between 512 and 32768, inclusive.
50616** Or it can be 1 to represent a 65536-byte page.  The latter case was
50617** added in 3.7.1 when support for 64K pages was added.
50618*/
50619struct WalIndexHdr {
50620  u32 iVersion;                   /* Wal-index version */
50621  u32 unused;                     /* Unused (padding) field */
50622  u32 iChange;                    /* Counter incremented each transaction */
50623  u8 isInit;                      /* 1 when initialized */
50624  u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
50625  u16 szPage;                     /* Database page size in bytes. 1==64K */
50626  u32 mxFrame;                    /* Index of last valid frame in the WAL */
50627  u32 nPage;                      /* Size of database in pages */
50628  u32 aFrameCksum[2];             /* Checksum of last frame in log */
50629  u32 aSalt[2];                   /* Two salt values copied from WAL header */
50630  u32 aCksum[2];                  /* Checksum over all prior fields */
50631};
50632
50633/*
50634** A copy of the following object occurs in the wal-index immediately
50635** following the second copy of the WalIndexHdr.  This object stores
50636** information used by checkpoint.
50637**
50638** nBackfill is the number of frames in the WAL that have been written
50639** back into the database. (We call the act of moving content from WAL to
50640** database "backfilling".)  The nBackfill number is never greater than
50641** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
50642** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
50643** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
50644** mxFrame back to zero when the WAL is reset.
50645**
50646** There is one entry in aReadMark[] for each reader lock.  If a reader
50647** holds read-lock K, then the value in aReadMark[K] is no greater than
50648** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
50649** for any aReadMark[] means that entry is unused.  aReadMark[0] is
50650** a special case; its value is never used and it exists as a place-holder
50651** to avoid having to offset aReadMark[] indexs by one.  Readers holding
50652** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
50653** directly from the database.
50654**
50655** The value of aReadMark[K] may only be changed by a thread that
50656** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
50657** aReadMark[K] cannot changed while there is a reader is using that mark
50658** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
50659**
50660** The checkpointer may only transfer frames from WAL to database where
50661** the frame numbers are less than or equal to every aReadMark[] that is
50662** in use (that is, every aReadMark[j] for which there is a corresponding
50663** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
50664** largest value and will increase an unused aReadMark[] to mxFrame if there
50665** is not already an aReadMark[] equal to mxFrame.  The exception to the
50666** previous sentence is when nBackfill equals mxFrame (meaning that everything
50667** in the WAL has been backfilled into the database) then new readers
50668** will choose aReadMark[0] which has value 0 and hence such reader will
50669** get all their all content directly from the database file and ignore
50670** the WAL.
50671**
50672** Writers normally append new frames to the end of the WAL.  However,
50673** if nBackfill equals mxFrame (meaning that all WAL content has been
50674** written back into the database) and if no readers are using the WAL
50675** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
50676** the writer will first "reset" the WAL back to the beginning and start
50677** writing new content beginning at frame 1.
50678**
50679** We assume that 32-bit loads are atomic and so no locks are needed in
50680** order to read from any aReadMark[] entries.
50681*/
50682struct WalCkptInfo {
50683  u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
50684  u32 aReadMark[WAL_NREADER];     /* Reader marks */
50685};
50686#define READMARK_NOT_USED  0xffffffff
50687
50688
50689/* A block of WALINDEX_LOCK_RESERVED bytes beginning at
50690** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
50691** only support mandatory file-locks, we do not read or write data
50692** from the region of the file on which locks are applied.
50693*/
50694#define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
50695#define WALINDEX_LOCK_RESERVED 16
50696#define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
50697
50698/* Size of header before each frame in wal */
50699#define WAL_FRAME_HDRSIZE 24
50700
50701/* Size of write ahead log header, including checksum. */
50702/* #define WAL_HDRSIZE 24 */
50703#define WAL_HDRSIZE 32
50704
50705/* WAL magic value. Either this value, or the same value with the least
50706** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
50707** big-endian format in the first 4 bytes of a WAL file.
50708**
50709** If the LSB is set, then the checksums for each frame within the WAL
50710** file are calculated by treating all data as an array of 32-bit
50711** big-endian words. Otherwise, they are calculated by interpreting
50712** all data as 32-bit little-endian words.
50713*/
50714#define WAL_MAGIC 0x377f0682
50715
50716/*
50717** Return the offset of frame iFrame in the write-ahead log file,
50718** assuming a database page size of szPage bytes. The offset returned
50719** is to the start of the write-ahead log frame-header.
50720*/
50721#define walFrameOffset(iFrame, szPage) (                               \
50722  WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
50723)
50724
50725/*
50726** An open write-ahead log file is represented by an instance of the
50727** following object.
50728*/
50729struct Wal {
50730  sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
50731  sqlite3_file *pDbFd;       /* File handle for the database file */
50732  sqlite3_file *pWalFd;      /* File handle for WAL file */
50733  u32 iCallback;             /* Value to pass to log callback (or 0) */
50734  i64 mxWalSize;             /* Truncate WAL to this size upon reset */
50735  int nWiData;               /* Size of array apWiData */
50736  int szFirstBlock;          /* Size of first block written to WAL file */
50737  volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
50738  u32 szPage;                /* Database page size */
50739  i16 readLock;              /* Which read lock is being held.  -1 for none */
50740  u8 syncFlags;              /* Flags to use to sync header writes */
50741  u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
50742  u8 writeLock;              /* True if in a write transaction */
50743  u8 ckptLock;               /* True if holding a checkpoint lock */
50744  u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
50745  u8 truncateOnCommit;       /* True to truncate WAL file on commit */
50746  u8 syncHeader;             /* Fsync the WAL header if true */
50747  u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
50748  WalIndexHdr hdr;           /* Wal-index header for current transaction */
50749  u32 minFrame;              /* Ignore wal frames before this one */
50750  const char *zWalName;      /* Name of WAL file */
50751  u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
50752#ifdef SQLITE_DEBUG
50753  u8 lockError;              /* True if a locking error has occurred */
50754#endif
50755};
50756
50757/*
50758** Candidate values for Wal.exclusiveMode.
50759*/
50760#define WAL_NORMAL_MODE     0
50761#define WAL_EXCLUSIVE_MODE  1
50762#define WAL_HEAPMEMORY_MODE 2
50763
50764/*
50765** Possible values for WAL.readOnly
50766*/
50767#define WAL_RDWR        0    /* Normal read/write connection */
50768#define WAL_RDONLY      1    /* The WAL file is readonly */
50769#define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
50770
50771/*
50772** Each page of the wal-index mapping contains a hash-table made up of
50773** an array of HASHTABLE_NSLOT elements of the following type.
50774*/
50775typedef u16 ht_slot;
50776
50777/*
50778** This structure is used to implement an iterator that loops through
50779** all frames in the WAL in database page order. Where two or more frames
50780** correspond to the same database page, the iterator visits only the
50781** frame most recently written to the WAL (in other words, the frame with
50782** the largest index).
50783**
50784** The internals of this structure are only accessed by:
50785**
50786**   walIteratorInit() - Create a new iterator,
50787**   walIteratorNext() - Step an iterator,
50788**   walIteratorFree() - Free an iterator.
50789**
50790** This functionality is used by the checkpoint code (see walCheckpoint()).
50791*/
50792struct WalIterator {
50793  int iPrior;                     /* Last result returned from the iterator */
50794  int nSegment;                   /* Number of entries in aSegment[] */
50795  struct WalSegment {
50796    int iNext;                    /* Next slot in aIndex[] not yet returned */
50797    ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
50798    u32 *aPgno;                   /* Array of page numbers. */
50799    int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
50800    int iZero;                    /* Frame number associated with aPgno[0] */
50801  } aSegment[1];                  /* One for every 32KB page in the wal-index */
50802};
50803
50804/*
50805** Define the parameters of the hash tables in the wal-index file. There
50806** is a hash-table following every HASHTABLE_NPAGE page numbers in the
50807** wal-index.
50808**
50809** Changing any of these constants will alter the wal-index format and
50810** create incompatibilities.
50811*/
50812#define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
50813#define HASHTABLE_HASH_1     383                  /* Should be prime */
50814#define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
50815
50816/*
50817** The block of page numbers associated with the first hash-table in a
50818** wal-index is smaller than usual. This is so that there is a complete
50819** hash-table on each aligned 32KB page of the wal-index.
50820*/
50821#define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
50822
50823/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
50824#define WALINDEX_PGSZ   (                                         \
50825    sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
50826)
50827
50828/*
50829** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
50830** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
50831** numbered from zero.
50832**
50833** If this call is successful, *ppPage is set to point to the wal-index
50834** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
50835** then an SQLite error code is returned and *ppPage is set to 0.
50836*/
50837static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
50838  int rc = SQLITE_OK;
50839
50840  /* Enlarge the pWal->apWiData[] array if required */
50841  if( pWal->nWiData<=iPage ){
50842    int nByte = sizeof(u32*)*(iPage+1);
50843    volatile u32 **apNew;
50844    apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
50845    if( !apNew ){
50846      *ppPage = 0;
50847      return SQLITE_NOMEM;
50848    }
50849    memset((void*)&apNew[pWal->nWiData], 0,
50850           sizeof(u32*)*(iPage+1-pWal->nWiData));
50851    pWal->apWiData = apNew;
50852    pWal->nWiData = iPage+1;
50853  }
50854
50855  /* Request a pointer to the required page from the VFS */
50856  if( pWal->apWiData[iPage]==0 ){
50857    if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
50858      pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
50859      if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
50860    }else{
50861      rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
50862          pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
50863      );
50864      if( rc==SQLITE_READONLY ){
50865        pWal->readOnly |= WAL_SHM_RDONLY;
50866        rc = SQLITE_OK;
50867      }
50868    }
50869  }
50870
50871  *ppPage = pWal->apWiData[iPage];
50872  assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
50873  return rc;
50874}
50875
50876/*
50877** Return a pointer to the WalCkptInfo structure in the wal-index.
50878*/
50879static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
50880  assert( pWal->nWiData>0 && pWal->apWiData[0] );
50881  return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
50882}
50883
50884/*
50885** Return a pointer to the WalIndexHdr structure in the wal-index.
50886*/
50887static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
50888  assert( pWal->nWiData>0 && pWal->apWiData[0] );
50889  return (volatile WalIndexHdr*)pWal->apWiData[0];
50890}
50891
50892/*
50893** The argument to this macro must be of type u32. On a little-endian
50894** architecture, it returns the u32 value that results from interpreting
50895** the 4 bytes as a big-endian value. On a big-endian architecture, it
50896** returns the value that would be produced by interpreting the 4 bytes
50897** of the input value as a little-endian integer.
50898*/
50899#define BYTESWAP32(x) ( \
50900    (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
50901  + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
50902)
50903
50904/*
50905** Generate or extend an 8 byte checksum based on the data in
50906** array aByte[] and the initial values of aIn[0] and aIn[1] (or
50907** initial values of 0 and 0 if aIn==NULL).
50908**
50909** The checksum is written back into aOut[] before returning.
50910**
50911** nByte must be a positive multiple of 8.
50912*/
50913static void walChecksumBytes(
50914  int nativeCksum, /* True for native byte-order, false for non-native */
50915  u8 *a,           /* Content to be checksummed */
50916  int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
50917  const u32 *aIn,  /* Initial checksum value input */
50918  u32 *aOut        /* OUT: Final checksum value output */
50919){
50920  u32 s1, s2;
50921  u32 *aData = (u32 *)a;
50922  u32 *aEnd = (u32 *)&a[nByte];
50923
50924  if( aIn ){
50925    s1 = aIn[0];
50926    s2 = aIn[1];
50927  }else{
50928    s1 = s2 = 0;
50929  }
50930
50931  assert( nByte>=8 );
50932  assert( (nByte&0x00000007)==0 );
50933
50934  if( nativeCksum ){
50935    do {
50936      s1 += *aData++ + s2;
50937      s2 += *aData++ + s1;
50938    }while( aData<aEnd );
50939  }else{
50940    do {
50941      s1 += BYTESWAP32(aData[0]) + s2;
50942      s2 += BYTESWAP32(aData[1]) + s1;
50943      aData += 2;
50944    }while( aData<aEnd );
50945  }
50946
50947  aOut[0] = s1;
50948  aOut[1] = s2;
50949}
50950
50951static void walShmBarrier(Wal *pWal){
50952  if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
50953    sqlite3OsShmBarrier(pWal->pDbFd);
50954  }
50955}
50956
50957/*
50958** Write the header information in pWal->hdr into the wal-index.
50959**
50960** The checksum on pWal->hdr is updated before it is written.
50961*/
50962static void walIndexWriteHdr(Wal *pWal){
50963  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
50964  const int nCksum = offsetof(WalIndexHdr, aCksum);
50965
50966  assert( pWal->writeLock );
50967  pWal->hdr.isInit = 1;
50968  pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
50969  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
50970  memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
50971  walShmBarrier(pWal);
50972  memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
50973}
50974
50975/*
50976** This function encodes a single frame header and writes it to a buffer
50977** supplied by the caller. A frame-header is made up of a series of
50978** 4-byte big-endian integers, as follows:
50979**
50980**     0: Page number.
50981**     4: For commit records, the size of the database image in pages
50982**        after the commit. For all other records, zero.
50983**     8: Salt-1 (copied from the wal-header)
50984**    12: Salt-2 (copied from the wal-header)
50985**    16: Checksum-1.
50986**    20: Checksum-2.
50987*/
50988static void walEncodeFrame(
50989  Wal *pWal,                      /* The write-ahead log */
50990  u32 iPage,                      /* Database page number for frame */
50991  u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
50992  u8 *aData,                      /* Pointer to page data */
50993  u8 *aFrame                      /* OUT: Write encoded frame here */
50994){
50995  int nativeCksum;                /* True for native byte-order checksums */
50996  u32 *aCksum = pWal->hdr.aFrameCksum;
50997  assert( WAL_FRAME_HDRSIZE==24 );
50998  sqlite3Put4byte(&aFrame[0], iPage);
50999  sqlite3Put4byte(&aFrame[4], nTruncate);
51000  memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
51001
51002  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
51003  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
51004  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
51005
51006  sqlite3Put4byte(&aFrame[16], aCksum[0]);
51007  sqlite3Put4byte(&aFrame[20], aCksum[1]);
51008}
51009
51010/*
51011** Check to see if the frame with header in aFrame[] and content
51012** in aData[] is valid.  If it is a valid frame, fill *piPage and
51013** *pnTruncate and return true.  Return if the frame is not valid.
51014*/
51015static int walDecodeFrame(
51016  Wal *pWal,                      /* The write-ahead log */
51017  u32 *piPage,                    /* OUT: Database page number for frame */
51018  u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
51019  u8 *aData,                      /* Pointer to page data (for checksum) */
51020  u8 *aFrame                      /* Frame data */
51021){
51022  int nativeCksum;                /* True for native byte-order checksums */
51023  u32 *aCksum = pWal->hdr.aFrameCksum;
51024  u32 pgno;                       /* Page number of the frame */
51025  assert( WAL_FRAME_HDRSIZE==24 );
51026
51027  /* A frame is only valid if the salt values in the frame-header
51028  ** match the salt values in the wal-header.
51029  */
51030  if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
51031    return 0;
51032  }
51033
51034  /* A frame is only valid if the page number is creater than zero.
51035  */
51036  pgno = sqlite3Get4byte(&aFrame[0]);
51037  if( pgno==0 ){
51038    return 0;
51039  }
51040
51041  /* A frame is only valid if a checksum of the WAL header,
51042  ** all prior frams, the first 16 bytes of this frame-header,
51043  ** and the frame-data matches the checksum in the last 8
51044  ** bytes of this frame-header.
51045  */
51046  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
51047  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
51048  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
51049  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
51050   || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
51051  ){
51052    /* Checksum failed. */
51053    return 0;
51054  }
51055
51056  /* If we reach this point, the frame is valid.  Return the page number
51057  ** and the new database size.
51058  */
51059  *piPage = pgno;
51060  *pnTruncate = sqlite3Get4byte(&aFrame[4]);
51061  return 1;
51062}
51063
51064
51065#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
51066/*
51067** Names of locks.  This routine is used to provide debugging output and is not
51068** a part of an ordinary build.
51069*/
51070static const char *walLockName(int lockIdx){
51071  if( lockIdx==WAL_WRITE_LOCK ){
51072    return "WRITE-LOCK";
51073  }else if( lockIdx==WAL_CKPT_LOCK ){
51074    return "CKPT-LOCK";
51075  }else if( lockIdx==WAL_RECOVER_LOCK ){
51076    return "RECOVER-LOCK";
51077  }else{
51078    static char zName[15];
51079    sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
51080                     lockIdx-WAL_READ_LOCK(0));
51081    return zName;
51082  }
51083}
51084#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
51085
51086
51087/*
51088** Set or release locks on the WAL.  Locks are either shared or exclusive.
51089** A lock cannot be moved directly between shared and exclusive - it must go
51090** through the unlocked state first.
51091**
51092** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
51093*/
51094static int walLockShared(Wal *pWal, int lockIdx){
51095  int rc;
51096  if( pWal->exclusiveMode ) return SQLITE_OK;
51097  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
51098                        SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
51099  WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
51100            walLockName(lockIdx), rc ? "failed" : "ok"));
51101  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
51102  return rc;
51103}
51104static void walUnlockShared(Wal *pWal, int lockIdx){
51105  if( pWal->exclusiveMode ) return;
51106  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
51107                         SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
51108  WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
51109}
51110static int walLockExclusive(Wal *pWal, int lockIdx, int n, int fBlock){
51111  int rc;
51112  if( pWal->exclusiveMode ) return SQLITE_OK;
51113  if( fBlock ) sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_WAL_BLOCK, 0);
51114  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
51115                        SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
51116  WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
51117            walLockName(lockIdx), n, rc ? "failed" : "ok"));
51118  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
51119  return rc;
51120}
51121static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
51122  if( pWal->exclusiveMode ) return;
51123  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
51124                         SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
51125  WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
51126             walLockName(lockIdx), n));
51127}
51128
51129/*
51130** Compute a hash on a page number.  The resulting hash value must land
51131** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
51132** the hash to the next value in the event of a collision.
51133*/
51134static int walHash(u32 iPage){
51135  assert( iPage>0 );
51136  assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
51137  return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
51138}
51139static int walNextHash(int iPriorHash){
51140  return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
51141}
51142
51143/*
51144** Return pointers to the hash table and page number array stored on
51145** page iHash of the wal-index. The wal-index is broken into 32KB pages
51146** numbered starting from 0.
51147**
51148** Set output variable *paHash to point to the start of the hash table
51149** in the wal-index file. Set *piZero to one less than the frame
51150** number of the first frame indexed by this hash table. If a
51151** slot in the hash table is set to N, it refers to frame number
51152** (*piZero+N) in the log.
51153**
51154** Finally, set *paPgno so that *paPgno[1] is the page number of the
51155** first frame indexed by the hash table, frame (*piZero+1).
51156*/
51157static int walHashGet(
51158  Wal *pWal,                      /* WAL handle */
51159  int iHash,                      /* Find the iHash'th table */
51160  volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
51161  volatile u32 **paPgno,          /* OUT: Pointer to page number array */
51162  u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
51163){
51164  int rc;                         /* Return code */
51165  volatile u32 *aPgno;
51166
51167  rc = walIndexPage(pWal, iHash, &aPgno);
51168  assert( rc==SQLITE_OK || iHash>0 );
51169
51170  if( rc==SQLITE_OK ){
51171    u32 iZero;
51172    volatile ht_slot *aHash;
51173
51174    aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
51175    if( iHash==0 ){
51176      aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
51177      iZero = 0;
51178    }else{
51179      iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
51180    }
51181
51182    *paPgno = &aPgno[-1];
51183    *paHash = aHash;
51184    *piZero = iZero;
51185  }
51186  return rc;
51187}
51188
51189/*
51190** Return the number of the wal-index page that contains the hash-table
51191** and page-number array that contain entries corresponding to WAL frame
51192** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
51193** are numbered starting from 0.
51194*/
51195static int walFramePage(u32 iFrame){
51196  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
51197  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
51198       && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
51199       && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
51200       && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
51201       && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
51202  );
51203  return iHash;
51204}
51205
51206/*
51207** Return the page number associated with frame iFrame in this WAL.
51208*/
51209static u32 walFramePgno(Wal *pWal, u32 iFrame){
51210  int iHash = walFramePage(iFrame);
51211  if( iHash==0 ){
51212    return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
51213  }
51214  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
51215}
51216
51217/*
51218** Remove entries from the hash table that point to WAL slots greater
51219** than pWal->hdr.mxFrame.
51220**
51221** This function is called whenever pWal->hdr.mxFrame is decreased due
51222** to a rollback or savepoint.
51223**
51224** At most only the hash table containing pWal->hdr.mxFrame needs to be
51225** updated.  Any later hash tables will be automatically cleared when
51226** pWal->hdr.mxFrame advances to the point where those hash tables are
51227** actually needed.
51228*/
51229static void walCleanupHash(Wal *pWal){
51230  volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
51231  volatile u32 *aPgno = 0;        /* Page number array for hash table */
51232  u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
51233  int iLimit = 0;                 /* Zero values greater than this */
51234  int nByte;                      /* Number of bytes to zero in aPgno[] */
51235  int i;                          /* Used to iterate through aHash[] */
51236
51237  assert( pWal->writeLock );
51238  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
51239  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
51240  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
51241
51242  if( pWal->hdr.mxFrame==0 ) return;
51243
51244  /* Obtain pointers to the hash-table and page-number array containing
51245  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
51246  ** that the page said hash-table and array reside on is already mapped.
51247  */
51248  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
51249  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
51250  walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
51251
51252  /* Zero all hash-table entries that correspond to frame numbers greater
51253  ** than pWal->hdr.mxFrame.
51254  */
51255  iLimit = pWal->hdr.mxFrame - iZero;
51256  assert( iLimit>0 );
51257  for(i=0; i<HASHTABLE_NSLOT; i++){
51258    if( aHash[i]>iLimit ){
51259      aHash[i] = 0;
51260    }
51261  }
51262
51263  /* Zero the entries in the aPgno array that correspond to frames with
51264  ** frame numbers greater than pWal->hdr.mxFrame.
51265  */
51266  nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
51267  memset((void *)&aPgno[iLimit+1], 0, nByte);
51268
51269#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
51270  /* Verify that the every entry in the mapping region is still reachable
51271  ** via the hash table even after the cleanup.
51272  */
51273  if( iLimit ){
51274    int j;           /* Loop counter */
51275    int iKey;        /* Hash key */
51276    for(j=1; j<=iLimit; j++){
51277      for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
51278        if( aHash[iKey]==j ) break;
51279      }
51280      assert( aHash[iKey]==j );
51281    }
51282  }
51283#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
51284}
51285
51286
51287/*
51288** Set an entry in the wal-index that will map database page number
51289** pPage into WAL frame iFrame.
51290*/
51291static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
51292  int rc;                         /* Return code */
51293  u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
51294  volatile u32 *aPgno = 0;        /* Page number array */
51295  volatile ht_slot *aHash = 0;    /* Hash table */
51296
51297  rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
51298
51299  /* Assuming the wal-index file was successfully mapped, populate the
51300  ** page number array and hash table entry.
51301  */
51302  if( rc==SQLITE_OK ){
51303    int iKey;                     /* Hash table key */
51304    int idx;                      /* Value to write to hash-table slot */
51305    int nCollide;                 /* Number of hash collisions */
51306
51307    idx = iFrame - iZero;
51308    assert( idx <= HASHTABLE_NSLOT/2 + 1 );
51309
51310    /* If this is the first entry to be added to this hash-table, zero the
51311    ** entire hash table and aPgno[] array before proceeding.
51312    */
51313    if( idx==1 ){
51314      int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
51315      memset((void*)&aPgno[1], 0, nByte);
51316    }
51317
51318    /* If the entry in aPgno[] is already set, then the previous writer
51319    ** must have exited unexpectedly in the middle of a transaction (after
51320    ** writing one or more dirty pages to the WAL to free up memory).
51321    ** Remove the remnants of that writers uncommitted transaction from
51322    ** the hash-table before writing any new entries.
51323    */
51324    if( aPgno[idx] ){
51325      walCleanupHash(pWal);
51326      assert( !aPgno[idx] );
51327    }
51328
51329    /* Write the aPgno[] array entry and the hash-table slot. */
51330    nCollide = idx;
51331    for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
51332      if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
51333    }
51334    aPgno[idx] = iPage;
51335    aHash[iKey] = (ht_slot)idx;
51336
51337#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
51338    /* Verify that the number of entries in the hash table exactly equals
51339    ** the number of entries in the mapping region.
51340    */
51341    {
51342      int i;           /* Loop counter */
51343      int nEntry = 0;  /* Number of entries in the hash table */
51344      for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
51345      assert( nEntry==idx );
51346    }
51347
51348    /* Verify that the every entry in the mapping region is reachable
51349    ** via the hash table.  This turns out to be a really, really expensive
51350    ** thing to check, so only do this occasionally - not on every
51351    ** iteration.
51352    */
51353    if( (idx&0x3ff)==0 ){
51354      int i;           /* Loop counter */
51355      for(i=1; i<=idx; i++){
51356        for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
51357          if( aHash[iKey]==i ) break;
51358        }
51359        assert( aHash[iKey]==i );
51360      }
51361    }
51362#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
51363  }
51364
51365
51366  return rc;
51367}
51368
51369
51370/*
51371** Recover the wal-index by reading the write-ahead log file.
51372**
51373** This routine first tries to establish an exclusive lock on the
51374** wal-index to prevent other threads/processes from doing anything
51375** with the WAL or wal-index while recovery is running.  The
51376** WAL_RECOVER_LOCK is also held so that other threads will know
51377** that this thread is running recovery.  If unable to establish
51378** the necessary locks, this routine returns SQLITE_BUSY.
51379*/
51380static int walIndexRecover(Wal *pWal){
51381  int rc;                         /* Return Code */
51382  i64 nSize;                      /* Size of log file */
51383  u32 aFrameCksum[2] = {0, 0};
51384  int iLock;                      /* Lock offset to lock for checkpoint */
51385  int nLock;                      /* Number of locks to hold */
51386
51387  /* Obtain an exclusive lock on all byte in the locking range not already
51388  ** locked by the caller. The caller is guaranteed to have locked the
51389  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
51390  ** If successful, the same bytes that are locked here are unlocked before
51391  ** this function returns.
51392  */
51393  assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
51394  assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
51395  assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
51396  assert( pWal->writeLock );
51397  iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
51398  nLock = SQLITE_SHM_NLOCK - iLock;
51399  rc = walLockExclusive(pWal, iLock, nLock, 0);
51400  if( rc ){
51401    return rc;
51402  }
51403  WALTRACE(("WAL%p: recovery begin...\n", pWal));
51404
51405  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
51406
51407  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
51408  if( rc!=SQLITE_OK ){
51409    goto recovery_error;
51410  }
51411
51412  if( nSize>WAL_HDRSIZE ){
51413    u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
51414    u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
51415    int szFrame;                  /* Number of bytes in buffer aFrame[] */
51416    u8 *aData;                    /* Pointer to data part of aFrame buffer */
51417    int iFrame;                   /* Index of last frame read */
51418    i64 iOffset;                  /* Next offset to read from log file */
51419    int szPage;                   /* Page size according to the log */
51420    u32 magic;                    /* Magic value read from WAL header */
51421    u32 version;                  /* Magic value read from WAL header */
51422    int isValid;                  /* True if this frame is valid */
51423
51424    /* Read in the WAL header. */
51425    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
51426    if( rc!=SQLITE_OK ){
51427      goto recovery_error;
51428    }
51429
51430    /* If the database page size is not a power of two, or is greater than
51431    ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
51432    ** data. Similarly, if the 'magic' value is invalid, ignore the whole
51433    ** WAL file.
51434    */
51435    magic = sqlite3Get4byte(&aBuf[0]);
51436    szPage = sqlite3Get4byte(&aBuf[8]);
51437    if( (magic&0xFFFFFFFE)!=WAL_MAGIC
51438     || szPage&(szPage-1)
51439     || szPage>SQLITE_MAX_PAGE_SIZE
51440     || szPage<512
51441    ){
51442      goto finished;
51443    }
51444    pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
51445    pWal->szPage = szPage;
51446    pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
51447    memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
51448
51449    /* Verify that the WAL header checksum is correct */
51450    walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
51451        aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
51452    );
51453    if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
51454     || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
51455    ){
51456      goto finished;
51457    }
51458
51459    /* Verify that the version number on the WAL format is one that
51460    ** are able to understand */
51461    version = sqlite3Get4byte(&aBuf[4]);
51462    if( version!=WAL_MAX_VERSION ){
51463      rc = SQLITE_CANTOPEN_BKPT;
51464      goto finished;
51465    }
51466
51467    /* Malloc a buffer to read frames into. */
51468    szFrame = szPage + WAL_FRAME_HDRSIZE;
51469    aFrame = (u8 *)sqlite3_malloc64(szFrame);
51470    if( !aFrame ){
51471      rc = SQLITE_NOMEM;
51472      goto recovery_error;
51473    }
51474    aData = &aFrame[WAL_FRAME_HDRSIZE];
51475
51476    /* Read all frames from the log file. */
51477    iFrame = 0;
51478    for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
51479      u32 pgno;                   /* Database page number for frame */
51480      u32 nTruncate;              /* dbsize field from frame header */
51481
51482      /* Read and decode the next log frame. */
51483      iFrame++;
51484      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
51485      if( rc!=SQLITE_OK ) break;
51486      isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
51487      if( !isValid ) break;
51488      rc = walIndexAppend(pWal, iFrame, pgno);
51489      if( rc!=SQLITE_OK ) break;
51490
51491      /* If nTruncate is non-zero, this is a commit record. */
51492      if( nTruncate ){
51493        pWal->hdr.mxFrame = iFrame;
51494        pWal->hdr.nPage = nTruncate;
51495        pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
51496        testcase( szPage<=32768 );
51497        testcase( szPage>=65536 );
51498        aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
51499        aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
51500      }
51501    }
51502
51503    sqlite3_free(aFrame);
51504  }
51505
51506finished:
51507  if( rc==SQLITE_OK ){
51508    volatile WalCkptInfo *pInfo;
51509    int i;
51510    pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
51511    pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
51512    walIndexWriteHdr(pWal);
51513
51514    /* Reset the checkpoint-header. This is safe because this thread is
51515    ** currently holding locks that exclude all other readers, writers and
51516    ** checkpointers.
51517    */
51518    pInfo = walCkptInfo(pWal);
51519    pInfo->nBackfill = 0;
51520    pInfo->aReadMark[0] = 0;
51521    for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
51522    if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
51523
51524    /* If more than one frame was recovered from the log file, report an
51525    ** event via sqlite3_log(). This is to help with identifying performance
51526    ** problems caused by applications routinely shutting down without
51527    ** checkpointing the log file.
51528    */
51529    if( pWal->hdr.nPage ){
51530      sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
51531          "recovered %d frames from WAL file %s",
51532          pWal->hdr.mxFrame, pWal->zWalName
51533      );
51534    }
51535  }
51536
51537recovery_error:
51538  WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
51539  walUnlockExclusive(pWal, iLock, nLock);
51540  return rc;
51541}
51542
51543/*
51544** Close an open wal-index.
51545*/
51546static void walIndexClose(Wal *pWal, int isDelete){
51547  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
51548    int i;
51549    for(i=0; i<pWal->nWiData; i++){
51550      sqlite3_free((void *)pWal->apWiData[i]);
51551      pWal->apWiData[i] = 0;
51552    }
51553  }else{
51554    sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
51555  }
51556}
51557
51558/*
51559** Open a connection to the WAL file zWalName. The database file must
51560** already be opened on connection pDbFd. The buffer that zWalName points
51561** to must remain valid for the lifetime of the returned Wal* handle.
51562**
51563** A SHARED lock should be held on the database file when this function
51564** is called. The purpose of this SHARED lock is to prevent any other
51565** client from unlinking the WAL or wal-index file. If another process
51566** were to do this just after this client opened one of these files, the
51567** system would be badly broken.
51568**
51569** If the log file is successfully opened, SQLITE_OK is returned and
51570** *ppWal is set to point to a new WAL handle. If an error occurs,
51571** an SQLite error code is returned and *ppWal is left unmodified.
51572*/
51573SQLITE_PRIVATE int sqlite3WalOpen(
51574  sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
51575  sqlite3_file *pDbFd,            /* The open database file */
51576  const char *zWalName,           /* Name of the WAL file */
51577  int bNoShm,                     /* True to run in heap-memory mode */
51578  i64 mxWalSize,                  /* Truncate WAL to this size on reset */
51579  Wal **ppWal                     /* OUT: Allocated Wal handle */
51580){
51581  int rc;                         /* Return Code */
51582  Wal *pRet;                      /* Object to allocate and return */
51583  int flags;                      /* Flags passed to OsOpen() */
51584
51585  assert( zWalName && zWalName[0] );
51586  assert( pDbFd );
51587
51588  /* In the amalgamation, the os_unix.c and os_win.c source files come before
51589  ** this source file.  Verify that the #defines of the locking byte offsets
51590  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
51591  */
51592#ifdef WIN_SHM_BASE
51593  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
51594#endif
51595#ifdef UNIX_SHM_BASE
51596  assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
51597#endif
51598
51599
51600  /* Allocate an instance of struct Wal to return. */
51601  *ppWal = 0;
51602  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
51603  if( !pRet ){
51604    return SQLITE_NOMEM;
51605  }
51606
51607  pRet->pVfs = pVfs;
51608  pRet->pWalFd = (sqlite3_file *)&pRet[1];
51609  pRet->pDbFd = pDbFd;
51610  pRet->readLock = -1;
51611  pRet->mxWalSize = mxWalSize;
51612  pRet->zWalName = zWalName;
51613  pRet->syncHeader = 1;
51614  pRet->padToSectorBoundary = 1;
51615  pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
51616
51617  /* Open file handle on the write-ahead log file. */
51618  flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
51619  rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
51620  if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
51621    pRet->readOnly = WAL_RDONLY;
51622  }
51623
51624  if( rc!=SQLITE_OK ){
51625    walIndexClose(pRet, 0);
51626    sqlite3OsClose(pRet->pWalFd);
51627    sqlite3_free(pRet);
51628  }else{
51629    int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
51630    if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
51631    if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
51632      pRet->padToSectorBoundary = 0;
51633    }
51634    *ppWal = pRet;
51635    WALTRACE(("WAL%d: opened\n", pRet));
51636  }
51637  return rc;
51638}
51639
51640/*
51641** Change the size to which the WAL file is trucated on each reset.
51642*/
51643SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
51644  if( pWal ) pWal->mxWalSize = iLimit;
51645}
51646
51647/*
51648** Find the smallest page number out of all pages held in the WAL that
51649** has not been returned by any prior invocation of this method on the
51650** same WalIterator object.   Write into *piFrame the frame index where
51651** that page was last written into the WAL.  Write into *piPage the page
51652** number.
51653**
51654** Return 0 on success.  If there are no pages in the WAL with a page
51655** number larger than *piPage, then return 1.
51656*/
51657static int walIteratorNext(
51658  WalIterator *p,               /* Iterator */
51659  u32 *piPage,                  /* OUT: The page number of the next page */
51660  u32 *piFrame                  /* OUT: Wal frame index of next page */
51661){
51662  u32 iMin;                     /* Result pgno must be greater than iMin */
51663  u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
51664  int i;                        /* For looping through segments */
51665
51666  iMin = p->iPrior;
51667  assert( iMin<0xffffffff );
51668  for(i=p->nSegment-1; i>=0; i--){
51669    struct WalSegment *pSegment = &p->aSegment[i];
51670    while( pSegment->iNext<pSegment->nEntry ){
51671      u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
51672      if( iPg>iMin ){
51673        if( iPg<iRet ){
51674          iRet = iPg;
51675          *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
51676        }
51677        break;
51678      }
51679      pSegment->iNext++;
51680    }
51681  }
51682
51683  *piPage = p->iPrior = iRet;
51684  return (iRet==0xFFFFFFFF);
51685}
51686
51687/*
51688** This function merges two sorted lists into a single sorted list.
51689**
51690** aLeft[] and aRight[] are arrays of indices.  The sort key is
51691** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
51692** is guaranteed for all J<K:
51693**
51694**        aContent[aLeft[J]] < aContent[aLeft[K]]
51695**        aContent[aRight[J]] < aContent[aRight[K]]
51696**
51697** This routine overwrites aRight[] with a new (probably longer) sequence
51698** of indices such that the aRight[] contains every index that appears in
51699** either aLeft[] or the old aRight[] and such that the second condition
51700** above is still met.
51701**
51702** The aContent[aLeft[X]] values will be unique for all X.  And the
51703** aContent[aRight[X]] values will be unique too.  But there might be
51704** one or more combinations of X and Y such that
51705**
51706**      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
51707**
51708** When that happens, omit the aLeft[X] and use the aRight[Y] index.
51709*/
51710static void walMerge(
51711  const u32 *aContent,            /* Pages in wal - keys for the sort */
51712  ht_slot *aLeft,                 /* IN: Left hand input list */
51713  int nLeft,                      /* IN: Elements in array *paLeft */
51714  ht_slot **paRight,              /* IN/OUT: Right hand input list */
51715  int *pnRight,                   /* IN/OUT: Elements in *paRight */
51716  ht_slot *aTmp                   /* Temporary buffer */
51717){
51718  int iLeft = 0;                  /* Current index in aLeft */
51719  int iRight = 0;                 /* Current index in aRight */
51720  int iOut = 0;                   /* Current index in output buffer */
51721  int nRight = *pnRight;
51722  ht_slot *aRight = *paRight;
51723
51724  assert( nLeft>0 && nRight>0 );
51725  while( iRight<nRight || iLeft<nLeft ){
51726    ht_slot logpage;
51727    Pgno dbpage;
51728
51729    if( (iLeft<nLeft)
51730     && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
51731    ){
51732      logpage = aLeft[iLeft++];
51733    }else{
51734      logpage = aRight[iRight++];
51735    }
51736    dbpage = aContent[logpage];
51737
51738    aTmp[iOut++] = logpage;
51739    if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
51740
51741    assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
51742    assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
51743  }
51744
51745  *paRight = aLeft;
51746  *pnRight = iOut;
51747  memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
51748}
51749
51750/*
51751** Sort the elements in list aList using aContent[] as the sort key.
51752** Remove elements with duplicate keys, preferring to keep the
51753** larger aList[] values.
51754**
51755** The aList[] entries are indices into aContent[].  The values in
51756** aList[] are to be sorted so that for all J<K:
51757**
51758**      aContent[aList[J]] < aContent[aList[K]]
51759**
51760** For any X and Y such that
51761**
51762**      aContent[aList[X]] == aContent[aList[Y]]
51763**
51764** Keep the larger of the two values aList[X] and aList[Y] and discard
51765** the smaller.
51766*/
51767static void walMergesort(
51768  const u32 *aContent,            /* Pages in wal */
51769  ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
51770  ht_slot *aList,                 /* IN/OUT: List to sort */
51771  int *pnList                     /* IN/OUT: Number of elements in aList[] */
51772){
51773  struct Sublist {
51774    int nList;                    /* Number of elements in aList */
51775    ht_slot *aList;               /* Pointer to sub-list content */
51776  };
51777
51778  const int nList = *pnList;      /* Size of input list */
51779  int nMerge = 0;                 /* Number of elements in list aMerge */
51780  ht_slot *aMerge = 0;            /* List to be merged */
51781  int iList;                      /* Index into input list */
51782  u32 iSub = 0;                   /* Index into aSub array */
51783  struct Sublist aSub[13];        /* Array of sub-lists */
51784
51785  memset(aSub, 0, sizeof(aSub));
51786  assert( nList<=HASHTABLE_NPAGE && nList>0 );
51787  assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
51788
51789  for(iList=0; iList<nList; iList++){
51790    nMerge = 1;
51791    aMerge = &aList[iList];
51792    for(iSub=0; iList & (1<<iSub); iSub++){
51793      struct Sublist *p;
51794      assert( iSub<ArraySize(aSub) );
51795      p = &aSub[iSub];
51796      assert( p->aList && p->nList<=(1<<iSub) );
51797      assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
51798      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
51799    }
51800    aSub[iSub].aList = aMerge;
51801    aSub[iSub].nList = nMerge;
51802  }
51803
51804  for(iSub++; iSub<ArraySize(aSub); iSub++){
51805    if( nList & (1<<iSub) ){
51806      struct Sublist *p;
51807      assert( iSub<ArraySize(aSub) );
51808      p = &aSub[iSub];
51809      assert( p->nList<=(1<<iSub) );
51810      assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
51811      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
51812    }
51813  }
51814  assert( aMerge==aList );
51815  *pnList = nMerge;
51816
51817#ifdef SQLITE_DEBUG
51818  {
51819    int i;
51820    for(i=1; i<*pnList; i++){
51821      assert( aContent[aList[i]] > aContent[aList[i-1]] );
51822    }
51823  }
51824#endif
51825}
51826
51827/*
51828** Free an iterator allocated by walIteratorInit().
51829*/
51830static void walIteratorFree(WalIterator *p){
51831  sqlite3_free(p);
51832}
51833
51834/*
51835** Construct a WalInterator object that can be used to loop over all
51836** pages in the WAL in ascending order. The caller must hold the checkpoint
51837** lock.
51838**
51839** On success, make *pp point to the newly allocated WalInterator object
51840** return SQLITE_OK. Otherwise, return an error code. If this routine
51841** returns an error, the value of *pp is undefined.
51842**
51843** The calling routine should invoke walIteratorFree() to destroy the
51844** WalIterator object when it has finished with it.
51845*/
51846static int walIteratorInit(Wal *pWal, WalIterator **pp){
51847  WalIterator *p;                 /* Return value */
51848  int nSegment;                   /* Number of segments to merge */
51849  u32 iLast;                      /* Last frame in log */
51850  int nByte;                      /* Number of bytes to allocate */
51851  int i;                          /* Iterator variable */
51852  ht_slot *aTmp;                  /* Temp space used by merge-sort */
51853  int rc = SQLITE_OK;             /* Return Code */
51854
51855  /* This routine only runs while holding the checkpoint lock. And
51856  ** it only runs if there is actually content in the log (mxFrame>0).
51857  */
51858  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
51859  iLast = pWal->hdr.mxFrame;
51860
51861  /* Allocate space for the WalIterator object. */
51862  nSegment = walFramePage(iLast) + 1;
51863  nByte = sizeof(WalIterator)
51864        + (nSegment-1)*sizeof(struct WalSegment)
51865        + iLast*sizeof(ht_slot);
51866  p = (WalIterator *)sqlite3_malloc64(nByte);
51867  if( !p ){
51868    return SQLITE_NOMEM;
51869  }
51870  memset(p, 0, nByte);
51871  p->nSegment = nSegment;
51872
51873  /* Allocate temporary space used by the merge-sort routine. This block
51874  ** of memory will be freed before this function returns.
51875  */
51876  aTmp = (ht_slot *)sqlite3_malloc64(
51877      sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
51878  );
51879  if( !aTmp ){
51880    rc = SQLITE_NOMEM;
51881  }
51882
51883  for(i=0; rc==SQLITE_OK && i<nSegment; i++){
51884    volatile ht_slot *aHash;
51885    u32 iZero;
51886    volatile u32 *aPgno;
51887
51888    rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
51889    if( rc==SQLITE_OK ){
51890      int j;                      /* Counter variable */
51891      int nEntry;                 /* Number of entries in this segment */
51892      ht_slot *aIndex;            /* Sorted index for this segment */
51893
51894      aPgno++;
51895      if( (i+1)==nSegment ){
51896        nEntry = (int)(iLast - iZero);
51897      }else{
51898        nEntry = (int)((u32*)aHash - (u32*)aPgno);
51899      }
51900      aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
51901      iZero++;
51902
51903      for(j=0; j<nEntry; j++){
51904        aIndex[j] = (ht_slot)j;
51905      }
51906      walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
51907      p->aSegment[i].iZero = iZero;
51908      p->aSegment[i].nEntry = nEntry;
51909      p->aSegment[i].aIndex = aIndex;
51910      p->aSegment[i].aPgno = (u32 *)aPgno;
51911    }
51912  }
51913  sqlite3_free(aTmp);
51914
51915  if( rc!=SQLITE_OK ){
51916    walIteratorFree(p);
51917  }
51918  *pp = p;
51919  return rc;
51920}
51921
51922/*
51923** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
51924** n. If the attempt fails and parameter xBusy is not NULL, then it is a
51925** busy-handler function. Invoke it and retry the lock until either the
51926** lock is successfully obtained or the busy-handler returns 0.
51927*/
51928static int walBusyLock(
51929  Wal *pWal,                      /* WAL connection */
51930  int (*xBusy)(void*),            /* Function to call when busy */
51931  void *pBusyArg,                 /* Context argument for xBusyHandler */
51932  int lockIdx,                    /* Offset of first byte to lock */
51933  int n                           /* Number of bytes to lock */
51934){
51935  int rc;
51936  do {
51937    rc = walLockExclusive(pWal, lockIdx, n, 0);
51938  }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
51939  return rc;
51940}
51941
51942/*
51943** The cache of the wal-index header must be valid to call this function.
51944** Return the page-size in bytes used by the database.
51945*/
51946static int walPagesize(Wal *pWal){
51947  return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
51948}
51949
51950/*
51951** The following is guaranteed when this function is called:
51952**
51953**   a) the WRITER lock is held,
51954**   b) the entire log file has been checkpointed, and
51955**   c) any existing readers are reading exclusively from the database
51956**      file - there are no readers that may attempt to read a frame from
51957**      the log file.
51958**
51959** This function updates the shared-memory structures so that the next
51960** client to write to the database (which may be this one) does so by
51961** writing frames into the start of the log file.
51962**
51963** The value of parameter salt1 is used as the aSalt[1] value in the
51964** new wal-index header. It should be passed a pseudo-random value (i.e.
51965** one obtained from sqlite3_randomness()).
51966*/
51967static void walRestartHdr(Wal *pWal, u32 salt1){
51968  volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
51969  int i;                          /* Loop counter */
51970  u32 *aSalt = pWal->hdr.aSalt;   /* Big-endian salt values */
51971  pWal->nCkpt++;
51972  pWal->hdr.mxFrame = 0;
51973  sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
51974  memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
51975  walIndexWriteHdr(pWal);
51976  pInfo->nBackfill = 0;
51977  pInfo->aReadMark[1] = 0;
51978  for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
51979  assert( pInfo->aReadMark[0]==0 );
51980}
51981
51982/*
51983** Copy as much content as we can from the WAL back into the database file
51984** in response to an sqlite3_wal_checkpoint() request or the equivalent.
51985**
51986** The amount of information copies from WAL to database might be limited
51987** by active readers.  This routine will never overwrite a database page
51988** that a concurrent reader might be using.
51989**
51990** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
51991** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
51992** checkpoints are always run by a background thread or background
51993** process, foreground threads will never block on a lengthy fsync call.
51994**
51995** Fsync is called on the WAL before writing content out of the WAL and
51996** into the database.  This ensures that if the new content is persistent
51997** in the WAL and can be recovered following a power-loss or hard reset.
51998**
51999** Fsync is also called on the database file if (and only if) the entire
52000** WAL content is copied into the database file.  This second fsync makes
52001** it safe to delete the WAL since the new content will persist in the
52002** database file.
52003**
52004** This routine uses and updates the nBackfill field of the wal-index header.
52005** This is the only routine that will increase the value of nBackfill.
52006** (A WAL reset or recovery will revert nBackfill to zero, but not increase
52007** its value.)
52008**
52009** The caller must be holding sufficient locks to ensure that no other
52010** checkpoint is running (in any other thread or process) at the same
52011** time.
52012*/
52013static int walCheckpoint(
52014  Wal *pWal,                      /* Wal connection */
52015  int eMode,                      /* One of PASSIVE, FULL or RESTART */
52016  int (*xBusy)(void*),            /* Function to call when busy */
52017  void *pBusyArg,                 /* Context argument for xBusyHandler */
52018  int sync_flags,                 /* Flags for OsSync() (or 0) */
52019  u8 *zBuf                        /* Temporary buffer to use */
52020){
52021  int rc = SQLITE_OK;             /* Return code */
52022  int szPage;                     /* Database page-size */
52023  WalIterator *pIter = 0;         /* Wal iterator context */
52024  u32 iDbpage = 0;                /* Next database page to write */
52025  u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
52026  u32 mxSafeFrame;                /* Max frame that can be backfilled */
52027  u32 mxPage;                     /* Max database page to write */
52028  int i;                          /* Loop counter */
52029  volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
52030
52031  szPage = walPagesize(pWal);
52032  testcase( szPage<=32768 );
52033  testcase( szPage>=65536 );
52034  pInfo = walCkptInfo(pWal);
52035  if( pInfo->nBackfill<pWal->hdr.mxFrame ){
52036
52037    /* Allocate the iterator */
52038    rc = walIteratorInit(pWal, &pIter);
52039    if( rc!=SQLITE_OK ){
52040      return rc;
52041    }
52042    assert( pIter );
52043
52044    /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
52045    ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
52046    assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
52047
52048    /* Compute in mxSafeFrame the index of the last frame of the WAL that is
52049    ** safe to write into the database.  Frames beyond mxSafeFrame might
52050    ** overwrite database pages that are in use by active readers and thus
52051    ** cannot be backfilled from the WAL.
52052    */
52053    mxSafeFrame = pWal->hdr.mxFrame;
52054    mxPage = pWal->hdr.nPage;
52055    for(i=1; i<WAL_NREADER; i++){
52056      /* Thread-sanitizer reports that the following is an unsafe read,
52057      ** as some other thread may be in the process of updating the value
52058      ** of the aReadMark[] slot. The assumption here is that if that is
52059      ** happening, the other client may only be increasing the value,
52060      ** not decreasing it. So assuming either that either the "old" or
52061      ** "new" version of the value is read, and not some arbitrary value
52062      ** that would never be written by a real client, things are still
52063      ** safe.  */
52064      u32 y = pInfo->aReadMark[i];
52065      if( mxSafeFrame>y ){
52066        assert( y<=pWal->hdr.mxFrame );
52067        rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
52068        if( rc==SQLITE_OK ){
52069          pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
52070          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
52071        }else if( rc==SQLITE_BUSY ){
52072          mxSafeFrame = y;
52073          xBusy = 0;
52074        }else{
52075          goto walcheckpoint_out;
52076        }
52077      }
52078    }
52079
52080    if( pInfo->nBackfill<mxSafeFrame
52081     && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
52082    ){
52083      i64 nSize;                    /* Current size of database file */
52084      u32 nBackfill = pInfo->nBackfill;
52085
52086      /* Sync the WAL to disk */
52087      if( sync_flags ){
52088        rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
52089      }
52090
52091      /* If the database may grow as a result of this checkpoint, hint
52092      ** about the eventual size of the db file to the VFS layer.
52093      */
52094      if( rc==SQLITE_OK ){
52095        i64 nReq = ((i64)mxPage * szPage);
52096        rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
52097        if( rc==SQLITE_OK && nSize<nReq ){
52098          sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
52099        }
52100      }
52101
52102
52103      /* Iterate through the contents of the WAL, copying data to the db file */
52104      while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
52105        i64 iOffset;
52106        assert( walFramePgno(pWal, iFrame)==iDbpage );
52107        if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
52108          continue;
52109        }
52110        iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
52111        /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
52112        rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
52113        if( rc!=SQLITE_OK ) break;
52114        iOffset = (iDbpage-1)*(i64)szPage;
52115        testcase( IS_BIG_INT(iOffset) );
52116        rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
52117        if( rc!=SQLITE_OK ) break;
52118      }
52119
52120      /* If work was actually accomplished... */
52121      if( rc==SQLITE_OK ){
52122        if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
52123          i64 szDb = pWal->hdr.nPage*(i64)szPage;
52124          testcase( IS_BIG_INT(szDb) );
52125          rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
52126          if( rc==SQLITE_OK && sync_flags ){
52127            rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
52128          }
52129        }
52130        if( rc==SQLITE_OK ){
52131          pInfo->nBackfill = mxSafeFrame;
52132        }
52133      }
52134
52135      /* Release the reader lock held while backfilling */
52136      walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
52137    }
52138
52139    if( rc==SQLITE_BUSY ){
52140      /* Reset the return code so as not to report a checkpoint failure
52141      ** just because there are active readers.  */
52142      rc = SQLITE_OK;
52143    }
52144  }
52145
52146  /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
52147  ** entire wal file has been copied into the database file, then block
52148  ** until all readers have finished using the wal file. This ensures that
52149  ** the next process to write to the database restarts the wal file.
52150  */
52151  if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
52152    assert( pWal->writeLock );
52153    if( pInfo->nBackfill<pWal->hdr.mxFrame ){
52154      rc = SQLITE_BUSY;
52155    }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
52156      u32 salt1;
52157      sqlite3_randomness(4, &salt1);
52158      assert( pInfo->nBackfill==pWal->hdr.mxFrame );
52159      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
52160      if( rc==SQLITE_OK ){
52161        if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
52162          /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
52163          ** SQLITE_CHECKPOINT_RESTART with the addition that it also
52164          ** truncates the log file to zero bytes just prior to a
52165          ** successful return.
52166          **
52167          ** In theory, it might be safe to do this without updating the
52168          ** wal-index header in shared memory, as all subsequent reader or
52169          ** writer clients should see that the entire log file has been
52170          ** checkpointed and behave accordingly. This seems unsafe though,
52171          ** as it would leave the system in a state where the contents of
52172          ** the wal-index header do not match the contents of the
52173          ** file-system. To avoid this, update the wal-index header to
52174          ** indicate that the log file contains zero valid frames.  */
52175          walRestartHdr(pWal, salt1);
52176          rc = sqlite3OsTruncate(pWal->pWalFd, 0);
52177        }
52178        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
52179      }
52180    }
52181  }
52182
52183 walcheckpoint_out:
52184  walIteratorFree(pIter);
52185  return rc;
52186}
52187
52188/*
52189** If the WAL file is currently larger than nMax bytes in size, truncate
52190** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
52191*/
52192static void walLimitSize(Wal *pWal, i64 nMax){
52193  i64 sz;
52194  int rx;
52195  sqlite3BeginBenignMalloc();
52196  rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
52197  if( rx==SQLITE_OK && (sz > nMax ) ){
52198    rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
52199  }
52200  sqlite3EndBenignMalloc();
52201  if( rx ){
52202    sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
52203  }
52204}
52205
52206/*
52207** Close a connection to a log file.
52208*/
52209SQLITE_PRIVATE int sqlite3WalClose(
52210  Wal *pWal,                      /* Wal to close */
52211  int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
52212  int nBuf,
52213  u8 *zBuf                        /* Buffer of at least nBuf bytes */
52214){
52215  int rc = SQLITE_OK;
52216  if( pWal ){
52217    int isDelete = 0;             /* True to unlink wal and wal-index files */
52218
52219    /* If an EXCLUSIVE lock can be obtained on the database file (using the
52220    ** ordinary, rollback-mode locking methods, this guarantees that the
52221    ** connection associated with this log file is the only connection to
52222    ** the database. In this case checkpoint the database and unlink both
52223    ** the wal and wal-index files.
52224    **
52225    ** The EXCLUSIVE lock is not released before returning.
52226    */
52227    rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
52228    if( rc==SQLITE_OK ){
52229      if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
52230        pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
52231      }
52232      rc = sqlite3WalCheckpoint(
52233          pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
52234      );
52235      if( rc==SQLITE_OK ){
52236        int bPersist = -1;
52237        sqlite3OsFileControlHint(
52238            pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
52239        );
52240        if( bPersist!=1 ){
52241          /* Try to delete the WAL file if the checkpoint completed and
52242          ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
52243          ** mode (!bPersist) */
52244          isDelete = 1;
52245        }else if( pWal->mxWalSize>=0 ){
52246          /* Try to truncate the WAL file to zero bytes if the checkpoint
52247          ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
52248          ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
52249          ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
52250          ** to zero bytes as truncating to the journal_size_limit might
52251          ** leave a corrupt WAL file on disk. */
52252          walLimitSize(pWal, 0);
52253        }
52254      }
52255    }
52256
52257    walIndexClose(pWal, isDelete);
52258    sqlite3OsClose(pWal->pWalFd);
52259    if( isDelete ){
52260      sqlite3BeginBenignMalloc();
52261      sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
52262      sqlite3EndBenignMalloc();
52263    }
52264    WALTRACE(("WAL%p: closed\n", pWal));
52265    sqlite3_free((void *)pWal->apWiData);
52266    sqlite3_free(pWal);
52267  }
52268  return rc;
52269}
52270
52271/*
52272** Try to read the wal-index header.  Return 0 on success and 1 if
52273** there is a problem.
52274**
52275** The wal-index is in shared memory.  Another thread or process might
52276** be writing the header at the same time this procedure is trying to
52277** read it, which might result in inconsistency.  A dirty read is detected
52278** by verifying that both copies of the header are the same and also by
52279** a checksum on the header.
52280**
52281** If and only if the read is consistent and the header is different from
52282** pWal->hdr, then pWal->hdr is updated to the content of the new header
52283** and *pChanged is set to 1.
52284**
52285** If the checksum cannot be verified return non-zero. If the header
52286** is read successfully and the checksum verified, return zero.
52287*/
52288static int walIndexTryHdr(Wal *pWal, int *pChanged){
52289  u32 aCksum[2];                  /* Checksum on the header content */
52290  WalIndexHdr h1, h2;             /* Two copies of the header content */
52291  WalIndexHdr volatile *aHdr;     /* Header in shared memory */
52292
52293  /* The first page of the wal-index must be mapped at this point. */
52294  assert( pWal->nWiData>0 && pWal->apWiData[0] );
52295
52296  /* Read the header. This might happen concurrently with a write to the
52297  ** same area of shared memory on a different CPU in a SMP,
52298  ** meaning it is possible that an inconsistent snapshot is read
52299  ** from the file. If this happens, return non-zero.
52300  **
52301  ** There are two copies of the header at the beginning of the wal-index.
52302  ** When reading, read [0] first then [1].  Writes are in the reverse order.
52303  ** Memory barriers are used to prevent the compiler or the hardware from
52304  ** reordering the reads and writes.
52305  */
52306  aHdr = walIndexHdr(pWal);
52307  memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
52308  walShmBarrier(pWal);
52309  memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
52310
52311  if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
52312    return 1;   /* Dirty read */
52313  }
52314  if( h1.isInit==0 ){
52315    return 1;   /* Malformed header - probably all zeros */
52316  }
52317  walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
52318  if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
52319    return 1;   /* Checksum does not match */
52320  }
52321
52322  if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
52323    *pChanged = 1;
52324    memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
52325    pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
52326    testcase( pWal->szPage<=32768 );
52327    testcase( pWal->szPage>=65536 );
52328  }
52329
52330  /* The header was successfully read. Return zero. */
52331  return 0;
52332}
52333
52334/*
52335** Read the wal-index header from the wal-index and into pWal->hdr.
52336** If the wal-header appears to be corrupt, try to reconstruct the
52337** wal-index from the WAL before returning.
52338**
52339** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
52340** changed by this operation.  If pWal->hdr is unchanged, set *pChanged
52341** to 0.
52342**
52343** If the wal-index header is successfully read, return SQLITE_OK.
52344** Otherwise an SQLite error code.
52345*/
52346static int walIndexReadHdr(Wal *pWal, int *pChanged){
52347  int rc;                         /* Return code */
52348  int badHdr;                     /* True if a header read failed */
52349  volatile u32 *page0;            /* Chunk of wal-index containing header */
52350
52351  /* Ensure that page 0 of the wal-index (the page that contains the
52352  ** wal-index header) is mapped. Return early if an error occurs here.
52353  */
52354  assert( pChanged );
52355  rc = walIndexPage(pWal, 0, &page0);
52356  if( rc!=SQLITE_OK ){
52357    return rc;
52358  };
52359  assert( page0 || pWal->writeLock==0 );
52360
52361  /* If the first page of the wal-index has been mapped, try to read the
52362  ** wal-index header immediately, without holding any lock. This usually
52363  ** works, but may fail if the wal-index header is corrupt or currently
52364  ** being modified by another thread or process.
52365  */
52366  badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
52367
52368  /* If the first attempt failed, it might have been due to a race
52369  ** with a writer.  So get a WRITE lock and try again.
52370  */
52371  assert( badHdr==0 || pWal->writeLock==0 );
52372  if( badHdr ){
52373    if( pWal->readOnly & WAL_SHM_RDONLY ){
52374      if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
52375        walUnlockShared(pWal, WAL_WRITE_LOCK);
52376        rc = SQLITE_READONLY_RECOVERY;
52377      }
52378    }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1, 1)) ){
52379      pWal->writeLock = 1;
52380      if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
52381        badHdr = walIndexTryHdr(pWal, pChanged);
52382        if( badHdr ){
52383          /* If the wal-index header is still malformed even while holding
52384          ** a WRITE lock, it can only mean that the header is corrupted and
52385          ** needs to be reconstructed.  So run recovery to do exactly that.
52386          */
52387          rc = walIndexRecover(pWal);
52388          *pChanged = 1;
52389        }
52390      }
52391      pWal->writeLock = 0;
52392      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
52393    }
52394  }
52395
52396  /* If the header is read successfully, check the version number to make
52397  ** sure the wal-index was not constructed with some future format that
52398  ** this version of SQLite cannot understand.
52399  */
52400  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
52401    rc = SQLITE_CANTOPEN_BKPT;
52402  }
52403
52404  return rc;
52405}
52406
52407/*
52408** This is the value that walTryBeginRead returns when it needs to
52409** be retried.
52410*/
52411#define WAL_RETRY  (-1)
52412
52413/*
52414** Attempt to start a read transaction.  This might fail due to a race or
52415** other transient condition.  When that happens, it returns WAL_RETRY to
52416** indicate to the caller that it is safe to retry immediately.
52417**
52418** On success return SQLITE_OK.  On a permanent failure (such an
52419** I/O error or an SQLITE_BUSY because another process is running
52420** recovery) return a positive error code.
52421**
52422** The useWal parameter is true to force the use of the WAL and disable
52423** the case where the WAL is bypassed because it has been completely
52424** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
52425** to make a copy of the wal-index header into pWal->hdr.  If the
52426** wal-index header has changed, *pChanged is set to 1 (as an indication
52427** to the caller that the local paget cache is obsolete and needs to be
52428** flushed.)  When useWal==1, the wal-index header is assumed to already
52429** be loaded and the pChanged parameter is unused.
52430**
52431** The caller must set the cnt parameter to the number of prior calls to
52432** this routine during the current read attempt that returned WAL_RETRY.
52433** This routine will start taking more aggressive measures to clear the
52434** race conditions after multiple WAL_RETRY returns, and after an excessive
52435** number of errors will ultimately return SQLITE_PROTOCOL.  The
52436** SQLITE_PROTOCOL return indicates that some other process has gone rogue
52437** and is not honoring the locking protocol.  There is a vanishingly small
52438** chance that SQLITE_PROTOCOL could be returned because of a run of really
52439** bad luck when there is lots of contention for the wal-index, but that
52440** possibility is so small that it can be safely neglected, we believe.
52441**
52442** On success, this routine obtains a read lock on
52443** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
52444** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
52445** that means the Wal does not hold any read lock.  The reader must not
52446** access any database page that is modified by a WAL frame up to and
52447** including frame number aReadMark[pWal->readLock].  The reader will
52448** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
52449** Or if pWal->readLock==0, then the reader will ignore the WAL
52450** completely and get all content directly from the database file.
52451** If the useWal parameter is 1 then the WAL will never be ignored and
52452** this routine will always set pWal->readLock>0 on success.
52453** When the read transaction is completed, the caller must release the
52454** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
52455**
52456** This routine uses the nBackfill and aReadMark[] fields of the header
52457** to select a particular WAL_READ_LOCK() that strives to let the
52458** checkpoint process do as much work as possible.  This routine might
52459** update values of the aReadMark[] array in the header, but if it does
52460** so it takes care to hold an exclusive lock on the corresponding
52461** WAL_READ_LOCK() while changing values.
52462*/
52463static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
52464  volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
52465  u32 mxReadMark;                 /* Largest aReadMark[] value */
52466  int mxI;                        /* Index of largest aReadMark[] value */
52467  int i;                          /* Loop counter */
52468  int rc = SQLITE_OK;             /* Return code  */
52469
52470  assert( pWal->readLock<0 );     /* Not currently locked */
52471
52472  /* Take steps to avoid spinning forever if there is a protocol error.
52473  **
52474  ** Circumstances that cause a RETRY should only last for the briefest
52475  ** instances of time.  No I/O or other system calls are done while the
52476  ** locks are held, so the locks should not be held for very long. But
52477  ** if we are unlucky, another process that is holding a lock might get
52478  ** paged out or take a page-fault that is time-consuming to resolve,
52479  ** during the few nanoseconds that it is holding the lock.  In that case,
52480  ** it might take longer than normal for the lock to free.
52481  **
52482  ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
52483  ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
52484  ** is more of a scheduler yield than an actual delay.  But on the 10th
52485  ** an subsequent retries, the delays start becoming longer and longer,
52486  ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
52487  ** The total delay time before giving up is less than 10 seconds.
52488  */
52489  if( cnt>5 ){
52490    int nDelay = 1;                      /* Pause time in microseconds */
52491    if( cnt>100 ){
52492      VVA_ONLY( pWal->lockError = 1; )
52493      return SQLITE_PROTOCOL;
52494    }
52495    if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
52496    sqlite3OsSleep(pWal->pVfs, nDelay);
52497  }
52498
52499  if( !useWal ){
52500    rc = walIndexReadHdr(pWal, pChanged);
52501    if( rc==SQLITE_BUSY ){
52502      /* If there is not a recovery running in another thread or process
52503      ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
52504      ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
52505      ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
52506      ** would be technically correct.  But the race is benign since with
52507      ** WAL_RETRY this routine will be called again and will probably be
52508      ** right on the second iteration.
52509      */
52510      if( pWal->apWiData[0]==0 ){
52511        /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
52512        ** We assume this is a transient condition, so return WAL_RETRY. The
52513        ** xShmMap() implementation used by the default unix and win32 VFS
52514        ** modules may return SQLITE_BUSY due to a race condition in the
52515        ** code that determines whether or not the shared-memory region
52516        ** must be zeroed before the requested page is returned.
52517        */
52518        rc = WAL_RETRY;
52519      }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
52520        walUnlockShared(pWal, WAL_RECOVER_LOCK);
52521        rc = WAL_RETRY;
52522      }else if( rc==SQLITE_BUSY ){
52523        rc = SQLITE_BUSY_RECOVERY;
52524      }
52525    }
52526    if( rc!=SQLITE_OK ){
52527      return rc;
52528    }
52529  }
52530
52531  pInfo = walCkptInfo(pWal);
52532  if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
52533    /* The WAL has been completely backfilled (or it is empty).
52534    ** and can be safely ignored.
52535    */
52536    rc = walLockShared(pWal, WAL_READ_LOCK(0));
52537    walShmBarrier(pWal);
52538    if( rc==SQLITE_OK ){
52539      if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
52540        /* It is not safe to allow the reader to continue here if frames
52541        ** may have been appended to the log before READ_LOCK(0) was obtained.
52542        ** When holding READ_LOCK(0), the reader ignores the entire log file,
52543        ** which implies that the database file contains a trustworthy
52544        ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
52545        ** happening, this is usually correct.
52546        **
52547        ** However, if frames have been appended to the log (or if the log
52548        ** is wrapped and written for that matter) before the READ_LOCK(0)
52549        ** is obtained, that is not necessarily true. A checkpointer may
52550        ** have started to backfill the appended frames but crashed before
52551        ** it finished. Leaving a corrupt image in the database file.
52552        */
52553        walUnlockShared(pWal, WAL_READ_LOCK(0));
52554        return WAL_RETRY;
52555      }
52556      pWal->readLock = 0;
52557      return SQLITE_OK;
52558    }else if( rc!=SQLITE_BUSY ){
52559      return rc;
52560    }
52561  }
52562
52563  /* If we get this far, it means that the reader will want to use
52564  ** the WAL to get at content from recent commits.  The job now is
52565  ** to select one of the aReadMark[] entries that is closest to
52566  ** but not exceeding pWal->hdr.mxFrame and lock that entry.
52567  */
52568  mxReadMark = 0;
52569  mxI = 0;
52570  for(i=1; i<WAL_NREADER; i++){
52571    u32 thisMark = pInfo->aReadMark[i];
52572    if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
52573      assert( thisMark!=READMARK_NOT_USED );
52574      mxReadMark = thisMark;
52575      mxI = i;
52576    }
52577  }
52578  /* There was once an "if" here. The extra "{" is to preserve indentation. */
52579  {
52580    if( (pWal->readOnly & WAL_SHM_RDONLY)==0
52581     && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
52582    ){
52583      for(i=1; i<WAL_NREADER; i++){
52584        rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1, 0);
52585        if( rc==SQLITE_OK ){
52586          mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
52587          mxI = i;
52588          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
52589          break;
52590        }else if( rc!=SQLITE_BUSY ){
52591          return rc;
52592        }
52593      }
52594    }
52595    if( mxI==0 ){
52596      assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
52597      return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
52598    }
52599
52600    rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
52601    if( rc ){
52602      return rc==SQLITE_BUSY ? WAL_RETRY : rc;
52603    }
52604    /* Now that the read-lock has been obtained, check that neither the
52605    ** value in the aReadMark[] array or the contents of the wal-index
52606    ** header have changed.
52607    **
52608    ** It is necessary to check that the wal-index header did not change
52609    ** between the time it was read and when the shared-lock was obtained
52610    ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
52611    ** that the log file may have been wrapped by a writer, or that frames
52612    ** that occur later in the log than pWal->hdr.mxFrame may have been
52613    ** copied into the database by a checkpointer. If either of these things
52614    ** happened, then reading the database with the current value of
52615    ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
52616    ** instead.
52617    **
52618    ** Before checking that the live wal-index header has not changed
52619    ** since it was read, set Wal.minFrame to the first frame in the wal
52620    ** file that has not yet been checkpointed. This client will not need
52621    ** to read any frames earlier than minFrame from the wal file - they
52622    ** can be safely read directly from the database file.
52623    **
52624    ** Because a ShmBarrier() call is made between taking the copy of
52625    ** nBackfill and checking that the wal-header in shared-memory still
52626    ** matches the one cached in pWal->hdr, it is guaranteed that the
52627    ** checkpointer that set nBackfill was not working with a wal-index
52628    ** header newer than that cached in pWal->hdr. If it were, that could
52629    ** cause a problem. The checkpointer could omit to checkpoint
52630    ** a version of page X that lies before pWal->minFrame (call that version
52631    ** A) on the basis that there is a newer version (version B) of the same
52632    ** page later in the wal file. But if version B happens to like past
52633    ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
52634    ** that it can read version A from the database file. However, since
52635    ** we can guarantee that the checkpointer that set nBackfill could not
52636    ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
52637    */
52638    pWal->minFrame = pInfo->nBackfill+1;
52639    walShmBarrier(pWal);
52640    if( pInfo->aReadMark[mxI]!=mxReadMark
52641     || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
52642    ){
52643      walUnlockShared(pWal, WAL_READ_LOCK(mxI));
52644      return WAL_RETRY;
52645    }else{
52646      assert( mxReadMark<=pWal->hdr.mxFrame );
52647      pWal->readLock = (i16)mxI;
52648    }
52649  }
52650  return rc;
52651}
52652
52653/*
52654** Begin a read transaction on the database.
52655**
52656** This routine used to be called sqlite3OpenSnapshot() and with good reason:
52657** it takes a snapshot of the state of the WAL and wal-index for the current
52658** instant in time.  The current thread will continue to use this snapshot.
52659** Other threads might append new content to the WAL and wal-index but
52660** that extra content is ignored by the current thread.
52661**
52662** If the database contents have changes since the previous read
52663** transaction, then *pChanged is set to 1 before returning.  The
52664** Pager layer will use this to know that is cache is stale and
52665** needs to be flushed.
52666*/
52667SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
52668  int rc;                         /* Return code */
52669  int cnt = 0;                    /* Number of TryBeginRead attempts */
52670
52671  do{
52672    rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
52673  }while( rc==WAL_RETRY );
52674  testcase( (rc&0xff)==SQLITE_BUSY );
52675  testcase( (rc&0xff)==SQLITE_IOERR );
52676  testcase( rc==SQLITE_PROTOCOL );
52677  testcase( rc==SQLITE_OK );
52678  return rc;
52679}
52680
52681/*
52682** Finish with a read transaction.  All this does is release the
52683** read-lock.
52684*/
52685SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
52686  sqlite3WalEndWriteTransaction(pWal);
52687  if( pWal->readLock>=0 ){
52688    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
52689    pWal->readLock = -1;
52690  }
52691}
52692
52693/*
52694** Search the wal file for page pgno. If found, set *piRead to the frame that
52695** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
52696** to zero.
52697**
52698** Return SQLITE_OK if successful, or an error code if an error occurs. If an
52699** error does occur, the final value of *piRead is undefined.
52700*/
52701SQLITE_PRIVATE int sqlite3WalFindFrame(
52702  Wal *pWal,                      /* WAL handle */
52703  Pgno pgno,                      /* Database page number to read data for */
52704  u32 *piRead                     /* OUT: Frame number (or zero) */
52705){
52706  u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
52707  u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
52708  int iHash;                      /* Used to loop through N hash tables */
52709  int iMinHash;
52710
52711  /* This routine is only be called from within a read transaction. */
52712  assert( pWal->readLock>=0 || pWal->lockError );
52713
52714  /* If the "last page" field of the wal-index header snapshot is 0, then
52715  ** no data will be read from the wal under any circumstances. Return early
52716  ** in this case as an optimization.  Likewise, if pWal->readLock==0,
52717  ** then the WAL is ignored by the reader so return early, as if the
52718  ** WAL were empty.
52719  */
52720  if( iLast==0 || pWal->readLock==0 ){
52721    *piRead = 0;
52722    return SQLITE_OK;
52723  }
52724
52725  /* Search the hash table or tables for an entry matching page number
52726  ** pgno. Each iteration of the following for() loop searches one
52727  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
52728  **
52729  ** This code might run concurrently to the code in walIndexAppend()
52730  ** that adds entries to the wal-index (and possibly to this hash
52731  ** table). This means the value just read from the hash
52732  ** slot (aHash[iKey]) may have been added before or after the
52733  ** current read transaction was opened. Values added after the
52734  ** read transaction was opened may have been written incorrectly -
52735  ** i.e. these slots may contain garbage data. However, we assume
52736  ** that any slots written before the current read transaction was
52737  ** opened remain unmodified.
52738  **
52739  ** For the reasons above, the if(...) condition featured in the inner
52740  ** loop of the following block is more stringent that would be required
52741  ** if we had exclusive access to the hash-table:
52742  **
52743  **   (aPgno[iFrame]==pgno):
52744  **     This condition filters out normal hash-table collisions.
52745  **
52746  **   (iFrame<=iLast):
52747  **     This condition filters out entries that were added to the hash
52748  **     table after the current read-transaction had started.
52749  */
52750  iMinHash = walFramePage(pWal->minFrame);
52751  for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){
52752    volatile ht_slot *aHash;      /* Pointer to hash table */
52753    volatile u32 *aPgno;          /* Pointer to array of page numbers */
52754    u32 iZero;                    /* Frame number corresponding to aPgno[0] */
52755    int iKey;                     /* Hash slot index */
52756    int nCollide;                 /* Number of hash collisions remaining */
52757    int rc;                       /* Error code */
52758
52759    rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
52760    if( rc!=SQLITE_OK ){
52761      return rc;
52762    }
52763    nCollide = HASHTABLE_NSLOT;
52764    for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
52765      u32 iFrame = aHash[iKey] + iZero;
52766      if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){
52767        assert( iFrame>iRead || CORRUPT_DB );
52768        iRead = iFrame;
52769      }
52770      if( (nCollide--)==0 ){
52771        return SQLITE_CORRUPT_BKPT;
52772      }
52773    }
52774  }
52775
52776#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
52777  /* If expensive assert() statements are available, do a linear search
52778  ** of the wal-index file content. Make sure the results agree with the
52779  ** result obtained using the hash indexes above.  */
52780  {
52781    u32 iRead2 = 0;
52782    u32 iTest;
52783    assert( pWal->minFrame>0 );
52784    for(iTest=iLast; iTest>=pWal->minFrame; iTest--){
52785      if( walFramePgno(pWal, iTest)==pgno ){
52786        iRead2 = iTest;
52787        break;
52788      }
52789    }
52790    assert( iRead==iRead2 );
52791  }
52792#endif
52793
52794  *piRead = iRead;
52795  return SQLITE_OK;
52796}
52797
52798/*
52799** Read the contents of frame iRead from the wal file into buffer pOut
52800** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
52801** error code otherwise.
52802*/
52803SQLITE_PRIVATE int sqlite3WalReadFrame(
52804  Wal *pWal,                      /* WAL handle */
52805  u32 iRead,                      /* Frame to read */
52806  int nOut,                       /* Size of buffer pOut in bytes */
52807  u8 *pOut                        /* Buffer to write page data to */
52808){
52809  int sz;
52810  i64 iOffset;
52811  sz = pWal->hdr.szPage;
52812  sz = (sz&0xfe00) + ((sz&0x0001)<<16);
52813  testcase( sz<=32768 );
52814  testcase( sz>=65536 );
52815  iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
52816  /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
52817  return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
52818}
52819
52820/*
52821** Return the size of the database in pages (or zero, if unknown).
52822*/
52823SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
52824  if( pWal && ALWAYS(pWal->readLock>=0) ){
52825    return pWal->hdr.nPage;
52826  }
52827  return 0;
52828}
52829
52830
52831/*
52832** This function starts a write transaction on the WAL.
52833**
52834** A read transaction must have already been started by a prior call
52835** to sqlite3WalBeginReadTransaction().
52836**
52837** If another thread or process has written into the database since
52838** the read transaction was started, then it is not possible for this
52839** thread to write as doing so would cause a fork.  So this routine
52840** returns SQLITE_BUSY in that case and no write transaction is started.
52841**
52842** There can only be a single writer active at a time.
52843*/
52844SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
52845  int rc;
52846
52847  /* Cannot start a write transaction without first holding a read
52848  ** transaction. */
52849  assert( pWal->readLock>=0 );
52850
52851  if( pWal->readOnly ){
52852    return SQLITE_READONLY;
52853  }
52854
52855  /* Only one writer allowed at a time.  Get the write lock.  Return
52856  ** SQLITE_BUSY if unable.
52857  */
52858  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1, 0);
52859  if( rc ){
52860    return rc;
52861  }
52862  pWal->writeLock = 1;
52863
52864  /* If another connection has written to the database file since the
52865  ** time the read transaction on this connection was started, then
52866  ** the write is disallowed.
52867  */
52868  if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
52869    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
52870    pWal->writeLock = 0;
52871    rc = SQLITE_BUSY_SNAPSHOT;
52872  }
52873
52874  return rc;
52875}
52876
52877/*
52878** End a write transaction.  The commit has already been done.  This
52879** routine merely releases the lock.
52880*/
52881SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
52882  if( pWal->writeLock ){
52883    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
52884    pWal->writeLock = 0;
52885    pWal->truncateOnCommit = 0;
52886  }
52887  return SQLITE_OK;
52888}
52889
52890/*
52891** If any data has been written (but not committed) to the log file, this
52892** function moves the write-pointer back to the start of the transaction.
52893**
52894** Additionally, the callback function is invoked for each frame written
52895** to the WAL since the start of the transaction. If the callback returns
52896** other than SQLITE_OK, it is not invoked again and the error code is
52897** returned to the caller.
52898**
52899** Otherwise, if the callback function does not return an error, this
52900** function returns SQLITE_OK.
52901*/
52902SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
52903  int rc = SQLITE_OK;
52904  if( ALWAYS(pWal->writeLock) ){
52905    Pgno iMax = pWal->hdr.mxFrame;
52906    Pgno iFrame;
52907
52908    /* Restore the clients cache of the wal-index header to the state it
52909    ** was in before the client began writing to the database.
52910    */
52911    memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
52912
52913    for(iFrame=pWal->hdr.mxFrame+1;
52914        ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
52915        iFrame++
52916    ){
52917      /* This call cannot fail. Unless the page for which the page number
52918      ** is passed as the second argument is (a) in the cache and
52919      ** (b) has an outstanding reference, then xUndo is either a no-op
52920      ** (if (a) is false) or simply expels the page from the cache (if (b)
52921      ** is false).
52922      **
52923      ** If the upper layer is doing a rollback, it is guaranteed that there
52924      ** are no outstanding references to any page other than page 1. And
52925      ** page 1 is never written to the log until the transaction is
52926      ** committed. As a result, the call to xUndo may not fail.
52927      */
52928      assert( walFramePgno(pWal, iFrame)!=1 );
52929      rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
52930    }
52931    if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
52932  }
52933  return rc;
52934}
52935
52936/*
52937** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
52938** values. This function populates the array with values required to
52939** "rollback" the write position of the WAL handle back to the current
52940** point in the event of a savepoint rollback (via WalSavepointUndo()).
52941*/
52942SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
52943  assert( pWal->writeLock );
52944  aWalData[0] = pWal->hdr.mxFrame;
52945  aWalData[1] = pWal->hdr.aFrameCksum[0];
52946  aWalData[2] = pWal->hdr.aFrameCksum[1];
52947  aWalData[3] = pWal->nCkpt;
52948}
52949
52950/*
52951** Move the write position of the WAL back to the point identified by
52952** the values in the aWalData[] array. aWalData must point to an array
52953** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
52954** by a call to WalSavepoint().
52955*/
52956SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
52957  int rc = SQLITE_OK;
52958
52959  assert( pWal->writeLock );
52960  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
52961
52962  if( aWalData[3]!=pWal->nCkpt ){
52963    /* This savepoint was opened immediately after the write-transaction
52964    ** was started. Right after that, the writer decided to wrap around
52965    ** to the start of the log. Update the savepoint values to match.
52966    */
52967    aWalData[0] = 0;
52968    aWalData[3] = pWal->nCkpt;
52969  }
52970
52971  if( aWalData[0]<pWal->hdr.mxFrame ){
52972    pWal->hdr.mxFrame = aWalData[0];
52973    pWal->hdr.aFrameCksum[0] = aWalData[1];
52974    pWal->hdr.aFrameCksum[1] = aWalData[2];
52975    walCleanupHash(pWal);
52976  }
52977
52978  return rc;
52979}
52980
52981/*
52982** This function is called just before writing a set of frames to the log
52983** file (see sqlite3WalFrames()). It checks to see if, instead of appending
52984** to the current log file, it is possible to overwrite the start of the
52985** existing log file with the new frames (i.e. "reset" the log). If so,
52986** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
52987** unchanged.
52988**
52989** SQLITE_OK is returned if no error is encountered (regardless of whether
52990** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
52991** if an error occurs.
52992*/
52993static int walRestartLog(Wal *pWal){
52994  int rc = SQLITE_OK;
52995  int cnt;
52996
52997  if( pWal->readLock==0 ){
52998    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
52999    assert( pInfo->nBackfill==pWal->hdr.mxFrame );
53000    if( pInfo->nBackfill>0 ){
53001      u32 salt1;
53002      sqlite3_randomness(4, &salt1);
53003      rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1, 0);
53004      if( rc==SQLITE_OK ){
53005        /* If all readers are using WAL_READ_LOCK(0) (in other words if no
53006        ** readers are currently using the WAL), then the transactions
53007        ** frames will overwrite the start of the existing log. Update the
53008        ** wal-index header to reflect this.
53009        **
53010        ** In theory it would be Ok to update the cache of the header only
53011        ** at this point. But updating the actual wal-index header is also
53012        ** safe and means there is no special case for sqlite3WalUndo()
53013        ** to handle if this transaction is rolled back.  */
53014        walRestartHdr(pWal, salt1);
53015        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
53016      }else if( rc!=SQLITE_BUSY ){
53017        return rc;
53018      }
53019    }
53020    walUnlockShared(pWal, WAL_READ_LOCK(0));
53021    pWal->readLock = -1;
53022    cnt = 0;
53023    do{
53024      int notUsed;
53025      rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
53026    }while( rc==WAL_RETRY );
53027    assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
53028    testcase( (rc&0xff)==SQLITE_IOERR );
53029    testcase( rc==SQLITE_PROTOCOL );
53030    testcase( rc==SQLITE_OK );
53031  }
53032  return rc;
53033}
53034
53035/*
53036** Information about the current state of the WAL file and where
53037** the next fsync should occur - passed from sqlite3WalFrames() into
53038** walWriteToLog().
53039*/
53040typedef struct WalWriter {
53041  Wal *pWal;                   /* The complete WAL information */
53042  sqlite3_file *pFd;           /* The WAL file to which we write */
53043  sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
53044  int syncFlags;               /* Flags for the fsync */
53045  int szPage;                  /* Size of one page */
53046} WalWriter;
53047
53048/*
53049** Write iAmt bytes of content into the WAL file beginning at iOffset.
53050** Do a sync when crossing the p->iSyncPoint boundary.
53051**
53052** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
53053** first write the part before iSyncPoint, then sync, then write the
53054** rest.
53055*/
53056static int walWriteToLog(
53057  WalWriter *p,              /* WAL to write to */
53058  void *pContent,            /* Content to be written */
53059  int iAmt,                  /* Number of bytes to write */
53060  sqlite3_int64 iOffset      /* Start writing at this offset */
53061){
53062  int rc;
53063  if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
53064    int iFirstAmt = (int)(p->iSyncPoint - iOffset);
53065    rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
53066    if( rc ) return rc;
53067    iOffset += iFirstAmt;
53068    iAmt -= iFirstAmt;
53069    pContent = (void*)(iFirstAmt + (char*)pContent);
53070    assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
53071    rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
53072    if( iAmt==0 || rc ) return rc;
53073  }
53074  rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
53075  return rc;
53076}
53077
53078/*
53079** Write out a single frame of the WAL
53080*/
53081static int walWriteOneFrame(
53082  WalWriter *p,               /* Where to write the frame */
53083  PgHdr *pPage,               /* The page of the frame to be written */
53084  int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
53085  sqlite3_int64 iOffset       /* Byte offset at which to write */
53086){
53087  int rc;                         /* Result code from subfunctions */
53088  void *pData;                    /* Data actually written */
53089  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
53090#if defined(SQLITE_HAS_CODEC)
53091  if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
53092#else
53093  pData = pPage->pData;
53094#endif
53095  walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
53096  rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
53097  if( rc ) return rc;
53098  /* Write the page data */
53099  rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
53100  return rc;
53101}
53102
53103/*
53104** Write a set of frames to the log. The caller must hold the write-lock
53105** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
53106*/
53107SQLITE_PRIVATE int sqlite3WalFrames(
53108  Wal *pWal,                      /* Wal handle to write to */
53109  int szPage,                     /* Database page-size in bytes */
53110  PgHdr *pList,                   /* List of dirty pages to write */
53111  Pgno nTruncate,                 /* Database size after this commit */
53112  int isCommit,                   /* True if this is a commit */
53113  int sync_flags                  /* Flags to pass to OsSync() (or 0) */
53114){
53115  int rc;                         /* Used to catch return codes */
53116  u32 iFrame;                     /* Next frame address */
53117  PgHdr *p;                       /* Iterator to run through pList with. */
53118  PgHdr *pLast = 0;               /* Last frame in list */
53119  int nExtra = 0;                 /* Number of extra copies of last page */
53120  int szFrame;                    /* The size of a single frame */
53121  i64 iOffset;                    /* Next byte to write in WAL file */
53122  WalWriter w;                    /* The writer */
53123
53124  assert( pList );
53125  assert( pWal->writeLock );
53126
53127  /* If this frame set completes a transaction, then nTruncate>0.  If
53128  ** nTruncate==0 then this frame set does not complete the transaction. */
53129  assert( (isCommit!=0)==(nTruncate!=0) );
53130
53131#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
53132  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
53133    WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
53134              pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
53135  }
53136#endif
53137
53138  /* See if it is possible to write these frames into the start of the
53139  ** log file, instead of appending to it at pWal->hdr.mxFrame.
53140  */
53141  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
53142    return rc;
53143  }
53144
53145  /* If this is the first frame written into the log, write the WAL
53146  ** header to the start of the WAL file. See comments at the top of
53147  ** this source file for a description of the WAL header format.
53148  */
53149  iFrame = pWal->hdr.mxFrame;
53150  if( iFrame==0 ){
53151    u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
53152    u32 aCksum[2];                /* Checksum for wal-header */
53153
53154    sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
53155    sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
53156    sqlite3Put4byte(&aWalHdr[8], szPage);
53157    sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
53158    if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
53159    memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
53160    walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
53161    sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
53162    sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
53163
53164    pWal->szPage = szPage;
53165    pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
53166    pWal->hdr.aFrameCksum[0] = aCksum[0];
53167    pWal->hdr.aFrameCksum[1] = aCksum[1];
53168    pWal->truncateOnCommit = 1;
53169
53170    rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
53171    WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
53172    if( rc!=SQLITE_OK ){
53173      return rc;
53174    }
53175
53176    /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
53177    ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
53178    ** an out-of-order write following a WAL restart could result in
53179    ** database corruption.  See the ticket:
53180    **
53181    **     http://localhost:591/sqlite/info/ff5be73dee
53182    */
53183    if( pWal->syncHeader && sync_flags ){
53184      rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
53185      if( rc ) return rc;
53186    }
53187  }
53188  assert( (int)pWal->szPage==szPage );
53189
53190  /* Setup information needed to write frames into the WAL */
53191  w.pWal = pWal;
53192  w.pFd = pWal->pWalFd;
53193  w.iSyncPoint = 0;
53194  w.syncFlags = sync_flags;
53195  w.szPage = szPage;
53196  iOffset = walFrameOffset(iFrame+1, szPage);
53197  szFrame = szPage + WAL_FRAME_HDRSIZE;
53198
53199  /* Write all frames into the log file exactly once */
53200  for(p=pList; p; p=p->pDirty){
53201    int nDbSize;   /* 0 normally.  Positive == commit flag */
53202    iFrame++;
53203    assert( iOffset==walFrameOffset(iFrame, szPage) );
53204    nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
53205    rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
53206    if( rc ) return rc;
53207    pLast = p;
53208    iOffset += szFrame;
53209  }
53210
53211  /* If this is the end of a transaction, then we might need to pad
53212  ** the transaction and/or sync the WAL file.
53213  **
53214  ** Padding and syncing only occur if this set of frames complete a
53215  ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
53216  ** or synchronous==OFF, then no padding or syncing are needed.
53217  **
53218  ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
53219  ** needed and only the sync is done.  If padding is needed, then the
53220  ** final frame is repeated (with its commit mark) until the next sector
53221  ** boundary is crossed.  Only the part of the WAL prior to the last
53222  ** sector boundary is synced; the part of the last frame that extends
53223  ** past the sector boundary is written after the sync.
53224  */
53225  if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
53226    if( pWal->padToSectorBoundary ){
53227      int sectorSize = sqlite3SectorSize(pWal->pWalFd);
53228      w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
53229      while( iOffset<w.iSyncPoint ){
53230        rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
53231        if( rc ) return rc;
53232        iOffset += szFrame;
53233        nExtra++;
53234      }
53235    }else{
53236      rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
53237    }
53238  }
53239
53240  /* If this frame set completes the first transaction in the WAL and
53241  ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
53242  ** journal size limit, if possible.
53243  */
53244  if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
53245    i64 sz = pWal->mxWalSize;
53246    if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
53247      sz = walFrameOffset(iFrame+nExtra+1, szPage);
53248    }
53249    walLimitSize(pWal, sz);
53250    pWal->truncateOnCommit = 0;
53251  }
53252
53253  /* Append data to the wal-index. It is not necessary to lock the
53254  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
53255  ** guarantees that there are no other writers, and no data that may
53256  ** be in use by existing readers is being overwritten.
53257  */
53258  iFrame = pWal->hdr.mxFrame;
53259  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
53260    iFrame++;
53261    rc = walIndexAppend(pWal, iFrame, p->pgno);
53262  }
53263  while( rc==SQLITE_OK && nExtra>0 ){
53264    iFrame++;
53265    nExtra--;
53266    rc = walIndexAppend(pWal, iFrame, pLast->pgno);
53267  }
53268
53269  if( rc==SQLITE_OK ){
53270    /* Update the private copy of the header. */
53271    pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
53272    testcase( szPage<=32768 );
53273    testcase( szPage>=65536 );
53274    pWal->hdr.mxFrame = iFrame;
53275    if( isCommit ){
53276      pWal->hdr.iChange++;
53277      pWal->hdr.nPage = nTruncate;
53278    }
53279    /* If this is a commit, update the wal-index header too. */
53280    if( isCommit ){
53281      walIndexWriteHdr(pWal);
53282      pWal->iCallback = iFrame;
53283    }
53284  }
53285
53286  WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
53287  return rc;
53288}
53289
53290/*
53291** This routine is called to implement sqlite3_wal_checkpoint() and
53292** related interfaces.
53293**
53294** Obtain a CHECKPOINT lock and then backfill as much information as
53295** we can from WAL into the database.
53296**
53297** If parameter xBusy is not NULL, it is a pointer to a busy-handler
53298** callback. In this case this function runs a blocking checkpoint.
53299*/
53300SQLITE_PRIVATE int sqlite3WalCheckpoint(
53301  Wal *pWal,                      /* Wal connection */
53302  int eMode,                      /* PASSIVE, FULL, RESTART, or TRUNCATE */
53303  int (*xBusy)(void*),            /* Function to call when busy */
53304  void *pBusyArg,                 /* Context argument for xBusyHandler */
53305  int sync_flags,                 /* Flags to sync db file with (or 0) */
53306  int nBuf,                       /* Size of temporary buffer */
53307  u8 *zBuf,                       /* Temporary buffer to use */
53308  int *pnLog,                     /* OUT: Number of frames in WAL */
53309  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
53310){
53311  int rc;                         /* Return code */
53312  int isChanged = 0;              /* True if a new wal-index header is loaded */
53313  int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
53314  int (*xBusy2)(void*) = xBusy;   /* Busy handler for eMode2 */
53315
53316  assert( pWal->ckptLock==0 );
53317  assert( pWal->writeLock==0 );
53318
53319  /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
53320  ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
53321  assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
53322
53323  if( pWal->readOnly ) return SQLITE_READONLY;
53324  WALTRACE(("WAL%p: checkpoint begins\n", pWal));
53325
53326  /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
53327  ** "checkpoint" lock on the database file. */
53328  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1, 0);
53329  if( rc ){
53330    /* EVIDENCE-OF: R-10421-19736 If any other process is running a
53331    ** checkpoint operation at the same time, the lock cannot be obtained and
53332    ** SQLITE_BUSY is returned.
53333    ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
53334    ** it will not be invoked in this case.
53335    */
53336    testcase( rc==SQLITE_BUSY );
53337    testcase( xBusy!=0 );
53338    return rc;
53339  }
53340  pWal->ckptLock = 1;
53341
53342  /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
53343  ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
53344  ** file.
53345  **
53346  ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
53347  ** immediately, and a busy-handler is configured, it is invoked and the
53348  ** writer lock retried until either the busy-handler returns 0 or the
53349  ** lock is successfully obtained.
53350  */
53351  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
53352    rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
53353    if( rc==SQLITE_OK ){
53354      pWal->writeLock = 1;
53355    }else if( rc==SQLITE_BUSY ){
53356      eMode2 = SQLITE_CHECKPOINT_PASSIVE;
53357      xBusy2 = 0;
53358      rc = SQLITE_OK;
53359    }
53360  }
53361
53362  /* Read the wal-index header. */
53363  if( rc==SQLITE_OK ){
53364    rc = walIndexReadHdr(pWal, &isChanged);
53365    if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
53366      sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
53367    }
53368  }
53369
53370  /* Copy data from the log to the database file. */
53371  if( rc==SQLITE_OK ){
53372    if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
53373      rc = SQLITE_CORRUPT_BKPT;
53374    }else{
53375      rc = walCheckpoint(pWal, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
53376    }
53377
53378    /* If no error occurred, set the output variables. */
53379    if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
53380      if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
53381      if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
53382    }
53383  }
53384
53385  if( isChanged ){
53386    /* If a new wal-index header was loaded before the checkpoint was
53387    ** performed, then the pager-cache associated with pWal is now
53388    ** out of date. So zero the cached wal-index header to ensure that
53389    ** next time the pager opens a snapshot on this database it knows that
53390    ** the cache needs to be reset.
53391    */
53392    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
53393  }
53394
53395  /* Release the locks. */
53396  sqlite3WalEndWriteTransaction(pWal);
53397  walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
53398  pWal->ckptLock = 0;
53399  WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
53400  return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
53401}
53402
53403/* Return the value to pass to a sqlite3_wal_hook callback, the
53404** number of frames in the WAL at the point of the last commit since
53405** sqlite3WalCallback() was called.  If no commits have occurred since
53406** the last call, then return 0.
53407*/
53408SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
53409  u32 ret = 0;
53410  if( pWal ){
53411    ret = pWal->iCallback;
53412    pWal->iCallback = 0;
53413  }
53414  return (int)ret;
53415}
53416
53417/*
53418** This function is called to change the WAL subsystem into or out
53419** of locking_mode=EXCLUSIVE.
53420**
53421** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
53422** into locking_mode=NORMAL.  This means that we must acquire a lock
53423** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
53424** or if the acquisition of the lock fails, then return 0.  If the
53425** transition out of exclusive-mode is successful, return 1.  This
53426** operation must occur while the pager is still holding the exclusive
53427** lock on the main database file.
53428**
53429** If op is one, then change from locking_mode=NORMAL into
53430** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
53431** be released.  Return 1 if the transition is made and 0 if the
53432** WAL is already in exclusive-locking mode - meaning that this
53433** routine is a no-op.  The pager must already hold the exclusive lock
53434** on the main database file before invoking this operation.
53435**
53436** If op is negative, then do a dry-run of the op==1 case but do
53437** not actually change anything. The pager uses this to see if it
53438** should acquire the database exclusive lock prior to invoking
53439** the op==1 case.
53440*/
53441SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
53442  int rc;
53443  assert( pWal->writeLock==0 );
53444  assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
53445
53446  /* pWal->readLock is usually set, but might be -1 if there was a
53447  ** prior error while attempting to acquire are read-lock. This cannot
53448  ** happen if the connection is actually in exclusive mode (as no xShmLock
53449  ** locks are taken in this case). Nor should the pager attempt to
53450  ** upgrade to exclusive-mode following such an error.
53451  */
53452  assert( pWal->readLock>=0 || pWal->lockError );
53453  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
53454
53455  if( op==0 ){
53456    if( pWal->exclusiveMode ){
53457      pWal->exclusiveMode = 0;
53458      if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
53459        pWal->exclusiveMode = 1;
53460      }
53461      rc = pWal->exclusiveMode==0;
53462    }else{
53463      /* Already in locking_mode=NORMAL */
53464      rc = 0;
53465    }
53466  }else if( op>0 ){
53467    assert( pWal->exclusiveMode==0 );
53468    assert( pWal->readLock>=0 );
53469    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
53470    pWal->exclusiveMode = 1;
53471    rc = 1;
53472  }else{
53473    rc = pWal->exclusiveMode==0;
53474  }
53475  return rc;
53476}
53477
53478/*
53479** Return true if the argument is non-NULL and the WAL module is using
53480** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
53481** WAL module is using shared-memory, return false.
53482*/
53483SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
53484  return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
53485}
53486
53487#ifdef SQLITE_ENABLE_ZIPVFS
53488/*
53489** If the argument is not NULL, it points to a Wal object that holds a
53490** read-lock. This function returns the database page-size if it is known,
53491** or zero if it is not (or if pWal is NULL).
53492*/
53493SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
53494  assert( pWal==0 || pWal->readLock>=0 );
53495  return (pWal ? pWal->szPage : 0);
53496}
53497#endif
53498
53499#endif /* #ifndef SQLITE_OMIT_WAL */
53500
53501/************** End of wal.c *************************************************/
53502/************** Begin file btmutex.c *****************************************/
53503/*
53504** 2007 August 27
53505**
53506** The author disclaims copyright to this source code.  In place of
53507** a legal notice, here is a blessing:
53508**
53509**    May you do good and not evil.
53510**    May you find forgiveness for yourself and forgive others.
53511**    May you share freely, never taking more than you give.
53512**
53513*************************************************************************
53514**
53515** This file contains code used to implement mutexes on Btree objects.
53516** This code really belongs in btree.c.  But btree.c is getting too
53517** big and we want to break it down some.  This packaged seemed like
53518** a good breakout.
53519*/
53520/************** Include btreeInt.h in the middle of btmutex.c ****************/
53521/************** Begin file btreeInt.h ****************************************/
53522/*
53523** 2004 April 6
53524**
53525** The author disclaims copyright to this source code.  In place of
53526** a legal notice, here is a blessing:
53527**
53528**    May you do good and not evil.
53529**    May you find forgiveness for yourself and forgive others.
53530**    May you share freely, never taking more than you give.
53531**
53532*************************************************************************
53533** This file implements an external (disk-based) database using BTrees.
53534** For a detailed discussion of BTrees, refer to
53535**
53536**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
53537**     "Sorting And Searching", pages 473-480. Addison-Wesley
53538**     Publishing Company, Reading, Massachusetts.
53539**
53540** The basic idea is that each page of the file contains N database
53541** entries and N+1 pointers to subpages.
53542**
53543**   ----------------------------------------------------------------
53544**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
53545**   ----------------------------------------------------------------
53546**
53547** All of the keys on the page that Ptr(0) points to have values less
53548** than Key(0).  All of the keys on page Ptr(1) and its subpages have
53549** values greater than Key(0) and less than Key(1).  All of the keys
53550** on Ptr(N) and its subpages have values greater than Key(N-1).  And
53551** so forth.
53552**
53553** Finding a particular key requires reading O(log(M)) pages from the
53554** disk where M is the number of entries in the tree.
53555**
53556** In this implementation, a single file can hold one or more separate
53557** BTrees.  Each BTree is identified by the index of its root page.  The
53558** key and data for any entry are combined to form the "payload".  A
53559** fixed amount of payload can be carried directly on the database
53560** page.  If the payload is larger than the preset amount then surplus
53561** bytes are stored on overflow pages.  The payload for an entry
53562** and the preceding pointer are combined to form a "Cell".  Each
53563** page has a small header which contains the Ptr(N) pointer and other
53564** information such as the size of key and data.
53565**
53566** FORMAT DETAILS
53567**
53568** The file is divided into pages.  The first page is called page 1,
53569** the second is page 2, and so forth.  A page number of zero indicates
53570** "no such page".  The page size can be any power of 2 between 512 and 65536.
53571** Each page can be either a btree page, a freelist page, an overflow
53572** page, or a pointer-map page.
53573**
53574** The first page is always a btree page.  The first 100 bytes of the first
53575** page contain a special header (the "file header") that describes the file.
53576** The format of the file header is as follows:
53577**
53578**   OFFSET   SIZE    DESCRIPTION
53579**      0      16     Header string: "SQLite format 3\000"
53580**     16       2     Page size in bytes.  (1 means 65536)
53581**     18       1     File format write version
53582**     19       1     File format read version
53583**     20       1     Bytes of unused space at the end of each page
53584**     21       1     Max embedded payload fraction (must be 64)
53585**     22       1     Min embedded payload fraction (must be 32)
53586**     23       1     Min leaf payload fraction (must be 32)
53587**     24       4     File change counter
53588**     28       4     Reserved for future use
53589**     32       4     First freelist page
53590**     36       4     Number of freelist pages in the file
53591**     40      60     15 4-byte meta values passed to higher layers
53592**
53593**     40       4     Schema cookie
53594**     44       4     File format of schema layer
53595**     48       4     Size of page cache
53596**     52       4     Largest root-page (auto/incr_vacuum)
53597**     56       4     1=UTF-8 2=UTF16le 3=UTF16be
53598**     60       4     User version
53599**     64       4     Incremental vacuum mode
53600**     68       4     Application-ID
53601**     72      20     unused
53602**     92       4     The version-valid-for number
53603**     96       4     SQLITE_VERSION_NUMBER
53604**
53605** All of the integer values are big-endian (most significant byte first).
53606**
53607** The file change counter is incremented when the database is changed
53608** This counter allows other processes to know when the file has changed
53609** and thus when they need to flush their cache.
53610**
53611** The max embedded payload fraction is the amount of the total usable
53612** space in a page that can be consumed by a single cell for standard
53613** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
53614** is to limit the maximum cell size so that at least 4 cells will fit
53615** on one page.  Thus the default max embedded payload fraction is 64.
53616**
53617** If the payload for a cell is larger than the max payload, then extra
53618** payload is spilled to overflow pages.  Once an overflow page is allocated,
53619** as many bytes as possible are moved into the overflow pages without letting
53620** the cell size drop below the min embedded payload fraction.
53621**
53622** The min leaf payload fraction is like the min embedded payload fraction
53623** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
53624** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
53625** not specified in the header.
53626**
53627** Each btree pages is divided into three sections:  The header, the
53628** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
53629** file header that occurs before the page header.
53630**
53631**      |----------------|
53632**      | file header    |   100 bytes.  Page 1 only.
53633**      |----------------|
53634**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
53635**      |----------------|
53636**      | cell pointer   |   |  2 bytes per cell.  Sorted order.
53637**      | array          |   |  Grows downward
53638**      |                |   v
53639**      |----------------|
53640**      | unallocated    |
53641**      | space          |
53642**      |----------------|   ^  Grows upwards
53643**      | cell content   |   |  Arbitrary order interspersed with freeblocks.
53644**      | area           |   |  and free space fragments.
53645**      |----------------|
53646**
53647** The page headers looks like this:
53648**
53649**   OFFSET   SIZE     DESCRIPTION
53650**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
53651**      1       2      byte offset to the first freeblock
53652**      3       2      number of cells on this page
53653**      5       2      first byte of the cell content area
53654**      7       1      number of fragmented free bytes
53655**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
53656**
53657** The flags define the format of this btree page.  The leaf flag means that
53658** this page has no children.  The zerodata flag means that this page carries
53659** only keys and no data.  The intkey flag means that the key is an integer
53660** which is stored in the key size entry of the cell header rather than in
53661** the payload area.
53662**
53663** The cell pointer array begins on the first byte after the page header.
53664** The cell pointer array contains zero or more 2-byte numbers which are
53665** offsets from the beginning of the page to the cell content in the cell
53666** content area.  The cell pointers occur in sorted order.  The system strives
53667** to keep free space after the last cell pointer so that new cells can
53668** be easily added without having to defragment the page.
53669**
53670** Cell content is stored at the very end of the page and grows toward the
53671** beginning of the page.
53672**
53673** Unused space within the cell content area is collected into a linked list of
53674** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
53675** to the first freeblock is given in the header.  Freeblocks occur in
53676** increasing order.  Because a freeblock must be at least 4 bytes in size,
53677** any group of 3 or fewer unused bytes in the cell content area cannot
53678** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
53679** a fragment.  The total number of bytes in all fragments is recorded.
53680** in the page header at offset 7.
53681**
53682**    SIZE    DESCRIPTION
53683**      2     Byte offset of the next freeblock
53684**      2     Bytes in this freeblock
53685**
53686** Cells are of variable length.  Cells are stored in the cell content area at
53687** the end of the page.  Pointers to the cells are in the cell pointer array
53688** that immediately follows the page header.  Cells is not necessarily
53689** contiguous or in order, but cell pointers are contiguous and in order.
53690**
53691** Cell content makes use of variable length integers.  A variable
53692** length integer is 1 to 9 bytes where the lower 7 bits of each
53693** byte are used.  The integer consists of all bytes that have bit 8 set and
53694** the first byte with bit 8 clear.  The most significant byte of the integer
53695** appears first.  A variable-length integer may not be more than 9 bytes long.
53696** As a special case, all 8 bytes of the 9th byte are used as data.  This
53697** allows a 64-bit integer to be encoded in 9 bytes.
53698**
53699**    0x00                      becomes  0x00000000
53700**    0x7f                      becomes  0x0000007f
53701**    0x81 0x00                 becomes  0x00000080
53702**    0x82 0x00                 becomes  0x00000100
53703**    0x80 0x7f                 becomes  0x0000007f
53704**    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
53705**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
53706**
53707** Variable length integers are used for rowids and to hold the number of
53708** bytes of key and data in a btree cell.
53709**
53710** The content of a cell looks like this:
53711**
53712**    SIZE    DESCRIPTION
53713**      4     Page number of the left child. Omitted if leaf flag is set.
53714**     var    Number of bytes of data. Omitted if the zerodata flag is set.
53715**     var    Number of bytes of key. Or the key itself if intkey flag is set.
53716**      *     Payload
53717**      4     First page of the overflow chain.  Omitted if no overflow
53718**
53719** Overflow pages form a linked list.  Each page except the last is completely
53720** filled with data (pagesize - 4 bytes).  The last page can have as little
53721** as 1 byte of data.
53722**
53723**    SIZE    DESCRIPTION
53724**      4     Page number of next overflow page
53725**      *     Data
53726**
53727** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
53728** file header points to the first in a linked list of trunk page.  Each trunk
53729** page points to multiple leaf pages.  The content of a leaf page is
53730** unspecified.  A trunk page looks like this:
53731**
53732**    SIZE    DESCRIPTION
53733**      4     Page number of next trunk page
53734**      4     Number of leaf pointers on this page
53735**      *     zero or more pages numbers of leaves
53736*/
53737/* #include "sqliteInt.h" */
53738
53739
53740/* The following value is the maximum cell size assuming a maximum page
53741** size give above.
53742*/
53743#define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
53744
53745/* The maximum number of cells on a single page of the database.  This
53746** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
53747** plus 2 bytes for the index to the cell in the page header).  Such
53748** small cells will be rare, but they are possible.
53749*/
53750#define MX_CELL(pBt) ((pBt->pageSize-8)/6)
53751
53752/* Forward declarations */
53753typedef struct MemPage MemPage;
53754typedef struct BtLock BtLock;
53755typedef struct CellInfo CellInfo;
53756
53757/*
53758** This is a magic string that appears at the beginning of every
53759** SQLite database in order to identify the file as a real database.
53760**
53761** You can change this value at compile-time by specifying a
53762** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
53763** header must be exactly 16 bytes including the zero-terminator so
53764** the string itself should be 15 characters long.  If you change
53765** the header, then your custom library will not be able to read
53766** databases generated by the standard tools and the standard tools
53767** will not be able to read databases created by your custom library.
53768*/
53769#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
53770#  define SQLITE_FILE_HEADER "SQLite format 3"
53771#endif
53772
53773/*
53774** Page type flags.  An ORed combination of these flags appear as the
53775** first byte of on-disk image of every BTree page.
53776*/
53777#define PTF_INTKEY    0x01
53778#define PTF_ZERODATA  0x02
53779#define PTF_LEAFDATA  0x04
53780#define PTF_LEAF      0x08
53781
53782/*
53783** As each page of the file is loaded into memory, an instance of the following
53784** structure is appended and initialized to zero.  This structure stores
53785** information about the page that is decoded from the raw file page.
53786**
53787** The pParent field points back to the parent page.  This allows us to
53788** walk up the BTree from any leaf to the root.  Care must be taken to
53789** unref() the parent page pointer when this page is no longer referenced.
53790** The pageDestructor() routine handles that chore.
53791**
53792** Access to all fields of this structure is controlled by the mutex
53793** stored in MemPage.pBt->mutex.
53794*/
53795struct MemPage {
53796  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
53797  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
53798  u8 intKey;           /* True if table b-trees.  False for index b-trees */
53799  u8 intKeyLeaf;       /* True if the leaf of an intKey table */
53800  u8 noPayload;        /* True if internal intKey page (thus w/o data) */
53801  u8 leaf;             /* True if a leaf page */
53802  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
53803  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
53804  u8 max1bytePayload;  /* min(maxLocal,127) */
53805  u8 bBusy;            /* Prevent endless loops on corrupt database files */
53806  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
53807  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
53808  u16 cellOffset;      /* Index in aData of first cell pointer */
53809  u16 nFree;           /* Number of free bytes on the page */
53810  u16 nCell;           /* Number of cells on this page, local and ovfl */
53811  u16 maskPage;        /* Mask for page offset */
53812  u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
53813                       ** non-overflow cell */
53814  u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
53815  BtShared *pBt;       /* Pointer to BtShared that this page is part of */
53816  u8 *aData;           /* Pointer to disk image of the page data */
53817  u8 *aDataEnd;        /* One byte past the end of usable data */
53818  u8 *aCellIdx;        /* The cell index area */
53819  u8 *aDataOfst;       /* Same as aData for leaves.  aData+4 for interior */
53820  DbPage *pDbPage;     /* Pager page handle */
53821  u16 (*xCellSize)(MemPage*,u8*);             /* cellSizePtr method */
53822  void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
53823  Pgno pgno;           /* Page number for this page */
53824};
53825
53826/*
53827** The in-memory image of a disk page has the auxiliary information appended
53828** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
53829** that extra information.
53830*/
53831#define EXTRA_SIZE sizeof(MemPage)
53832
53833/*
53834** A linked list of the following structures is stored at BtShared.pLock.
53835** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
53836** is opened on the table with root page BtShared.iTable. Locks are removed
53837** from this list when a transaction is committed or rolled back, or when
53838** a btree handle is closed.
53839*/
53840struct BtLock {
53841  Btree *pBtree;        /* Btree handle holding this lock */
53842  Pgno iTable;          /* Root page of table */
53843  u8 eLock;             /* READ_LOCK or WRITE_LOCK */
53844  BtLock *pNext;        /* Next in BtShared.pLock list */
53845};
53846
53847/* Candidate values for BtLock.eLock */
53848#define READ_LOCK     1
53849#define WRITE_LOCK    2
53850
53851/* A Btree handle
53852**
53853** A database connection contains a pointer to an instance of
53854** this object for every database file that it has open.  This structure
53855** is opaque to the database connection.  The database connection cannot
53856** see the internals of this structure and only deals with pointers to
53857** this structure.
53858**
53859** For some database files, the same underlying database cache might be
53860** shared between multiple connections.  In that case, each connection
53861** has it own instance of this object.  But each instance of this object
53862** points to the same BtShared object.  The database cache and the
53863** schema associated with the database file are all contained within
53864** the BtShared object.
53865**
53866** All fields in this structure are accessed under sqlite3.mutex.
53867** The pBt pointer itself may not be changed while there exists cursors
53868** in the referenced BtShared that point back to this Btree since those
53869** cursors have to go through this Btree to find their BtShared and
53870** they often do so without holding sqlite3.mutex.
53871*/
53872struct Btree {
53873  sqlite3 *db;       /* The database connection holding this btree */
53874  BtShared *pBt;     /* Sharable content of this btree */
53875  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
53876  u8 sharable;       /* True if we can share pBt with another db */
53877  u8 locked;         /* True if db currently has pBt locked */
53878  u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
53879  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
53880  int nBackup;       /* Number of backup operations reading this btree */
53881  u32 iDataVersion;  /* Combines with pBt->pPager->iDataVersion */
53882  Btree *pNext;      /* List of other sharable Btrees from the same db */
53883  Btree *pPrev;      /* Back pointer of the same list */
53884#ifndef SQLITE_OMIT_SHARED_CACHE
53885  BtLock lock;       /* Object used to lock page 1 */
53886#endif
53887};
53888
53889/*
53890** Btree.inTrans may take one of the following values.
53891**
53892** If the shared-data extension is enabled, there may be multiple users
53893** of the Btree structure. At most one of these may open a write transaction,
53894** but any number may have active read transactions.
53895*/
53896#define TRANS_NONE  0
53897#define TRANS_READ  1
53898#define TRANS_WRITE 2
53899
53900/*
53901** An instance of this object represents a single database file.
53902**
53903** A single database file can be in use at the same time by two
53904** or more database connections.  When two or more connections are
53905** sharing the same database file, each connection has it own
53906** private Btree object for the file and each of those Btrees points
53907** to this one BtShared object.  BtShared.nRef is the number of
53908** connections currently sharing this database file.
53909**
53910** Fields in this structure are accessed under the BtShared.mutex
53911** mutex, except for nRef and pNext which are accessed under the
53912** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
53913** may not be modified once it is initially set as long as nRef>0.
53914** The pSchema field may be set once under BtShared.mutex and
53915** thereafter is unchanged as long as nRef>0.
53916**
53917** isPending:
53918**
53919**   If a BtShared client fails to obtain a write-lock on a database
53920**   table (because there exists one or more read-locks on the table),
53921**   the shared-cache enters 'pending-lock' state and isPending is
53922**   set to true.
53923**
53924**   The shared-cache leaves the 'pending lock' state when either of
53925**   the following occur:
53926**
53927**     1) The current writer (BtShared.pWriter) concludes its transaction, OR
53928**     2) The number of locks held by other connections drops to zero.
53929**
53930**   while in the 'pending-lock' state, no connection may start a new
53931**   transaction.
53932**
53933**   This feature is included to help prevent writer-starvation.
53934*/
53935struct BtShared {
53936  Pager *pPager;        /* The page cache */
53937  sqlite3 *db;          /* Database connection currently using this Btree */
53938  BtCursor *pCursor;    /* A list of all open cursors */
53939  MemPage *pPage1;      /* First page of the database */
53940  u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
53941#ifndef SQLITE_OMIT_AUTOVACUUM
53942  u8 autoVacuum;        /* True if auto-vacuum is enabled */
53943  u8 incrVacuum;        /* True if incr-vacuum is enabled */
53944  u8 bDoTruncate;       /* True to truncate db on commit */
53945#endif
53946  u8 inTransaction;     /* Transaction state */
53947  u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
53948#ifdef SQLITE_HAS_CODEC
53949  u8 optimalReserve;    /* Desired amount of reserved space per page */
53950#endif
53951  u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
53952  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
53953  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
53954  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
53955  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
53956  u32 pageSize;         /* Total number of bytes on a page */
53957  u32 usableSize;       /* Number of usable bytes on each page */
53958  int nTransaction;     /* Number of open transactions (read + write) */
53959  u32 nPage;            /* Number of pages in the database */
53960  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
53961  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
53962  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
53963  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
53964#ifndef SQLITE_OMIT_SHARED_CACHE
53965  int nRef;             /* Number of references to this structure */
53966  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
53967  BtLock *pLock;        /* List of locks held on this shared-btree struct */
53968  Btree *pWriter;       /* Btree with currently open write transaction */
53969#endif
53970  u8 *pTmpSpace;        /* Temp space sufficient to hold a single cell */
53971};
53972
53973/*
53974** Allowed values for BtShared.btsFlags
53975*/
53976#define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
53977#define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
53978#define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
53979#define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
53980#define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
53981#define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
53982#define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
53983
53984/*
53985** An instance of the following structure is used to hold information
53986** about a cell.  The parseCellPtr() function fills in this structure
53987** based on information extract from the raw disk page.
53988*/
53989struct CellInfo {
53990  i64 nKey;      /* The key for INTKEY tables, or nPayload otherwise */
53991  u8 *pPayload;  /* Pointer to the start of payload */
53992  u32 nPayload;  /* Bytes of payload */
53993  u16 nLocal;    /* Amount of payload held locally, not on overflow */
53994  u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
53995  u16 nSize;     /* Size of the cell content on the main b-tree page */
53996};
53997
53998/*
53999** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
54000** this will be declared corrupt. This value is calculated based on a
54001** maximum database size of 2^31 pages a minimum fanout of 2 for a
54002** root-node and 3 for all other internal nodes.
54003**
54004** If a tree that appears to be taller than this is encountered, it is
54005** assumed that the database is corrupt.
54006*/
54007#define BTCURSOR_MAX_DEPTH 20
54008
54009/*
54010** A cursor is a pointer to a particular entry within a particular
54011** b-tree within a database file.
54012**
54013** The entry is identified by its MemPage and the index in
54014** MemPage.aCell[] of the entry.
54015**
54016** A single database file can be shared by two more database connections,
54017** but cursors cannot be shared.  Each cursor is associated with a
54018** particular database connection identified BtCursor.pBtree.db.
54019**
54020** Fields in this structure are accessed under the BtShared.mutex
54021** found at self->pBt->mutex.
54022**
54023** skipNext meaning:
54024**    eState==SKIPNEXT && skipNext>0:  Next sqlite3BtreeNext() is no-op.
54025**    eState==SKIPNEXT && skipNext<0:  Next sqlite3BtreePrevious() is no-op.
54026**    eState==FAULT:                   Cursor fault with skipNext as error code.
54027*/
54028struct BtCursor {
54029  Btree *pBtree;            /* The Btree to which this cursor belongs */
54030  BtShared *pBt;            /* The BtShared this cursor points to */
54031  BtCursor *pNext;          /* Forms a linked list of all cursors */
54032  Pgno *aOverflow;          /* Cache of overflow page locations */
54033  CellInfo info;            /* A parse of the cell we are pointing at */
54034  i64 nKey;                 /* Size of pKey, or last integer key */
54035  void *pKey;               /* Saved key that was cursor last known position */
54036  Pgno pgnoRoot;            /* The root page of this tree */
54037  int nOvflAlloc;           /* Allocated size of aOverflow[] array */
54038  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive.
54039                   ** Error code if eState==CURSOR_FAULT */
54040  u8 curFlags;              /* zero or more BTCF_* flags defined below */
54041  u8 curPagerFlags;         /* Flags to send to sqlite3PagerAcquire() */
54042  u8 eState;                /* One of the CURSOR_XXX constants (see below) */
54043  u8 hints;                 /* As configured by CursorSetHints() */
54044  /* All fields above are zeroed when the cursor is allocated.  See
54045  ** sqlite3BtreeCursorZero().  Fields that follow must be manually
54046  ** initialized. */
54047  i8 iPage;                 /* Index of current page in apPage */
54048  u8 curIntKey;             /* Value of apPage[0]->intKey */
54049  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
54050  void *padding1;           /* Make object size a multiple of 16 */
54051  u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
54052  MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
54053};
54054
54055/*
54056** Legal values for BtCursor.curFlags
54057*/
54058#define BTCF_WriteFlag    0x01   /* True if a write cursor */
54059#define BTCF_ValidNKey    0x02   /* True if info.nKey is valid */
54060#define BTCF_ValidOvfl    0x04   /* True if aOverflow is valid */
54061#define BTCF_AtLast       0x08   /* Cursor is pointing ot the last entry */
54062#define BTCF_Incrblob     0x10   /* True if an incremental I/O handle */
54063#define BTCF_Multiple     0x20   /* Maybe another cursor on the same btree */
54064
54065/*
54066** Potential values for BtCursor.eState.
54067**
54068** CURSOR_INVALID:
54069**   Cursor does not point to a valid entry. This can happen (for example)
54070**   because the table is empty or because BtreeCursorFirst() has not been
54071**   called.
54072**
54073** CURSOR_VALID:
54074**   Cursor points to a valid entry. getPayload() etc. may be called.
54075**
54076** CURSOR_SKIPNEXT:
54077**   Cursor is valid except that the Cursor.skipNext field is non-zero
54078**   indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
54079**   operation should be a no-op.
54080**
54081** CURSOR_REQUIRESEEK:
54082**   The table that this cursor was opened on still exists, but has been
54083**   modified since the cursor was last used. The cursor position is saved
54084**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
54085**   this state, restoreCursorPosition() can be called to attempt to
54086**   seek the cursor to the saved position.
54087**
54088** CURSOR_FAULT:
54089**   An unrecoverable error (an I/O error or a malloc failure) has occurred
54090**   on a different connection that shares the BtShared cache with this
54091**   cursor.  The error has left the cache in an inconsistent state.
54092**   Do nothing else with this cursor.  Any attempt to use the cursor
54093**   should return the error code stored in BtCursor.skipNext
54094*/
54095#define CURSOR_INVALID           0
54096#define CURSOR_VALID             1
54097#define CURSOR_SKIPNEXT          2
54098#define CURSOR_REQUIRESEEK       3
54099#define CURSOR_FAULT             4
54100
54101/*
54102** The database page the PENDING_BYTE occupies. This page is never used.
54103*/
54104# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
54105
54106/*
54107** These macros define the location of the pointer-map entry for a
54108** database page. The first argument to each is the number of usable
54109** bytes on each page of the database (often 1024). The second is the
54110** page number to look up in the pointer map.
54111**
54112** PTRMAP_PAGENO returns the database page number of the pointer-map
54113** page that stores the required pointer. PTRMAP_PTROFFSET returns
54114** the offset of the requested map entry.
54115**
54116** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
54117** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
54118** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
54119** this test.
54120*/
54121#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
54122#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
54123#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
54124
54125/*
54126** The pointer map is a lookup table that identifies the parent page for
54127** each child page in the database file.  The parent page is the page that
54128** contains a pointer to the child.  Every page in the database contains
54129** 0 or 1 parent pages.  (In this context 'database page' refers
54130** to any page that is not part of the pointer map itself.)  Each pointer map
54131** entry consists of a single byte 'type' and a 4 byte parent page number.
54132** The PTRMAP_XXX identifiers below are the valid types.
54133**
54134** The purpose of the pointer map is to facility moving pages from one
54135** position in the file to another as part of autovacuum.  When a page
54136** is moved, the pointer in its parent must be updated to point to the
54137** new location.  The pointer map is used to locate the parent page quickly.
54138**
54139** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
54140**                  used in this case.
54141**
54142** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
54143**                  is not used in this case.
54144**
54145** PTRMAP_OVERFLOW1: The database page is the first page in a list of
54146**                   overflow pages. The page number identifies the page that
54147**                   contains the cell with a pointer to this overflow page.
54148**
54149** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
54150**                   overflow pages. The page-number identifies the previous
54151**                   page in the overflow page list.
54152**
54153** PTRMAP_BTREE: The database page is a non-root btree page. The page number
54154**               identifies the parent page in the btree.
54155*/
54156#define PTRMAP_ROOTPAGE 1
54157#define PTRMAP_FREEPAGE 2
54158#define PTRMAP_OVERFLOW1 3
54159#define PTRMAP_OVERFLOW2 4
54160#define PTRMAP_BTREE 5
54161
54162/* A bunch of assert() statements to check the transaction state variables
54163** of handle p (type Btree*) are internally consistent.
54164*/
54165#define btreeIntegrity(p) \
54166  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
54167  assert( p->pBt->inTransaction>=p->inTrans );
54168
54169
54170/*
54171** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
54172** if the database supports auto-vacuum or not. Because it is used
54173** within an expression that is an argument to another macro
54174** (sqliteMallocRaw), it is not possible to use conditional compilation.
54175** So, this macro is defined instead.
54176*/
54177#ifndef SQLITE_OMIT_AUTOVACUUM
54178#define ISAUTOVACUUM (pBt->autoVacuum)
54179#else
54180#define ISAUTOVACUUM 0
54181#endif
54182
54183
54184/*
54185** This structure is passed around through all the sanity checking routines
54186** in order to keep track of some global state information.
54187**
54188** The aRef[] array is allocated so that there is 1 bit for each page in
54189** the database. As the integrity-check proceeds, for each page used in
54190** the database the corresponding bit is set. This allows integrity-check to
54191** detect pages that are used twice and orphaned pages (both of which
54192** indicate corruption).
54193*/
54194typedef struct IntegrityCk IntegrityCk;
54195struct IntegrityCk {
54196  BtShared *pBt;    /* The tree being checked out */
54197  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
54198  u8 *aPgRef;       /* 1 bit per page in the db (see above) */
54199  Pgno nPage;       /* Number of pages in the database */
54200  int mxErr;        /* Stop accumulating errors when this reaches zero */
54201  int nErr;         /* Number of messages written to zErrMsg so far */
54202  int mallocFailed; /* A memory allocation error has occurred */
54203  const char *zPfx; /* Error message prefix */
54204  int v1, v2;       /* Values for up to two %d fields in zPfx */
54205  StrAccum errMsg;  /* Accumulate the error message text here */
54206  u32 *heap;        /* Min-heap used for analyzing cell coverage */
54207};
54208
54209/*
54210** Routines to read or write a two- and four-byte big-endian integer values.
54211*/
54212#define get2byte(x)   ((x)[0]<<8 | (x)[1])
54213#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
54214#define get4byte sqlite3Get4byte
54215#define put4byte sqlite3Put4byte
54216
54217/*
54218** get2byteAligned(), unlike get2byte(), requires that its argument point to a
54219** two-byte aligned address.  get2bytea() is only used for accessing the
54220** cell addresses in a btree header.
54221*/
54222#if SQLITE_BYTEORDER==4321
54223# define get2byteAligned(x)  (*(u16*)(x))
54224#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
54225    && GCC_VERSION>=4008000
54226# define get2byteAligned(x)  __builtin_bswap16(*(u16*)(x))
54227#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
54228    && defined(_MSC_VER) && _MSC_VER>=1300
54229# define get2byteAligned(x)  _byteswap_ushort(*(u16*)(x))
54230#else
54231# define get2byteAligned(x)  ((x)[0]<<8 | (x)[1])
54232#endif
54233
54234/************** End of btreeInt.h ********************************************/
54235/************** Continuing where we left off in btmutex.c ********************/
54236#ifndef SQLITE_OMIT_SHARED_CACHE
54237#if SQLITE_THREADSAFE
54238
54239/*
54240** Obtain the BtShared mutex associated with B-Tree handle p. Also,
54241** set BtShared.db to the database handle associated with p and the
54242** p->locked boolean to true.
54243*/
54244static void lockBtreeMutex(Btree *p){
54245  assert( p->locked==0 );
54246  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
54247  assert( sqlite3_mutex_held(p->db->mutex) );
54248
54249  sqlite3_mutex_enter(p->pBt->mutex);
54250  p->pBt->db = p->db;
54251  p->locked = 1;
54252}
54253
54254/*
54255** Release the BtShared mutex associated with B-Tree handle p and
54256** clear the p->locked boolean.
54257*/
54258static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
54259  BtShared *pBt = p->pBt;
54260  assert( p->locked==1 );
54261  assert( sqlite3_mutex_held(pBt->mutex) );
54262  assert( sqlite3_mutex_held(p->db->mutex) );
54263  assert( p->db==pBt->db );
54264
54265  sqlite3_mutex_leave(pBt->mutex);
54266  p->locked = 0;
54267}
54268
54269/* Forward reference */
54270static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
54271
54272/*
54273** Enter a mutex on the given BTree object.
54274**
54275** If the object is not sharable, then no mutex is ever required
54276** and this routine is a no-op.  The underlying mutex is non-recursive.
54277** But we keep a reference count in Btree.wantToLock so the behavior
54278** of this interface is recursive.
54279**
54280** To avoid deadlocks, multiple Btrees are locked in the same order
54281** by all database connections.  The p->pNext is a list of other
54282** Btrees belonging to the same database connection as the p Btree
54283** which need to be locked after p.  If we cannot get a lock on
54284** p, then first unlock all of the others on p->pNext, then wait
54285** for the lock to become available on p, then relock all of the
54286** subsequent Btrees that desire a lock.
54287*/
54288SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
54289  /* Some basic sanity checking on the Btree.  The list of Btrees
54290  ** connected by pNext and pPrev should be in sorted order by
54291  ** Btree.pBt value. All elements of the list should belong to
54292  ** the same connection. Only shared Btrees are on the list. */
54293  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
54294  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
54295  assert( p->pNext==0 || p->pNext->db==p->db );
54296  assert( p->pPrev==0 || p->pPrev->db==p->db );
54297  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
54298
54299  /* Check for locking consistency */
54300  assert( !p->locked || p->wantToLock>0 );
54301  assert( p->sharable || p->wantToLock==0 );
54302
54303  /* We should already hold a lock on the database connection */
54304  assert( sqlite3_mutex_held(p->db->mutex) );
54305
54306  /* Unless the database is sharable and unlocked, then BtShared.db
54307  ** should already be set correctly. */
54308  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
54309
54310  if( !p->sharable ) return;
54311  p->wantToLock++;
54312  if( p->locked ) return;
54313  btreeLockCarefully(p);
54314}
54315
54316/* This is a helper function for sqlite3BtreeLock(). By moving
54317** complex, but seldom used logic, out of sqlite3BtreeLock() and
54318** into this routine, we avoid unnecessary stack pointer changes
54319** and thus help the sqlite3BtreeLock() routine to run much faster
54320** in the common case.
54321*/
54322static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
54323  Btree *pLater;
54324
54325  /* In most cases, we should be able to acquire the lock we
54326  ** want without having to go through the ascending lock
54327  ** procedure that follows.  Just be sure not to block.
54328  */
54329  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
54330    p->pBt->db = p->db;
54331    p->locked = 1;
54332    return;
54333  }
54334
54335  /* To avoid deadlock, first release all locks with a larger
54336  ** BtShared address.  Then acquire our lock.  Then reacquire
54337  ** the other BtShared locks that we used to hold in ascending
54338  ** order.
54339  */
54340  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
54341    assert( pLater->sharable );
54342    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
54343    assert( !pLater->locked || pLater->wantToLock>0 );
54344    if( pLater->locked ){
54345      unlockBtreeMutex(pLater);
54346    }
54347  }
54348  lockBtreeMutex(p);
54349  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
54350    if( pLater->wantToLock ){
54351      lockBtreeMutex(pLater);
54352    }
54353  }
54354}
54355
54356
54357/*
54358** Exit the recursive mutex on a Btree.
54359*/
54360SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
54361  assert( sqlite3_mutex_held(p->db->mutex) );
54362  if( p->sharable ){
54363    assert( p->wantToLock>0 );
54364    p->wantToLock--;
54365    if( p->wantToLock==0 ){
54366      unlockBtreeMutex(p);
54367    }
54368  }
54369}
54370
54371#ifndef NDEBUG
54372/*
54373** Return true if the BtShared mutex is held on the btree, or if the
54374** B-Tree is not marked as sharable.
54375**
54376** This routine is used only from within assert() statements.
54377*/
54378SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
54379  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
54380  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
54381  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
54382  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
54383
54384  return (p->sharable==0 || p->locked);
54385}
54386#endif
54387
54388
54389#ifndef SQLITE_OMIT_INCRBLOB
54390/*
54391** Enter and leave a mutex on a Btree given a cursor owned by that
54392** Btree.  These entry points are used by incremental I/O and can be
54393** omitted if that module is not used.
54394*/
54395SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
54396  sqlite3BtreeEnter(pCur->pBtree);
54397}
54398SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
54399  sqlite3BtreeLeave(pCur->pBtree);
54400}
54401#endif /* SQLITE_OMIT_INCRBLOB */
54402
54403
54404/*
54405** Enter the mutex on every Btree associated with a database
54406** connection.  This is needed (for example) prior to parsing
54407** a statement since we will be comparing table and column names
54408** against all schemas and we do not want those schemas being
54409** reset out from under us.
54410**
54411** There is a corresponding leave-all procedures.
54412**
54413** Enter the mutexes in accending order by BtShared pointer address
54414** to avoid the possibility of deadlock when two threads with
54415** two or more btrees in common both try to lock all their btrees
54416** at the same instant.
54417*/
54418SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
54419  int i;
54420  Btree *p;
54421  assert( sqlite3_mutex_held(db->mutex) );
54422  for(i=0; i<db->nDb; i++){
54423    p = db->aDb[i].pBt;
54424    if( p ) sqlite3BtreeEnter(p);
54425  }
54426}
54427SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
54428  int i;
54429  Btree *p;
54430  assert( sqlite3_mutex_held(db->mutex) );
54431  for(i=0; i<db->nDb; i++){
54432    p = db->aDb[i].pBt;
54433    if( p ) sqlite3BtreeLeave(p);
54434  }
54435}
54436
54437/*
54438** Return true if a particular Btree requires a lock.  Return FALSE if
54439** no lock is ever required since it is not sharable.
54440*/
54441SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
54442  return p->sharable;
54443}
54444
54445#ifndef NDEBUG
54446/*
54447** Return true if the current thread holds the database connection
54448** mutex and all required BtShared mutexes.
54449**
54450** This routine is used inside assert() statements only.
54451*/
54452SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
54453  int i;
54454  if( !sqlite3_mutex_held(db->mutex) ){
54455    return 0;
54456  }
54457  for(i=0; i<db->nDb; i++){
54458    Btree *p;
54459    p = db->aDb[i].pBt;
54460    if( p && p->sharable &&
54461         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
54462      return 0;
54463    }
54464  }
54465  return 1;
54466}
54467#endif /* NDEBUG */
54468
54469#ifndef NDEBUG
54470/*
54471** Return true if the correct mutexes are held for accessing the
54472** db->aDb[iDb].pSchema structure.  The mutexes required for schema
54473** access are:
54474**
54475**   (1) The mutex on db
54476**   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
54477**
54478** If pSchema is not NULL, then iDb is computed from pSchema and
54479** db using sqlite3SchemaToIndex().
54480*/
54481SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
54482  Btree *p;
54483  assert( db!=0 );
54484  if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
54485  assert( iDb>=0 && iDb<db->nDb );
54486  if( !sqlite3_mutex_held(db->mutex) ) return 0;
54487  if( iDb==1 ) return 1;
54488  p = db->aDb[iDb].pBt;
54489  assert( p!=0 );
54490  return p->sharable==0 || p->locked==1;
54491}
54492#endif /* NDEBUG */
54493
54494#else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
54495/*
54496** The following are special cases for mutex enter routines for use
54497** in single threaded applications that use shared cache.  Except for
54498** these two routines, all mutex operations are no-ops in that case and
54499** are null #defines in btree.h.
54500**
54501** If shared cache is disabled, then all btree mutex routines, including
54502** the ones below, are no-ops and are null #defines in btree.h.
54503*/
54504
54505SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
54506  p->pBt->db = p->db;
54507}
54508SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
54509  int i;
54510  for(i=0; i<db->nDb; i++){
54511    Btree *p = db->aDb[i].pBt;
54512    if( p ){
54513      p->pBt->db = p->db;
54514    }
54515  }
54516}
54517#endif /* if SQLITE_THREADSAFE */
54518#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
54519
54520/************** End of btmutex.c *********************************************/
54521/************** Begin file btree.c *******************************************/
54522/*
54523** 2004 April 6
54524**
54525** The author disclaims copyright to this source code.  In place of
54526** a legal notice, here is a blessing:
54527**
54528**    May you do good and not evil.
54529**    May you find forgiveness for yourself and forgive others.
54530**    May you share freely, never taking more than you give.
54531**
54532*************************************************************************
54533** This file implements an external (disk-based) database using BTrees.
54534** See the header comment on "btreeInt.h" for additional information.
54535** Including a description of file format and an overview of operation.
54536*/
54537/* #include "btreeInt.h" */
54538
54539/*
54540** The header string that appears at the beginning of every
54541** SQLite database.
54542*/
54543static const char zMagicHeader[] = SQLITE_FILE_HEADER;
54544
54545/*
54546** Set this global variable to 1 to enable tracing using the TRACE
54547** macro.
54548*/
54549#if 0
54550int sqlite3BtreeTrace=1;  /* True to enable tracing */
54551# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
54552#else
54553# define TRACE(X)
54554#endif
54555
54556/*
54557** Extract a 2-byte big-endian integer from an array of unsigned bytes.
54558** But if the value is zero, make it 65536.
54559**
54560** This routine is used to extract the "offset to cell content area" value
54561** from the header of a btree page.  If the page size is 65536 and the page
54562** is empty, the offset should be 65536, but the 2-byte value stores zero.
54563** This routine makes the necessary adjustment to 65536.
54564*/
54565#define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
54566
54567/*
54568** Values passed as the 5th argument to allocateBtreePage()
54569*/
54570#define BTALLOC_ANY   0           /* Allocate any page */
54571#define BTALLOC_EXACT 1           /* Allocate exact page if possible */
54572#define BTALLOC_LE    2           /* Allocate any page <= the parameter */
54573
54574/*
54575** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
54576** defined, or 0 if it is. For example:
54577**
54578**   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
54579*/
54580#ifndef SQLITE_OMIT_AUTOVACUUM
54581#define IfNotOmitAV(expr) (expr)
54582#else
54583#define IfNotOmitAV(expr) 0
54584#endif
54585
54586#ifndef SQLITE_OMIT_SHARED_CACHE
54587/*
54588** A list of BtShared objects that are eligible for participation
54589** in shared cache.  This variable has file scope during normal builds,
54590** but the test harness needs to access it so we make it global for
54591** test builds.
54592**
54593** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
54594*/
54595#ifdef SQLITE_TEST
54596SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
54597#else
54598static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
54599#endif
54600#endif /* SQLITE_OMIT_SHARED_CACHE */
54601
54602#ifndef SQLITE_OMIT_SHARED_CACHE
54603/*
54604** Enable or disable the shared pager and schema features.
54605**
54606** This routine has no effect on existing database connections.
54607** The shared cache setting effects only future calls to
54608** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
54609*/
54610SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int enable){
54611  sqlite3GlobalConfig.sharedCacheEnabled = enable;
54612  return SQLITE_OK;
54613}
54614#endif
54615
54616
54617
54618#ifdef SQLITE_OMIT_SHARED_CACHE
54619  /*
54620  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
54621  ** and clearAllSharedCacheTableLocks()
54622  ** manipulate entries in the BtShared.pLock linked list used to store
54623  ** shared-cache table level locks. If the library is compiled with the
54624  ** shared-cache feature disabled, then there is only ever one user
54625  ** of each BtShared structure and so this locking is not necessary.
54626  ** So define the lock related functions as no-ops.
54627  */
54628  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
54629  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
54630  #define clearAllSharedCacheTableLocks(a)
54631  #define downgradeAllSharedCacheTableLocks(a)
54632  #define hasSharedCacheTableLock(a,b,c,d) 1
54633  #define hasReadConflicts(a, b) 0
54634#endif
54635
54636#ifndef SQLITE_OMIT_SHARED_CACHE
54637
54638#ifdef SQLITE_DEBUG
54639/*
54640**** This function is only used as part of an assert() statement. ***
54641**
54642** Check to see if pBtree holds the required locks to read or write to the
54643** table with root page iRoot.   Return 1 if it does and 0 if not.
54644**
54645** For example, when writing to a table with root-page iRoot via
54646** Btree connection pBtree:
54647**
54648**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
54649**
54650** When writing to an index that resides in a sharable database, the
54651** caller should have first obtained a lock specifying the root page of
54652** the corresponding table. This makes things a bit more complicated,
54653** as this module treats each table as a separate structure. To determine
54654** the table corresponding to the index being written, this
54655** function has to search through the database schema.
54656**
54657** Instead of a lock on the table/index rooted at page iRoot, the caller may
54658** hold a write-lock on the schema table (root page 1). This is also
54659** acceptable.
54660*/
54661static int hasSharedCacheTableLock(
54662  Btree *pBtree,         /* Handle that must hold lock */
54663  Pgno iRoot,            /* Root page of b-tree */
54664  int isIndex,           /* True if iRoot is the root of an index b-tree */
54665  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
54666){
54667  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
54668  Pgno iTab = 0;
54669  BtLock *pLock;
54670
54671  /* If this database is not shareable, or if the client is reading
54672  ** and has the read-uncommitted flag set, then no lock is required.
54673  ** Return true immediately.
54674  */
54675  if( (pBtree->sharable==0)
54676   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
54677  ){
54678    return 1;
54679  }
54680
54681  /* If the client is reading  or writing an index and the schema is
54682  ** not loaded, then it is too difficult to actually check to see if
54683  ** the correct locks are held.  So do not bother - just return true.
54684  ** This case does not come up very often anyhow.
54685  */
54686  if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
54687    return 1;
54688  }
54689
54690  /* Figure out the root-page that the lock should be held on. For table
54691  ** b-trees, this is just the root page of the b-tree being read or
54692  ** written. For index b-trees, it is the root page of the associated
54693  ** table.  */
54694  if( isIndex ){
54695    HashElem *p;
54696    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
54697      Index *pIdx = (Index *)sqliteHashData(p);
54698      if( pIdx->tnum==(int)iRoot ){
54699        if( iTab ){
54700          /* Two or more indexes share the same root page.  There must
54701          ** be imposter tables.  So just return true.  The assert is not
54702          ** useful in that case. */
54703          return 1;
54704        }
54705        iTab = pIdx->pTable->tnum;
54706      }
54707    }
54708  }else{
54709    iTab = iRoot;
54710  }
54711
54712  /* Search for the required lock. Either a write-lock on root-page iTab, a
54713  ** write-lock on the schema table, or (if the client is reading) a
54714  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
54715  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
54716    if( pLock->pBtree==pBtree
54717     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
54718     && pLock->eLock>=eLockType
54719    ){
54720      return 1;
54721    }
54722  }
54723
54724  /* Failed to find the required lock. */
54725  return 0;
54726}
54727#endif /* SQLITE_DEBUG */
54728
54729#ifdef SQLITE_DEBUG
54730/*
54731**** This function may be used as part of assert() statements only. ****
54732**
54733** Return true if it would be illegal for pBtree to write into the
54734** table or index rooted at iRoot because other shared connections are
54735** simultaneously reading that same table or index.
54736**
54737** It is illegal for pBtree to write if some other Btree object that
54738** shares the same BtShared object is currently reading or writing
54739** the iRoot table.  Except, if the other Btree object has the
54740** read-uncommitted flag set, then it is OK for the other object to
54741** have a read cursor.
54742**
54743** For example, before writing to any part of the table or index
54744** rooted at page iRoot, one should call:
54745**
54746**    assert( !hasReadConflicts(pBtree, iRoot) );
54747*/
54748static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
54749  BtCursor *p;
54750  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
54751    if( p->pgnoRoot==iRoot
54752     && p->pBtree!=pBtree
54753     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
54754    ){
54755      return 1;
54756    }
54757  }
54758  return 0;
54759}
54760#endif    /* #ifdef SQLITE_DEBUG */
54761
54762/*
54763** Query to see if Btree handle p may obtain a lock of type eLock
54764** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
54765** SQLITE_OK if the lock may be obtained (by calling
54766** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
54767*/
54768static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
54769  BtShared *pBt = p->pBt;
54770  BtLock *pIter;
54771
54772  assert( sqlite3BtreeHoldsMutex(p) );
54773  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
54774  assert( p->db!=0 );
54775  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
54776
54777  /* If requesting a write-lock, then the Btree must have an open write
54778  ** transaction on this file. And, obviously, for this to be so there
54779  ** must be an open write transaction on the file itself.
54780  */
54781  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
54782  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
54783
54784  /* This routine is a no-op if the shared-cache is not enabled */
54785  if( !p->sharable ){
54786    return SQLITE_OK;
54787  }
54788
54789  /* If some other connection is holding an exclusive lock, the
54790  ** requested lock may not be obtained.
54791  */
54792  if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
54793    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
54794    return SQLITE_LOCKED_SHAREDCACHE;
54795  }
54796
54797  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
54798    /* The condition (pIter->eLock!=eLock) in the following if(...)
54799    ** statement is a simplification of:
54800    **
54801    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
54802    **
54803    ** since we know that if eLock==WRITE_LOCK, then no other connection
54804    ** may hold a WRITE_LOCK on any table in this file (since there can
54805    ** only be a single writer).
54806    */
54807    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
54808    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
54809    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
54810      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
54811      if( eLock==WRITE_LOCK ){
54812        assert( p==pBt->pWriter );
54813        pBt->btsFlags |= BTS_PENDING;
54814      }
54815      return SQLITE_LOCKED_SHAREDCACHE;
54816    }
54817  }
54818  return SQLITE_OK;
54819}
54820#endif /* !SQLITE_OMIT_SHARED_CACHE */
54821
54822#ifndef SQLITE_OMIT_SHARED_CACHE
54823/*
54824** Add a lock on the table with root-page iTable to the shared-btree used
54825** by Btree handle p. Parameter eLock must be either READ_LOCK or
54826** WRITE_LOCK.
54827**
54828** This function assumes the following:
54829**
54830**   (a) The specified Btree object p is connected to a sharable
54831**       database (one with the BtShared.sharable flag set), and
54832**
54833**   (b) No other Btree objects hold a lock that conflicts
54834**       with the requested lock (i.e. querySharedCacheTableLock() has
54835**       already been called and returned SQLITE_OK).
54836**
54837** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
54838** is returned if a malloc attempt fails.
54839*/
54840static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
54841  BtShared *pBt = p->pBt;
54842  BtLock *pLock = 0;
54843  BtLock *pIter;
54844
54845  assert( sqlite3BtreeHoldsMutex(p) );
54846  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
54847  assert( p->db!=0 );
54848
54849  /* A connection with the read-uncommitted flag set will never try to
54850  ** obtain a read-lock using this function. The only read-lock obtained
54851  ** by a connection in read-uncommitted mode is on the sqlite_master
54852  ** table, and that lock is obtained in BtreeBeginTrans().  */
54853  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
54854
54855  /* This function should only be called on a sharable b-tree after it
54856  ** has been determined that no other b-tree holds a conflicting lock.  */
54857  assert( p->sharable );
54858  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
54859
54860  /* First search the list for an existing lock on this table. */
54861  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
54862    if( pIter->iTable==iTable && pIter->pBtree==p ){
54863      pLock = pIter;
54864      break;
54865    }
54866  }
54867
54868  /* If the above search did not find a BtLock struct associating Btree p
54869  ** with table iTable, allocate one and link it into the list.
54870  */
54871  if( !pLock ){
54872    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
54873    if( !pLock ){
54874      return SQLITE_NOMEM;
54875    }
54876    pLock->iTable = iTable;
54877    pLock->pBtree = p;
54878    pLock->pNext = pBt->pLock;
54879    pBt->pLock = pLock;
54880  }
54881
54882  /* Set the BtLock.eLock variable to the maximum of the current lock
54883  ** and the requested lock. This means if a write-lock was already held
54884  ** and a read-lock requested, we don't incorrectly downgrade the lock.
54885  */
54886  assert( WRITE_LOCK>READ_LOCK );
54887  if( eLock>pLock->eLock ){
54888    pLock->eLock = eLock;
54889  }
54890
54891  return SQLITE_OK;
54892}
54893#endif /* !SQLITE_OMIT_SHARED_CACHE */
54894
54895#ifndef SQLITE_OMIT_SHARED_CACHE
54896/*
54897** Release all the table locks (locks obtained via calls to
54898** the setSharedCacheTableLock() procedure) held by Btree object p.
54899**
54900** This function assumes that Btree p has an open read or write
54901** transaction. If it does not, then the BTS_PENDING flag
54902** may be incorrectly cleared.
54903*/
54904static void clearAllSharedCacheTableLocks(Btree *p){
54905  BtShared *pBt = p->pBt;
54906  BtLock **ppIter = &pBt->pLock;
54907
54908  assert( sqlite3BtreeHoldsMutex(p) );
54909  assert( p->sharable || 0==*ppIter );
54910  assert( p->inTrans>0 );
54911
54912  while( *ppIter ){
54913    BtLock *pLock = *ppIter;
54914    assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
54915    assert( pLock->pBtree->inTrans>=pLock->eLock );
54916    if( pLock->pBtree==p ){
54917      *ppIter = pLock->pNext;
54918      assert( pLock->iTable!=1 || pLock==&p->lock );
54919      if( pLock->iTable!=1 ){
54920        sqlite3_free(pLock);
54921      }
54922    }else{
54923      ppIter = &pLock->pNext;
54924    }
54925  }
54926
54927  assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
54928  if( pBt->pWriter==p ){
54929    pBt->pWriter = 0;
54930    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
54931  }else if( pBt->nTransaction==2 ){
54932    /* This function is called when Btree p is concluding its
54933    ** transaction. If there currently exists a writer, and p is not
54934    ** that writer, then the number of locks held by connections other
54935    ** than the writer must be about to drop to zero. In this case
54936    ** set the BTS_PENDING flag to 0.
54937    **
54938    ** If there is not currently a writer, then BTS_PENDING must
54939    ** be zero already. So this next line is harmless in that case.
54940    */
54941    pBt->btsFlags &= ~BTS_PENDING;
54942  }
54943}
54944
54945/*
54946** This function changes all write-locks held by Btree p into read-locks.
54947*/
54948static void downgradeAllSharedCacheTableLocks(Btree *p){
54949  BtShared *pBt = p->pBt;
54950  if( pBt->pWriter==p ){
54951    BtLock *pLock;
54952    pBt->pWriter = 0;
54953    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
54954    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
54955      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
54956      pLock->eLock = READ_LOCK;
54957    }
54958  }
54959}
54960
54961#endif /* SQLITE_OMIT_SHARED_CACHE */
54962
54963static void releasePage(MemPage *pPage);  /* Forward reference */
54964
54965/*
54966***** This routine is used inside of assert() only ****
54967**
54968** Verify that the cursor holds the mutex on its BtShared
54969*/
54970#ifdef SQLITE_DEBUG
54971static int cursorHoldsMutex(BtCursor *p){
54972  return sqlite3_mutex_held(p->pBt->mutex);
54973}
54974#endif
54975
54976/*
54977** Invalidate the overflow cache of the cursor passed as the first argument.
54978** on the shared btree structure pBt.
54979*/
54980#define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
54981
54982/*
54983** Invalidate the overflow page-list cache for all cursors opened
54984** on the shared btree structure pBt.
54985*/
54986static void invalidateAllOverflowCache(BtShared *pBt){
54987  BtCursor *p;
54988  assert( sqlite3_mutex_held(pBt->mutex) );
54989  for(p=pBt->pCursor; p; p=p->pNext){
54990    invalidateOverflowCache(p);
54991  }
54992}
54993
54994#ifndef SQLITE_OMIT_INCRBLOB
54995/*
54996** This function is called before modifying the contents of a table
54997** to invalidate any incrblob cursors that are open on the
54998** row or one of the rows being modified.
54999**
55000** If argument isClearTable is true, then the entire contents of the
55001** table is about to be deleted. In this case invalidate all incrblob
55002** cursors open on any row within the table with root-page pgnoRoot.
55003**
55004** Otherwise, if argument isClearTable is false, then the row with
55005** rowid iRow is being replaced or deleted. In this case invalidate
55006** only those incrblob cursors open on that specific row.
55007*/
55008static void invalidateIncrblobCursors(
55009  Btree *pBtree,          /* The database file to check */
55010  i64 iRow,               /* The rowid that might be changing */
55011  int isClearTable        /* True if all rows are being deleted */
55012){
55013  BtCursor *p;
55014  if( pBtree->hasIncrblobCur==0 ) return;
55015  assert( sqlite3BtreeHoldsMutex(pBtree) );
55016  pBtree->hasIncrblobCur = 0;
55017  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
55018    if( (p->curFlags & BTCF_Incrblob)!=0 ){
55019      pBtree->hasIncrblobCur = 1;
55020      if( isClearTable || p->info.nKey==iRow ){
55021        p->eState = CURSOR_INVALID;
55022      }
55023    }
55024  }
55025}
55026
55027#else
55028  /* Stub function when INCRBLOB is omitted */
55029  #define invalidateIncrblobCursors(x,y,z)
55030#endif /* SQLITE_OMIT_INCRBLOB */
55031
55032/*
55033** Set bit pgno of the BtShared.pHasContent bitvec. This is called
55034** when a page that previously contained data becomes a free-list leaf
55035** page.
55036**
55037** The BtShared.pHasContent bitvec exists to work around an obscure
55038** bug caused by the interaction of two useful IO optimizations surrounding
55039** free-list leaf pages:
55040**
55041**   1) When all data is deleted from a page and the page becomes
55042**      a free-list leaf page, the page is not written to the database
55043**      (as free-list leaf pages contain no meaningful data). Sometimes
55044**      such a page is not even journalled (as it will not be modified,
55045**      why bother journalling it?).
55046**
55047**   2) When a free-list leaf page is reused, its content is not read
55048**      from the database or written to the journal file (why should it
55049**      be, if it is not at all meaningful?).
55050**
55051** By themselves, these optimizations work fine and provide a handy
55052** performance boost to bulk delete or insert operations. However, if
55053** a page is moved to the free-list and then reused within the same
55054** transaction, a problem comes up. If the page is not journalled when
55055** it is moved to the free-list and it is also not journalled when it
55056** is extracted from the free-list and reused, then the original data
55057** may be lost. In the event of a rollback, it may not be possible
55058** to restore the database to its original configuration.
55059**
55060** The solution is the BtShared.pHasContent bitvec. Whenever a page is
55061** moved to become a free-list leaf page, the corresponding bit is
55062** set in the bitvec. Whenever a leaf page is extracted from the free-list,
55063** optimization 2 above is omitted if the corresponding bit is already
55064** set in BtShared.pHasContent. The contents of the bitvec are cleared
55065** at the end of every transaction.
55066*/
55067static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
55068  int rc = SQLITE_OK;
55069  if( !pBt->pHasContent ){
55070    assert( pgno<=pBt->nPage );
55071    pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
55072    if( !pBt->pHasContent ){
55073      rc = SQLITE_NOMEM;
55074    }
55075  }
55076  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
55077    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
55078  }
55079  return rc;
55080}
55081
55082/*
55083** Query the BtShared.pHasContent vector.
55084**
55085** This function is called when a free-list leaf page is removed from the
55086** free-list for reuse. It returns false if it is safe to retrieve the
55087** page from the pager layer with the 'no-content' flag set. True otherwise.
55088*/
55089static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
55090  Bitvec *p = pBt->pHasContent;
55091  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
55092}
55093
55094/*
55095** Clear (destroy) the BtShared.pHasContent bitvec. This should be
55096** invoked at the conclusion of each write-transaction.
55097*/
55098static void btreeClearHasContent(BtShared *pBt){
55099  sqlite3BitvecDestroy(pBt->pHasContent);
55100  pBt->pHasContent = 0;
55101}
55102
55103/*
55104** Release all of the apPage[] pages for a cursor.
55105*/
55106static void btreeReleaseAllCursorPages(BtCursor *pCur){
55107  int i;
55108  for(i=0; i<=pCur->iPage; i++){
55109    releasePage(pCur->apPage[i]);
55110    pCur->apPage[i] = 0;
55111  }
55112  pCur->iPage = -1;
55113}
55114
55115/*
55116** The cursor passed as the only argument must point to a valid entry
55117** when this function is called (i.e. have eState==CURSOR_VALID). This
55118** function saves the current cursor key in variables pCur->nKey and
55119** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
55120** code otherwise.
55121**
55122** If the cursor is open on an intkey table, then the integer key
55123** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
55124** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
55125** set to point to a malloced buffer pCur->nKey bytes in size containing
55126** the key.
55127*/
55128static int saveCursorKey(BtCursor *pCur){
55129  int rc;
55130  assert( CURSOR_VALID==pCur->eState );
55131  assert( 0==pCur->pKey );
55132  assert( cursorHoldsMutex(pCur) );
55133
55134  rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
55135  assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
55136
55137  /* If this is an intKey table, then the above call to BtreeKeySize()
55138  ** stores the integer key in pCur->nKey. In this case this value is
55139  ** all that is required. Otherwise, if pCur is not open on an intKey
55140  ** table, then malloc space for and store the pCur->nKey bytes of key
55141  ** data.  */
55142  if( 0==pCur->curIntKey ){
55143    void *pKey = sqlite3Malloc( pCur->nKey );
55144    if( pKey ){
55145      rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
55146      if( rc==SQLITE_OK ){
55147        pCur->pKey = pKey;
55148      }else{
55149        sqlite3_free(pKey);
55150      }
55151    }else{
55152      rc = SQLITE_NOMEM;
55153    }
55154  }
55155  assert( !pCur->curIntKey || !pCur->pKey );
55156  return rc;
55157}
55158
55159/*
55160** Save the current cursor position in the variables BtCursor.nKey
55161** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
55162**
55163** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
55164** prior to calling this routine.
55165*/
55166static int saveCursorPosition(BtCursor *pCur){
55167  int rc;
55168
55169  assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
55170  assert( 0==pCur->pKey );
55171  assert( cursorHoldsMutex(pCur) );
55172
55173  if( pCur->eState==CURSOR_SKIPNEXT ){
55174    pCur->eState = CURSOR_VALID;
55175  }else{
55176    pCur->skipNext = 0;
55177  }
55178
55179  rc = saveCursorKey(pCur);
55180  if( rc==SQLITE_OK ){
55181    btreeReleaseAllCursorPages(pCur);
55182    pCur->eState = CURSOR_REQUIRESEEK;
55183  }
55184
55185  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
55186  return rc;
55187}
55188
55189/* Forward reference */
55190static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
55191
55192/*
55193** Save the positions of all cursors (except pExcept) that are open on
55194** the table with root-page iRoot.  "Saving the cursor position" means that
55195** the location in the btree is remembered in such a way that it can be
55196** moved back to the same spot after the btree has been modified.  This
55197** routine is called just before cursor pExcept is used to modify the
55198** table, for example in BtreeDelete() or BtreeInsert().
55199**
55200** If there are two or more cursors on the same btree, then all such
55201** cursors should have their BTCF_Multiple flag set.  The btreeCursor()
55202** routine enforces that rule.  This routine only needs to be called in
55203** the uncommon case when pExpect has the BTCF_Multiple flag set.
55204**
55205** If pExpect!=NULL and if no other cursors are found on the same root-page,
55206** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
55207** pointless call to this routine.
55208**
55209** Implementation note:  This routine merely checks to see if any cursors
55210** need to be saved.  It calls out to saveCursorsOnList() in the (unusual)
55211** event that cursors are in need to being saved.
55212*/
55213static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
55214  BtCursor *p;
55215  assert( sqlite3_mutex_held(pBt->mutex) );
55216  assert( pExcept==0 || pExcept->pBt==pBt );
55217  for(p=pBt->pCursor; p; p=p->pNext){
55218    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
55219  }
55220  if( p ) return saveCursorsOnList(p, iRoot, pExcept);
55221  if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
55222  return SQLITE_OK;
55223}
55224
55225/* This helper routine to saveAllCursors does the actual work of saving
55226** the cursors if and when a cursor is found that actually requires saving.
55227** The common case is that no cursors need to be saved, so this routine is
55228** broken out from its caller to avoid unnecessary stack pointer movement.
55229*/
55230static int SQLITE_NOINLINE saveCursorsOnList(
55231  BtCursor *p,         /* The first cursor that needs saving */
55232  Pgno iRoot,          /* Only save cursor with this iRoot. Save all if zero */
55233  BtCursor *pExcept    /* Do not save this cursor */
55234){
55235  do{
55236    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
55237      if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
55238        int rc = saveCursorPosition(p);
55239        if( SQLITE_OK!=rc ){
55240          return rc;
55241        }
55242      }else{
55243        testcase( p->iPage>0 );
55244        btreeReleaseAllCursorPages(p);
55245      }
55246    }
55247    p = p->pNext;
55248  }while( p );
55249  return SQLITE_OK;
55250}
55251
55252/*
55253** Clear the current cursor position.
55254*/
55255SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
55256  assert( cursorHoldsMutex(pCur) );
55257  sqlite3_free(pCur->pKey);
55258  pCur->pKey = 0;
55259  pCur->eState = CURSOR_INVALID;
55260}
55261
55262/*
55263** In this version of BtreeMoveto, pKey is a packed index record
55264** such as is generated by the OP_MakeRecord opcode.  Unpack the
55265** record and then call BtreeMovetoUnpacked() to do the work.
55266*/
55267static int btreeMoveto(
55268  BtCursor *pCur,     /* Cursor open on the btree to be searched */
55269  const void *pKey,   /* Packed key if the btree is an index */
55270  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
55271  int bias,           /* Bias search to the high end */
55272  int *pRes           /* Write search results here */
55273){
55274  int rc;                    /* Status code */
55275  UnpackedRecord *pIdxKey;   /* Unpacked index key */
55276  char aSpace[200];          /* Temp space for pIdxKey - to avoid a malloc */
55277  char *pFree = 0;
55278
55279  if( pKey ){
55280    assert( nKey==(i64)(int)nKey );
55281    pIdxKey = sqlite3VdbeAllocUnpackedRecord(
55282        pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
55283    );
55284    if( pIdxKey==0 ) return SQLITE_NOMEM;
55285    sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
55286    if( pIdxKey->nField==0 ){
55287      sqlite3DbFree(pCur->pKeyInfo->db, pFree);
55288      return SQLITE_CORRUPT_BKPT;
55289    }
55290  }else{
55291    pIdxKey = 0;
55292  }
55293  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
55294  if( pFree ){
55295    sqlite3DbFree(pCur->pKeyInfo->db, pFree);
55296  }
55297  return rc;
55298}
55299
55300/*
55301** Restore the cursor to the position it was in (or as close to as possible)
55302** when saveCursorPosition() was called. Note that this call deletes the
55303** saved position info stored by saveCursorPosition(), so there can be
55304** at most one effective restoreCursorPosition() call after each
55305** saveCursorPosition().
55306*/
55307static int btreeRestoreCursorPosition(BtCursor *pCur){
55308  int rc;
55309  int skipNext;
55310  assert( cursorHoldsMutex(pCur) );
55311  assert( pCur->eState>=CURSOR_REQUIRESEEK );
55312  if( pCur->eState==CURSOR_FAULT ){
55313    return pCur->skipNext;
55314  }
55315  pCur->eState = CURSOR_INVALID;
55316  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
55317  if( rc==SQLITE_OK ){
55318    sqlite3_free(pCur->pKey);
55319    pCur->pKey = 0;
55320    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
55321    pCur->skipNext |= skipNext;
55322    if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
55323      pCur->eState = CURSOR_SKIPNEXT;
55324    }
55325  }
55326  return rc;
55327}
55328
55329#define restoreCursorPosition(p) \
55330  (p->eState>=CURSOR_REQUIRESEEK ? \
55331         btreeRestoreCursorPosition(p) : \
55332         SQLITE_OK)
55333
55334/*
55335** Determine whether or not a cursor has moved from the position where
55336** it was last placed, or has been invalidated for any other reason.
55337** Cursors can move when the row they are pointing at is deleted out
55338** from under them, for example.  Cursor might also move if a btree
55339** is rebalanced.
55340**
55341** Calling this routine with a NULL cursor pointer returns false.
55342**
55343** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
55344** back to where it ought to be if this routine returns true.
55345*/
55346SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
55347  return pCur->eState!=CURSOR_VALID;
55348}
55349
55350/*
55351** This routine restores a cursor back to its original position after it
55352** has been moved by some outside activity (such as a btree rebalance or
55353** a row having been deleted out from under the cursor).
55354**
55355** On success, the *pDifferentRow parameter is false if the cursor is left
55356** pointing at exactly the same row.  *pDifferntRow is the row the cursor
55357** was pointing to has been deleted, forcing the cursor to point to some
55358** nearby row.
55359**
55360** This routine should only be called for a cursor that just returned
55361** TRUE from sqlite3BtreeCursorHasMoved().
55362*/
55363SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
55364  int rc;
55365
55366  assert( pCur!=0 );
55367  assert( pCur->eState!=CURSOR_VALID );
55368  rc = restoreCursorPosition(pCur);
55369  if( rc ){
55370    *pDifferentRow = 1;
55371    return rc;
55372  }
55373  if( pCur->eState!=CURSOR_VALID ){
55374    *pDifferentRow = 1;
55375  }else{
55376    assert( pCur->skipNext==0 );
55377    *pDifferentRow = 0;
55378  }
55379  return SQLITE_OK;
55380}
55381
55382#ifndef SQLITE_OMIT_AUTOVACUUM
55383/*
55384** Given a page number of a regular database page, return the page
55385** number for the pointer-map page that contains the entry for the
55386** input page number.
55387**
55388** Return 0 (not a valid page) for pgno==1 since there is
55389** no pointer map associated with page 1.  The integrity_check logic
55390** requires that ptrmapPageno(*,1)!=1.
55391*/
55392static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
55393  int nPagesPerMapPage;
55394  Pgno iPtrMap, ret;
55395  assert( sqlite3_mutex_held(pBt->mutex) );
55396  if( pgno<2 ) return 0;
55397  nPagesPerMapPage = (pBt->usableSize/5)+1;
55398  iPtrMap = (pgno-2)/nPagesPerMapPage;
55399  ret = (iPtrMap*nPagesPerMapPage) + 2;
55400  if( ret==PENDING_BYTE_PAGE(pBt) ){
55401    ret++;
55402  }
55403  return ret;
55404}
55405
55406/*
55407** Write an entry into the pointer map.
55408**
55409** This routine updates the pointer map entry for page number 'key'
55410** so that it maps to type 'eType' and parent page number 'pgno'.
55411**
55412** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
55413** a no-op.  If an error occurs, the appropriate error code is written
55414** into *pRC.
55415*/
55416static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
55417  DbPage *pDbPage;  /* The pointer map page */
55418  u8 *pPtrmap;      /* The pointer map data */
55419  Pgno iPtrmap;     /* The pointer map page number */
55420  int offset;       /* Offset in pointer map page */
55421  int rc;           /* Return code from subfunctions */
55422
55423  if( *pRC ) return;
55424
55425  assert( sqlite3_mutex_held(pBt->mutex) );
55426  /* The master-journal page number must never be used as a pointer map page */
55427  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
55428
55429  assert( pBt->autoVacuum );
55430  if( key==0 ){
55431    *pRC = SQLITE_CORRUPT_BKPT;
55432    return;
55433  }
55434  iPtrmap = PTRMAP_PAGENO(pBt, key);
55435  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
55436  if( rc!=SQLITE_OK ){
55437    *pRC = rc;
55438    return;
55439  }
55440  offset = PTRMAP_PTROFFSET(iPtrmap, key);
55441  if( offset<0 ){
55442    *pRC = SQLITE_CORRUPT_BKPT;
55443    goto ptrmap_exit;
55444  }
55445  assert( offset <= (int)pBt->usableSize-5 );
55446  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
55447
55448  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
55449    TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
55450    *pRC= rc = sqlite3PagerWrite(pDbPage);
55451    if( rc==SQLITE_OK ){
55452      pPtrmap[offset] = eType;
55453      put4byte(&pPtrmap[offset+1], parent);
55454    }
55455  }
55456
55457ptrmap_exit:
55458  sqlite3PagerUnref(pDbPage);
55459}
55460
55461/*
55462** Read an entry from the pointer map.
55463**
55464** This routine retrieves the pointer map entry for page 'key', writing
55465** the type and parent page number to *pEType and *pPgno respectively.
55466** An error code is returned if something goes wrong, otherwise SQLITE_OK.
55467*/
55468static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
55469  DbPage *pDbPage;   /* The pointer map page */
55470  int iPtrmap;       /* Pointer map page index */
55471  u8 *pPtrmap;       /* Pointer map page data */
55472  int offset;        /* Offset of entry in pointer map */
55473  int rc;
55474
55475  assert( sqlite3_mutex_held(pBt->mutex) );
55476
55477  iPtrmap = PTRMAP_PAGENO(pBt, key);
55478  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
55479  if( rc!=0 ){
55480    return rc;
55481  }
55482  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
55483
55484  offset = PTRMAP_PTROFFSET(iPtrmap, key);
55485  if( offset<0 ){
55486    sqlite3PagerUnref(pDbPage);
55487    return SQLITE_CORRUPT_BKPT;
55488  }
55489  assert( offset <= (int)pBt->usableSize-5 );
55490  assert( pEType!=0 );
55491  *pEType = pPtrmap[offset];
55492  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
55493
55494  sqlite3PagerUnref(pDbPage);
55495  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
55496  return SQLITE_OK;
55497}
55498
55499#else /* if defined SQLITE_OMIT_AUTOVACUUM */
55500  #define ptrmapPut(w,x,y,z,rc)
55501  #define ptrmapGet(w,x,y,z) SQLITE_OK
55502  #define ptrmapPutOvflPtr(x, y, rc)
55503#endif
55504
55505/*
55506** Given a btree page and a cell index (0 means the first cell on
55507** the page, 1 means the second cell, and so forth) return a pointer
55508** to the cell content.
55509**
55510** findCellPastPtr() does the same except it skips past the initial
55511** 4-byte child pointer found on interior pages, if there is one.
55512**
55513** This routine works only for pages that do not contain overflow cells.
55514*/
55515#define findCell(P,I) \
55516  ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
55517#define findCellPastPtr(P,I) \
55518  ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
55519
55520
55521/*
55522** This is common tail processing for btreeParseCellPtr() and
55523** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
55524** on a single B-tree page.  Make necessary adjustments to the CellInfo
55525** structure.
55526*/
55527static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
55528  MemPage *pPage,         /* Page containing the cell */
55529  u8 *pCell,              /* Pointer to the cell text. */
55530  CellInfo *pInfo         /* Fill in this structure */
55531){
55532  /* If the payload will not fit completely on the local page, we have
55533  ** to decide how much to store locally and how much to spill onto
55534  ** overflow pages.  The strategy is to minimize the amount of unused
55535  ** space on overflow pages while keeping the amount of local storage
55536  ** in between minLocal and maxLocal.
55537  **
55538  ** Warning:  changing the way overflow payload is distributed in any
55539  ** way will result in an incompatible file format.
55540  */
55541  int minLocal;  /* Minimum amount of payload held locally */
55542  int maxLocal;  /* Maximum amount of payload held locally */
55543  int surplus;   /* Overflow payload available for local storage */
55544
55545  minLocal = pPage->minLocal;
55546  maxLocal = pPage->maxLocal;
55547  surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
55548  testcase( surplus==maxLocal );
55549  testcase( surplus==maxLocal+1 );
55550  if( surplus <= maxLocal ){
55551    pInfo->nLocal = (u16)surplus;
55552  }else{
55553    pInfo->nLocal = (u16)minLocal;
55554  }
55555  pInfo->iOverflow = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell);
55556  pInfo->nSize = pInfo->iOverflow + 4;
55557}
55558
55559/*
55560** The following routines are implementations of the MemPage.xParseCell()
55561** method.
55562**
55563** Parse a cell content block and fill in the CellInfo structure.
55564**
55565** btreeParseCellPtr()        =>   table btree leaf nodes
55566** btreeParseCellNoPayload()  =>   table btree internal nodes
55567** btreeParseCellPtrIndex()   =>   index btree nodes
55568**
55569** There is also a wrapper function btreeParseCell() that works for
55570** all MemPage types and that references the cell by index rather than
55571** by pointer.
55572*/
55573static void btreeParseCellPtrNoPayload(
55574  MemPage *pPage,         /* Page containing the cell */
55575  u8 *pCell,              /* Pointer to the cell text. */
55576  CellInfo *pInfo         /* Fill in this structure */
55577){
55578  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55579  assert( pPage->leaf==0 );
55580  assert( pPage->noPayload );
55581  assert( pPage->childPtrSize==4 );
55582#ifndef SQLITE_DEBUG
55583  UNUSED_PARAMETER(pPage);
55584#endif
55585  pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
55586  pInfo->nPayload = 0;
55587  pInfo->nLocal = 0;
55588  pInfo->iOverflow = 0;
55589  pInfo->pPayload = 0;
55590  return;
55591}
55592static void btreeParseCellPtr(
55593  MemPage *pPage,         /* Page containing the cell */
55594  u8 *pCell,              /* Pointer to the cell text. */
55595  CellInfo *pInfo         /* Fill in this structure */
55596){
55597  u8 *pIter;              /* For scanning through pCell */
55598  u32 nPayload;           /* Number of bytes of cell payload */
55599  u64 iKey;               /* Extracted Key value */
55600
55601  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55602  assert( pPage->leaf==0 || pPage->leaf==1 );
55603  assert( pPage->intKeyLeaf || pPage->noPayload );
55604  assert( pPage->noPayload==0 );
55605  assert( pPage->intKeyLeaf );
55606  assert( pPage->childPtrSize==0 );
55607  pIter = pCell;
55608
55609  /* The next block of code is equivalent to:
55610  **
55611  **     pIter += getVarint32(pIter, nPayload);
55612  **
55613  ** The code is inlined to avoid a function call.
55614  */
55615  nPayload = *pIter;
55616  if( nPayload>=0x80 ){
55617    u8 *pEnd = &pIter[8];
55618    nPayload &= 0x7f;
55619    do{
55620      nPayload = (nPayload<<7) | (*++pIter & 0x7f);
55621    }while( (*pIter)>=0x80 && pIter<pEnd );
55622  }
55623  pIter++;
55624
55625  /* The next block of code is equivalent to:
55626  **
55627  **     pIter += getVarint(pIter, (u64*)&pInfo->nKey);
55628  **
55629  ** The code is inlined to avoid a function call.
55630  */
55631  iKey = *pIter;
55632  if( iKey>=0x80 ){
55633    u8 *pEnd = &pIter[7];
55634    iKey &= 0x7f;
55635    while(1){
55636      iKey = (iKey<<7) | (*++pIter & 0x7f);
55637      if( (*pIter)<0x80 ) break;
55638      if( pIter>=pEnd ){
55639        iKey = (iKey<<8) | *++pIter;
55640        break;
55641      }
55642    }
55643  }
55644  pIter++;
55645
55646  pInfo->nKey = *(i64*)&iKey;
55647  pInfo->nPayload = nPayload;
55648  pInfo->pPayload = pIter;
55649  testcase( nPayload==pPage->maxLocal );
55650  testcase( nPayload==pPage->maxLocal+1 );
55651  if( nPayload<=pPage->maxLocal ){
55652    /* This is the (easy) common case where the entire payload fits
55653    ** on the local page.  No overflow is required.
55654    */
55655    pInfo->nSize = nPayload + (u16)(pIter - pCell);
55656    if( pInfo->nSize<4 ) pInfo->nSize = 4;
55657    pInfo->nLocal = (u16)nPayload;
55658    pInfo->iOverflow = 0;
55659  }else{
55660    btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
55661  }
55662}
55663static void btreeParseCellPtrIndex(
55664  MemPage *pPage,         /* Page containing the cell */
55665  u8 *pCell,              /* Pointer to the cell text. */
55666  CellInfo *pInfo         /* Fill in this structure */
55667){
55668  u8 *pIter;              /* For scanning through pCell */
55669  u32 nPayload;           /* Number of bytes of cell payload */
55670
55671  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55672  assert( pPage->leaf==0 || pPage->leaf==1 );
55673  assert( pPage->intKeyLeaf==0 );
55674  assert( pPage->noPayload==0 );
55675  pIter = pCell + pPage->childPtrSize;
55676  nPayload = *pIter;
55677  if( nPayload>=0x80 ){
55678    u8 *pEnd = &pIter[8];
55679    nPayload &= 0x7f;
55680    do{
55681      nPayload = (nPayload<<7) | (*++pIter & 0x7f);
55682    }while( *(pIter)>=0x80 && pIter<pEnd );
55683  }
55684  pIter++;
55685  pInfo->nKey = nPayload;
55686  pInfo->nPayload = nPayload;
55687  pInfo->pPayload = pIter;
55688  testcase( nPayload==pPage->maxLocal );
55689  testcase( nPayload==pPage->maxLocal+1 );
55690  if( nPayload<=pPage->maxLocal ){
55691    /* This is the (easy) common case where the entire payload fits
55692    ** on the local page.  No overflow is required.
55693    */
55694    pInfo->nSize = nPayload + (u16)(pIter - pCell);
55695    if( pInfo->nSize<4 ) pInfo->nSize = 4;
55696    pInfo->nLocal = (u16)nPayload;
55697    pInfo->iOverflow = 0;
55698  }else{
55699    btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
55700  }
55701}
55702static void btreeParseCell(
55703  MemPage *pPage,         /* Page containing the cell */
55704  int iCell,              /* The cell index.  First cell is 0 */
55705  CellInfo *pInfo         /* Fill in this structure */
55706){
55707  pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
55708}
55709
55710/*
55711** The following routines are implementations of the MemPage.xCellSize
55712** method.
55713**
55714** Compute the total number of bytes that a Cell needs in the cell
55715** data area of the btree-page.  The return number includes the cell
55716** data header and the local payload, but not any overflow page or
55717** the space used by the cell pointer.
55718**
55719** cellSizePtrNoPayload()    =>   table internal nodes
55720** cellSizePtr()             =>   all index nodes & table leaf nodes
55721*/
55722static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
55723  u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
55724  u8 *pEnd;                                /* End mark for a varint */
55725  u32 nSize;                               /* Size value to return */
55726
55727#ifdef SQLITE_DEBUG
55728  /* The value returned by this function should always be the same as
55729  ** the (CellInfo.nSize) value found by doing a full parse of the
55730  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
55731  ** this function verifies that this invariant is not violated. */
55732  CellInfo debuginfo;
55733  pPage->xParseCell(pPage, pCell, &debuginfo);
55734#endif
55735
55736  assert( pPage->noPayload==0 );
55737  nSize = *pIter;
55738  if( nSize>=0x80 ){
55739    pEnd = &pIter[8];
55740    nSize &= 0x7f;
55741    do{
55742      nSize = (nSize<<7) | (*++pIter & 0x7f);
55743    }while( *(pIter)>=0x80 && pIter<pEnd );
55744  }
55745  pIter++;
55746  if( pPage->intKey ){
55747    /* pIter now points at the 64-bit integer key value, a variable length
55748    ** integer. The following block moves pIter to point at the first byte
55749    ** past the end of the key value. */
55750    pEnd = &pIter[9];
55751    while( (*pIter++)&0x80 && pIter<pEnd );
55752  }
55753  testcase( nSize==pPage->maxLocal );
55754  testcase( nSize==pPage->maxLocal+1 );
55755  if( nSize<=pPage->maxLocal ){
55756    nSize += (u32)(pIter - pCell);
55757    if( nSize<4 ) nSize = 4;
55758  }else{
55759    int minLocal = pPage->minLocal;
55760    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
55761    testcase( nSize==pPage->maxLocal );
55762    testcase( nSize==pPage->maxLocal+1 );
55763    if( nSize>pPage->maxLocal ){
55764      nSize = minLocal;
55765    }
55766    nSize += 4 + (u16)(pIter - pCell);
55767  }
55768  assert( nSize==debuginfo.nSize || CORRUPT_DB );
55769  return (u16)nSize;
55770}
55771static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
55772  u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
55773  u8 *pEnd;              /* End mark for a varint */
55774
55775#ifdef SQLITE_DEBUG
55776  /* The value returned by this function should always be the same as
55777  ** the (CellInfo.nSize) value found by doing a full parse of the
55778  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
55779  ** this function verifies that this invariant is not violated. */
55780  CellInfo debuginfo;
55781  pPage->xParseCell(pPage, pCell, &debuginfo);
55782#else
55783  UNUSED_PARAMETER(pPage);
55784#endif
55785
55786  assert( pPage->childPtrSize==4 );
55787  pEnd = pIter + 9;
55788  while( (*pIter++)&0x80 && pIter<pEnd );
55789  assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
55790  return (u16)(pIter - pCell);
55791}
55792
55793
55794#ifdef SQLITE_DEBUG
55795/* This variation on cellSizePtr() is used inside of assert() statements
55796** only. */
55797static u16 cellSize(MemPage *pPage, int iCell){
55798  return pPage->xCellSize(pPage, findCell(pPage, iCell));
55799}
55800#endif
55801
55802#ifndef SQLITE_OMIT_AUTOVACUUM
55803/*
55804** If the cell pCell, part of page pPage contains a pointer
55805** to an overflow page, insert an entry into the pointer-map
55806** for the overflow page.
55807*/
55808static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
55809  CellInfo info;
55810  if( *pRC ) return;
55811  assert( pCell!=0 );
55812  pPage->xParseCell(pPage, pCell, &info);
55813  if( info.iOverflow ){
55814    Pgno ovfl = get4byte(&pCell[info.iOverflow]);
55815    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
55816  }
55817}
55818#endif
55819
55820
55821/*
55822** Defragment the page given.  All Cells are moved to the
55823** end of the page and all free space is collected into one
55824** big FreeBlk that occurs in between the header and cell
55825** pointer array and the cell content area.
55826**
55827** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
55828** b-tree page so that there are no freeblocks or fragment bytes, all
55829** unused bytes are contained in the unallocated space region, and all
55830** cells are packed tightly at the end of the page.
55831*/
55832static int defragmentPage(MemPage *pPage){
55833  int i;                     /* Loop counter */
55834  int pc;                    /* Address of the i-th cell */
55835  int hdr;                   /* Offset to the page header */
55836  int size;                  /* Size of a cell */
55837  int usableSize;            /* Number of usable bytes on a page */
55838  int cellOffset;            /* Offset to the cell pointer array */
55839  int cbrk;                  /* Offset to the cell content area */
55840  int nCell;                 /* Number of cells on the page */
55841  unsigned char *data;       /* The page data */
55842  unsigned char *temp;       /* Temp area for cell content */
55843  unsigned char *src;        /* Source of content */
55844  int iCellFirst;            /* First allowable cell index */
55845  int iCellLast;             /* Last possible cell index */
55846
55847
55848  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55849  assert( pPage->pBt!=0 );
55850  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
55851  assert( pPage->nOverflow==0 );
55852  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55853  temp = 0;
55854  src = data = pPage->aData;
55855  hdr = pPage->hdrOffset;
55856  cellOffset = pPage->cellOffset;
55857  nCell = pPage->nCell;
55858  assert( nCell==get2byte(&data[hdr+3]) );
55859  usableSize = pPage->pBt->usableSize;
55860  cbrk = usableSize;
55861  iCellFirst = cellOffset + 2*nCell;
55862  iCellLast = usableSize - 4;
55863  for(i=0; i<nCell; i++){
55864    u8 *pAddr;     /* The i-th cell pointer */
55865    pAddr = &data[cellOffset + i*2];
55866    pc = get2byte(pAddr);
55867    testcase( pc==iCellFirst );
55868    testcase( pc==iCellLast );
55869    /* These conditions have already been verified in btreeInitPage()
55870    ** if PRAGMA cell_size_check=ON.
55871    */
55872    if( pc<iCellFirst || pc>iCellLast ){
55873      return SQLITE_CORRUPT_BKPT;
55874    }
55875    assert( pc>=iCellFirst && pc<=iCellLast );
55876    size = pPage->xCellSize(pPage, &src[pc]);
55877    cbrk -= size;
55878    if( cbrk<iCellFirst || pc+size>usableSize ){
55879      return SQLITE_CORRUPT_BKPT;
55880    }
55881    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
55882    testcase( cbrk+size==usableSize );
55883    testcase( pc+size==usableSize );
55884    put2byte(pAddr, cbrk);
55885    if( temp==0 ){
55886      int x;
55887      if( cbrk==pc ) continue;
55888      temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
55889      x = get2byte(&data[hdr+5]);
55890      memcpy(&temp[x], &data[x], (cbrk+size) - x);
55891      src = temp;
55892    }
55893    memcpy(&data[cbrk], &src[pc], size);
55894  }
55895  assert( cbrk>=iCellFirst );
55896  put2byte(&data[hdr+5], cbrk);
55897  data[hdr+1] = 0;
55898  data[hdr+2] = 0;
55899  data[hdr+7] = 0;
55900  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
55901  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55902  if( cbrk-iCellFirst!=pPage->nFree ){
55903    return SQLITE_CORRUPT_BKPT;
55904  }
55905  return SQLITE_OK;
55906}
55907
55908/*
55909** Search the free-list on page pPg for space to store a cell nByte bytes in
55910** size. If one can be found, return a pointer to the space and remove it
55911** from the free-list.
55912**
55913** If no suitable space can be found on the free-list, return NULL.
55914**
55915** This function may detect corruption within pPg.  If corruption is
55916** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
55917**
55918** Slots on the free list that are between 1 and 3 bytes larger than nByte
55919** will be ignored if adding the extra space to the fragmentation count
55920** causes the fragmentation count to exceed 60.
55921*/
55922static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
55923  const int hdr = pPg->hdrOffset;
55924  u8 * const aData = pPg->aData;
55925  int iAddr = hdr + 1;
55926  int pc = get2byte(&aData[iAddr]);
55927  int x;
55928  int usableSize = pPg->pBt->usableSize;
55929
55930  assert( pc>0 );
55931  do{
55932    int size;            /* Size of the free slot */
55933    /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
55934    ** increasing offset. */
55935    if( pc>usableSize-4 || pc<iAddr+4 ){
55936      *pRc = SQLITE_CORRUPT_BKPT;
55937      return 0;
55938    }
55939    /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
55940    ** freeblock form a big-endian integer which is the size of the freeblock
55941    ** in bytes, including the 4-byte header. */
55942    size = get2byte(&aData[pc+2]);
55943    if( (x = size - nByte)>=0 ){
55944      testcase( x==4 );
55945      testcase( x==3 );
55946      if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){
55947        *pRc = SQLITE_CORRUPT_BKPT;
55948        return 0;
55949      }else if( x<4 ){
55950        /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
55951        ** number of bytes in fragments may not exceed 60. */
55952        if( aData[hdr+7]>57 ) return 0;
55953
55954        /* Remove the slot from the free-list. Update the number of
55955        ** fragmented bytes within the page. */
55956        memcpy(&aData[iAddr], &aData[pc], 2);
55957        aData[hdr+7] += (u8)x;
55958      }else{
55959        /* The slot remains on the free-list. Reduce its size to account
55960         ** for the portion used by the new allocation. */
55961        put2byte(&aData[pc+2], x);
55962      }
55963      return &aData[pc + x];
55964    }
55965    iAddr = pc;
55966    pc = get2byte(&aData[pc]);
55967  }while( pc );
55968
55969  return 0;
55970}
55971
55972/*
55973** Allocate nByte bytes of space from within the B-Tree page passed
55974** as the first argument. Write into *pIdx the index into pPage->aData[]
55975** of the first byte of allocated space. Return either SQLITE_OK or
55976** an error code (usually SQLITE_CORRUPT).
55977**
55978** The caller guarantees that there is sufficient space to make the
55979** allocation.  This routine might need to defragment in order to bring
55980** all the space together, however.  This routine will avoid using
55981** the first two bytes past the cell pointer area since presumably this
55982** allocation is being made in order to insert a new cell, so we will
55983** also end up needing a new cell pointer.
55984*/
55985static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
55986  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
55987  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
55988  int top;                             /* First byte of cell content area */
55989  int rc = SQLITE_OK;                  /* Integer return code */
55990  int gap;        /* First byte of gap between cell pointers and cell content */
55991
55992  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55993  assert( pPage->pBt );
55994  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55995  assert( nByte>=0 );  /* Minimum cell size is 4 */
55996  assert( pPage->nFree>=nByte );
55997  assert( pPage->nOverflow==0 );
55998  assert( nByte < (int)(pPage->pBt->usableSize-8) );
55999
56000  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
56001  gap = pPage->cellOffset + 2*pPage->nCell;
56002  assert( gap<=65536 );
56003  /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
56004  ** and the reserved space is zero (the usual value for reserved space)
56005  ** then the cell content offset of an empty page wants to be 65536.
56006  ** However, that integer is too large to be stored in a 2-byte unsigned
56007  ** integer, so a value of 0 is used in its place. */
56008  top = get2byte(&data[hdr+5]);
56009  assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
56010  if( gap>top ){
56011    if( top==0 && pPage->pBt->usableSize==65536 ){
56012      top = 65536;
56013    }else{
56014      return SQLITE_CORRUPT_BKPT;
56015    }
56016  }
56017
56018  /* If there is enough space between gap and top for one more cell pointer
56019  ** array entry offset, and if the freelist is not empty, then search the
56020  ** freelist looking for a free slot big enough to satisfy the request.
56021  */
56022  testcase( gap+2==top );
56023  testcase( gap+1==top );
56024  testcase( gap==top );
56025  if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
56026    u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
56027    if( pSpace ){
56028      assert( pSpace>=data && (pSpace - data)<65536 );
56029      *pIdx = (int)(pSpace - data);
56030      return SQLITE_OK;
56031    }else if( rc ){
56032      return rc;
56033    }
56034  }
56035
56036  /* The request could not be fulfilled using a freelist slot.  Check
56037  ** to see if defragmentation is necessary.
56038  */
56039  testcase( gap+2+nByte==top );
56040  if( gap+2+nByte>top ){
56041    assert( pPage->nCell>0 || CORRUPT_DB );
56042    rc = defragmentPage(pPage);
56043    if( rc ) return rc;
56044    top = get2byteNotZero(&data[hdr+5]);
56045    assert( gap+nByte<=top );
56046  }
56047
56048
56049  /* Allocate memory from the gap in between the cell pointer array
56050  ** and the cell content area.  The btreeInitPage() call has already
56051  ** validated the freelist.  Given that the freelist is valid, there
56052  ** is no way that the allocation can extend off the end of the page.
56053  ** The assert() below verifies the previous sentence.
56054  */
56055  top -= nByte;
56056  put2byte(&data[hdr+5], top);
56057  assert( top+nByte <= (int)pPage->pBt->usableSize );
56058  *pIdx = top;
56059  return SQLITE_OK;
56060}
56061
56062/*
56063** Return a section of the pPage->aData to the freelist.
56064** The first byte of the new free block is pPage->aData[iStart]
56065** and the size of the block is iSize bytes.
56066**
56067** Adjacent freeblocks are coalesced.
56068**
56069** Note that even though the freeblock list was checked by btreeInitPage(),
56070** that routine will not detect overlap between cells or freeblocks.  Nor
56071** does it detect cells or freeblocks that encrouch into the reserved bytes
56072** at the end of the page.  So do additional corruption checks inside this
56073** routine and return SQLITE_CORRUPT if any problems are found.
56074*/
56075static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
56076  u16 iPtr;                             /* Address of ptr to next freeblock */
56077  u16 iFreeBlk;                         /* Address of the next freeblock */
56078  u8 hdr;                               /* Page header size.  0 or 100 */
56079  u8 nFrag = 0;                         /* Reduction in fragmentation */
56080  u16 iOrigSize = iSize;                /* Original value of iSize */
56081  u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
56082  u32 iEnd = iStart + iSize;            /* First byte past the iStart buffer */
56083  unsigned char *data = pPage->aData;   /* Page content */
56084
56085  assert( pPage->pBt!=0 );
56086  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
56087  assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
56088  assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
56089  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56090  assert( iSize>=4 );   /* Minimum cell size is 4 */
56091  assert( iStart<=iLast );
56092
56093  /* Overwrite deleted information with zeros when the secure_delete
56094  ** option is enabled */
56095  if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
56096    memset(&data[iStart], 0, iSize);
56097  }
56098
56099  /* The list of freeblocks must be in ascending order.  Find the
56100  ** spot on the list where iStart should be inserted.
56101  */
56102  hdr = pPage->hdrOffset;
56103  iPtr = hdr + 1;
56104  if( data[iPtr+1]==0 && data[iPtr]==0 ){
56105    iFreeBlk = 0;  /* Shortcut for the case when the freelist is empty */
56106  }else{
56107    while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
56108      if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
56109      iPtr = iFreeBlk;
56110    }
56111    if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
56112    assert( iFreeBlk>iPtr || iFreeBlk==0 );
56113
56114    /* At this point:
56115    **    iFreeBlk:   First freeblock after iStart, or zero if none
56116    **    iPtr:       The address of a pointer to iFreeBlk
56117    **
56118    ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
56119    */
56120    if( iFreeBlk && iEnd+3>=iFreeBlk ){
56121      nFrag = iFreeBlk - iEnd;
56122      if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
56123      iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
56124      if( iEnd > pPage->pBt->usableSize ) return SQLITE_CORRUPT_BKPT;
56125      iSize = iEnd - iStart;
56126      iFreeBlk = get2byte(&data[iFreeBlk]);
56127    }
56128
56129    /* If iPtr is another freeblock (that is, if iPtr is not the freelist
56130    ** pointer in the page header) then check to see if iStart should be
56131    ** coalesced onto the end of iPtr.
56132    */
56133    if( iPtr>hdr+1 ){
56134      int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
56135      if( iPtrEnd+3>=iStart ){
56136        if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
56137        nFrag += iStart - iPtrEnd;
56138        iSize = iEnd - iPtr;
56139        iStart = iPtr;
56140      }
56141    }
56142    if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
56143    data[hdr+7] -= nFrag;
56144  }
56145  if( iStart==get2byte(&data[hdr+5]) ){
56146    /* The new freeblock is at the beginning of the cell content area,
56147    ** so just extend the cell content area rather than create another
56148    ** freelist entry */
56149    if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
56150    put2byte(&data[hdr+1], iFreeBlk);
56151    put2byte(&data[hdr+5], iEnd);
56152  }else{
56153    /* Insert the new freeblock into the freelist */
56154    put2byte(&data[iPtr], iStart);
56155    put2byte(&data[iStart], iFreeBlk);
56156    put2byte(&data[iStart+2], iSize);
56157  }
56158  pPage->nFree += iOrigSize;
56159  return SQLITE_OK;
56160}
56161
56162/*
56163** Decode the flags byte (the first byte of the header) for a page
56164** and initialize fields of the MemPage structure accordingly.
56165**
56166** Only the following combinations are supported.  Anything different
56167** indicates a corrupt database files:
56168**
56169**         PTF_ZERODATA
56170**         PTF_ZERODATA | PTF_LEAF
56171**         PTF_LEAFDATA | PTF_INTKEY
56172**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
56173*/
56174static int decodeFlags(MemPage *pPage, int flagByte){
56175  BtShared *pBt;     /* A copy of pPage->pBt */
56176
56177  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
56178  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56179  pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
56180  flagByte &= ~PTF_LEAF;
56181  pPage->childPtrSize = 4-4*pPage->leaf;
56182  pPage->xCellSize = cellSizePtr;
56183  pBt = pPage->pBt;
56184  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
56185    /* EVIDENCE-OF: R-03640-13415 A value of 5 means the page is an interior
56186    ** table b-tree page. */
56187    assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
56188    /* EVIDENCE-OF: R-20501-61796 A value of 13 means the page is a leaf
56189    ** table b-tree page. */
56190    assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
56191    pPage->intKey = 1;
56192    if( pPage->leaf ){
56193      pPage->intKeyLeaf = 1;
56194      pPage->noPayload = 0;
56195      pPage->xParseCell = btreeParseCellPtr;
56196    }else{
56197      pPage->intKeyLeaf = 0;
56198      pPage->noPayload = 1;
56199      pPage->xCellSize = cellSizePtrNoPayload;
56200      pPage->xParseCell = btreeParseCellPtrNoPayload;
56201    }
56202    pPage->maxLocal = pBt->maxLeaf;
56203    pPage->minLocal = pBt->minLeaf;
56204  }else if( flagByte==PTF_ZERODATA ){
56205    /* EVIDENCE-OF: R-27225-53936 A value of 2 means the page is an interior
56206    ** index b-tree page. */
56207    assert( (PTF_ZERODATA)==2 );
56208    /* EVIDENCE-OF: R-16571-11615 A value of 10 means the page is a leaf
56209    ** index b-tree page. */
56210    assert( (PTF_ZERODATA|PTF_LEAF)==10 );
56211    pPage->intKey = 0;
56212    pPage->intKeyLeaf = 0;
56213    pPage->noPayload = 0;
56214    pPage->xParseCell = btreeParseCellPtrIndex;
56215    pPage->maxLocal = pBt->maxLocal;
56216    pPage->minLocal = pBt->minLocal;
56217  }else{
56218    /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
56219    ** an error. */
56220    return SQLITE_CORRUPT_BKPT;
56221  }
56222  pPage->max1bytePayload = pBt->max1bytePayload;
56223  return SQLITE_OK;
56224}
56225
56226/*
56227** Initialize the auxiliary information for a disk block.
56228**
56229** Return SQLITE_OK on success.  If we see that the page does
56230** not contain a well-formed database page, then return
56231** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
56232** guarantee that the page is well-formed.  It only shows that
56233** we failed to detect any corruption.
56234*/
56235static int btreeInitPage(MemPage *pPage){
56236
56237  assert( pPage->pBt!=0 );
56238  assert( pPage->pBt->db!=0 );
56239  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56240  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
56241  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
56242  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
56243
56244  if( !pPage->isInit ){
56245    u16 pc;            /* Address of a freeblock within pPage->aData[] */
56246    u8 hdr;            /* Offset to beginning of page header */
56247    u8 *data;          /* Equal to pPage->aData */
56248    BtShared *pBt;        /* The main btree structure */
56249    int usableSize;    /* Amount of usable space on each page */
56250    u16 cellOffset;    /* Offset from start of page to first cell pointer */
56251    int nFree;         /* Number of unused bytes on the page */
56252    int top;           /* First byte of the cell content area */
56253    int iCellFirst;    /* First allowable cell or freeblock offset */
56254    int iCellLast;     /* Last possible cell or freeblock offset */
56255
56256    pBt = pPage->pBt;
56257
56258    hdr = pPage->hdrOffset;
56259    data = pPage->aData;
56260    /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
56261    ** the b-tree page type. */
56262    if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
56263    assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
56264    pPage->maskPage = (u16)(pBt->pageSize - 1);
56265    pPage->nOverflow = 0;
56266    usableSize = pBt->usableSize;
56267    pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
56268    pPage->aDataEnd = &data[usableSize];
56269    pPage->aCellIdx = &data[cellOffset];
56270    pPage->aDataOfst = &data[pPage->childPtrSize];
56271    /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
56272    ** the start of the cell content area. A zero value for this integer is
56273    ** interpreted as 65536. */
56274    top = get2byteNotZero(&data[hdr+5]);
56275    /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
56276    ** number of cells on the page. */
56277    pPage->nCell = get2byte(&data[hdr+3]);
56278    if( pPage->nCell>MX_CELL(pBt) ){
56279      /* To many cells for a single page.  The page must be corrupt */
56280      return SQLITE_CORRUPT_BKPT;
56281    }
56282    testcase( pPage->nCell==MX_CELL(pBt) );
56283    /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
56284    ** possible for a root page of a table that contains no rows) then the
56285    ** offset to the cell content area will equal the page size minus the
56286    ** bytes of reserved space. */
56287    assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
56288
56289    /* A malformed database page might cause us to read past the end
56290    ** of page when parsing a cell.
56291    **
56292    ** The following block of code checks early to see if a cell extends
56293    ** past the end of a page boundary and causes SQLITE_CORRUPT to be
56294    ** returned if it does.
56295    */
56296    iCellFirst = cellOffset + 2*pPage->nCell;
56297    iCellLast = usableSize - 4;
56298    if( pBt->db->flags & SQLITE_CellSizeCk ){
56299      int i;            /* Index into the cell pointer array */
56300      int sz;           /* Size of a cell */
56301
56302      if( !pPage->leaf ) iCellLast--;
56303      for(i=0; i<pPage->nCell; i++){
56304        pc = get2byteAligned(&data[cellOffset+i*2]);
56305        testcase( pc==iCellFirst );
56306        testcase( pc==iCellLast );
56307        if( pc<iCellFirst || pc>iCellLast ){
56308          return SQLITE_CORRUPT_BKPT;
56309        }
56310        sz = pPage->xCellSize(pPage, &data[pc]);
56311        testcase( pc+sz==usableSize );
56312        if( pc+sz>usableSize ){
56313          return SQLITE_CORRUPT_BKPT;
56314        }
56315      }
56316      if( !pPage->leaf ) iCellLast++;
56317    }
56318
56319    /* Compute the total free space on the page
56320    ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
56321    ** start of the first freeblock on the page, or is zero if there are no
56322    ** freeblocks. */
56323    pc = get2byte(&data[hdr+1]);
56324    nFree = data[hdr+7] + top;  /* Init nFree to non-freeblock free space */
56325    while( pc>0 ){
56326      u16 next, size;
56327      if( pc<iCellFirst || pc>iCellLast ){
56328        /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
56329        ** always be at least one cell before the first freeblock.
56330        **
56331        ** Or, the freeblock is off the end of the page
56332        */
56333        return SQLITE_CORRUPT_BKPT;
56334      }
56335      next = get2byte(&data[pc]);
56336      size = get2byte(&data[pc+2]);
56337      if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
56338        /* Free blocks must be in ascending order. And the last byte of
56339        ** the free-block must lie on the database page.  */
56340        return SQLITE_CORRUPT_BKPT;
56341      }
56342      nFree = nFree + size;
56343      pc = next;
56344    }
56345
56346    /* At this point, nFree contains the sum of the offset to the start
56347    ** of the cell-content area plus the number of free bytes within
56348    ** the cell-content area. If this is greater than the usable-size
56349    ** of the page, then the page must be corrupted. This check also
56350    ** serves to verify that the offset to the start of the cell-content
56351    ** area, according to the page header, lies within the page.
56352    */
56353    if( nFree>usableSize ){
56354      return SQLITE_CORRUPT_BKPT;
56355    }
56356    pPage->nFree = (u16)(nFree - iCellFirst);
56357    pPage->isInit = 1;
56358  }
56359  return SQLITE_OK;
56360}
56361
56362/*
56363** Set up a raw page so that it looks like a database page holding
56364** no entries.
56365*/
56366static void zeroPage(MemPage *pPage, int flags){
56367  unsigned char *data = pPage->aData;
56368  BtShared *pBt = pPage->pBt;
56369  u8 hdr = pPage->hdrOffset;
56370  u16 first;
56371
56372  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
56373  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
56374  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
56375  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
56376  assert( sqlite3_mutex_held(pBt->mutex) );
56377  if( pBt->btsFlags & BTS_SECURE_DELETE ){
56378    memset(&data[hdr], 0, pBt->usableSize - hdr);
56379  }
56380  data[hdr] = (char)flags;
56381  first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
56382  memset(&data[hdr+1], 0, 4);
56383  data[hdr+7] = 0;
56384  put2byte(&data[hdr+5], pBt->usableSize);
56385  pPage->nFree = (u16)(pBt->usableSize - first);
56386  decodeFlags(pPage, flags);
56387  pPage->cellOffset = first;
56388  pPage->aDataEnd = &data[pBt->usableSize];
56389  pPage->aCellIdx = &data[first];
56390  pPage->aDataOfst = &data[pPage->childPtrSize];
56391  pPage->nOverflow = 0;
56392  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
56393  pPage->maskPage = (u16)(pBt->pageSize - 1);
56394  pPage->nCell = 0;
56395  pPage->isInit = 1;
56396}
56397
56398
56399/*
56400** Convert a DbPage obtained from the pager into a MemPage used by
56401** the btree layer.
56402*/
56403static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
56404  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
56405  pPage->aData = sqlite3PagerGetData(pDbPage);
56406  pPage->pDbPage = pDbPage;
56407  pPage->pBt = pBt;
56408  pPage->pgno = pgno;
56409  pPage->hdrOffset = pgno==1 ? 100 : 0;
56410  return pPage;
56411}
56412
56413/*
56414** Get a page from the pager.  Initialize the MemPage.pBt and
56415** MemPage.aData elements if needed.  See also: btreeGetUnusedPage().
56416**
56417** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
56418** about the content of the page at this time.  So do not go to the disk
56419** to fetch the content.  Just fill in the content with zeros for now.
56420** If in the future we call sqlite3PagerWrite() on this page, that
56421** means we have started to be concerned about content and the disk
56422** read should occur at that point.
56423*/
56424static int btreeGetPage(
56425  BtShared *pBt,       /* The btree */
56426  Pgno pgno,           /* Number of the page to fetch */
56427  MemPage **ppPage,    /* Return the page in this parameter */
56428  int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
56429){
56430  int rc;
56431  DbPage *pDbPage;
56432
56433  assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
56434  assert( sqlite3_mutex_held(pBt->mutex) );
56435  rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
56436  if( rc ) return rc;
56437  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
56438  return SQLITE_OK;
56439}
56440
56441/*
56442** Retrieve a page from the pager cache. If the requested page is not
56443** already in the pager cache return NULL. Initialize the MemPage.pBt and
56444** MemPage.aData elements if needed.
56445*/
56446static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
56447  DbPage *pDbPage;
56448  assert( sqlite3_mutex_held(pBt->mutex) );
56449  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
56450  if( pDbPage ){
56451    return btreePageFromDbPage(pDbPage, pgno, pBt);
56452  }
56453  return 0;
56454}
56455
56456/*
56457** Return the size of the database file in pages. If there is any kind of
56458** error, return ((unsigned int)-1).
56459*/
56460static Pgno btreePagecount(BtShared *pBt){
56461  return pBt->nPage;
56462}
56463SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
56464  assert( sqlite3BtreeHoldsMutex(p) );
56465  assert( ((p->pBt->nPage)&0x8000000)==0 );
56466  return btreePagecount(p->pBt);
56467}
56468
56469/*
56470** Get a page from the pager and initialize it.
56471**
56472** If pCur!=0 then the page is being fetched as part of a moveToChild()
56473** call.  Do additional sanity checking on the page in this case.
56474** And if the fetch fails, this routine must decrement pCur->iPage.
56475**
56476** The page is fetched as read-write unless pCur is not NULL and is
56477** a read-only cursor.
56478**
56479** If an error occurs, then *ppPage is undefined. It
56480** may remain unchanged, or it may be set to an invalid value.
56481*/
56482static int getAndInitPage(
56483  BtShared *pBt,                  /* The database file */
56484  Pgno pgno,                      /* Number of the page to get */
56485  MemPage **ppPage,               /* Write the page pointer here */
56486  BtCursor *pCur,                 /* Cursor to receive the page, or NULL */
56487  int bReadOnly                   /* True for a read-only page */
56488){
56489  int rc;
56490  DbPage *pDbPage;
56491  assert( sqlite3_mutex_held(pBt->mutex) );
56492  assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] );
56493  assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
56494  assert( pCur==0 || pCur->iPage>0 );
56495
56496  if( pgno>btreePagecount(pBt) ){
56497    rc = SQLITE_CORRUPT_BKPT;
56498    goto getAndInitPage_error;
56499  }
56500  rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
56501  if( rc ){
56502    goto getAndInitPage_error;
56503  }
56504  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
56505  if( (*ppPage)->isInit==0 ){
56506    rc = btreeInitPage(*ppPage);
56507    if( rc!=SQLITE_OK ){
56508      releasePage(*ppPage);
56509      goto getAndInitPage_error;
56510    }
56511  }
56512
56513  /* If obtaining a child page for a cursor, we must verify that the page is
56514  ** compatible with the root page. */
56515  if( pCur
56516   && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey)
56517  ){
56518    rc = SQLITE_CORRUPT_BKPT;
56519    releasePage(*ppPage);
56520    goto getAndInitPage_error;
56521  }
56522  return SQLITE_OK;
56523
56524getAndInitPage_error:
56525  if( pCur ) pCur->iPage--;
56526  testcase( pgno==0 );
56527  assert( pgno!=0 || rc==SQLITE_CORRUPT );
56528  return rc;
56529}
56530
56531/*
56532** Release a MemPage.  This should be called once for each prior
56533** call to btreeGetPage.
56534*/
56535static void releasePageNotNull(MemPage *pPage){
56536  assert( pPage->aData );
56537  assert( pPage->pBt );
56538  assert( pPage->pDbPage!=0 );
56539  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
56540  assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
56541  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56542  sqlite3PagerUnrefNotNull(pPage->pDbPage);
56543}
56544static void releasePage(MemPage *pPage){
56545  if( pPage ) releasePageNotNull(pPage);
56546}
56547
56548/*
56549** Get an unused page.
56550**
56551** This works just like btreeGetPage() with the addition:
56552**
56553**   *  If the page is already in use for some other purpose, immediately
56554**      release it and return an SQLITE_CURRUPT error.
56555**   *  Make sure the isInit flag is clear
56556*/
56557static int btreeGetUnusedPage(
56558  BtShared *pBt,       /* The btree */
56559  Pgno pgno,           /* Number of the page to fetch */
56560  MemPage **ppPage,    /* Return the page in this parameter */
56561  int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
56562){
56563  int rc = btreeGetPage(pBt, pgno, ppPage, flags);
56564  if( rc==SQLITE_OK ){
56565    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
56566      releasePage(*ppPage);
56567      *ppPage = 0;
56568      return SQLITE_CORRUPT_BKPT;
56569    }
56570    (*ppPage)->isInit = 0;
56571  }else{
56572    *ppPage = 0;
56573  }
56574  return rc;
56575}
56576
56577
56578/*
56579** During a rollback, when the pager reloads information into the cache
56580** so that the cache is restored to its original state at the start of
56581** the transaction, for each page restored this routine is called.
56582**
56583** This routine needs to reset the extra data section at the end of the
56584** page to agree with the restored data.
56585*/
56586static void pageReinit(DbPage *pData){
56587  MemPage *pPage;
56588  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
56589  assert( sqlite3PagerPageRefcount(pData)>0 );
56590  if( pPage->isInit ){
56591    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56592    pPage->isInit = 0;
56593    if( sqlite3PagerPageRefcount(pData)>1 ){
56594      /* pPage might not be a btree page;  it might be an overflow page
56595      ** or ptrmap page or a free page.  In those cases, the following
56596      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
56597      ** But no harm is done by this.  And it is very important that
56598      ** btreeInitPage() be called on every btree page so we make
56599      ** the call for every page that comes in for re-initing. */
56600      btreeInitPage(pPage);
56601    }
56602  }
56603}
56604
56605/*
56606** Invoke the busy handler for a btree.
56607*/
56608static int btreeInvokeBusyHandler(void *pArg){
56609  BtShared *pBt = (BtShared*)pArg;
56610  assert( pBt->db );
56611  assert( sqlite3_mutex_held(pBt->db->mutex) );
56612  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
56613}
56614
56615/*
56616** Open a database file.
56617**
56618** zFilename is the name of the database file.  If zFilename is NULL
56619** then an ephemeral database is created.  The ephemeral database might
56620** be exclusively in memory, or it might use a disk-based memory cache.
56621** Either way, the ephemeral database will be automatically deleted
56622** when sqlite3BtreeClose() is called.
56623**
56624** If zFilename is ":memory:" then an in-memory database is created
56625** that is automatically destroyed when it is closed.
56626**
56627** The "flags" parameter is a bitmask that might contain bits like
56628** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
56629**
56630** If the database is already opened in the same database connection
56631** and we are in shared cache mode, then the open will fail with an
56632** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
56633** objects in the same database connection since doing so will lead
56634** to problems with locking.
56635*/
56636SQLITE_PRIVATE int sqlite3BtreeOpen(
56637  sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
56638  const char *zFilename,  /* Name of the file containing the BTree database */
56639  sqlite3 *db,            /* Associated database handle */
56640  Btree **ppBtree,        /* Pointer to new Btree object written here */
56641  int flags,              /* Options */
56642  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
56643){
56644  BtShared *pBt = 0;             /* Shared part of btree structure */
56645  Btree *p;                      /* Handle to return */
56646  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
56647  int rc = SQLITE_OK;            /* Result code from this function */
56648  u8 nReserve;                   /* Byte of unused space on each page */
56649  unsigned char zDbHeader[100];  /* Database header content */
56650
56651  /* True if opening an ephemeral, temporary database */
56652  const int isTempDb = zFilename==0 || zFilename[0]==0;
56653
56654  /* Set the variable isMemdb to true for an in-memory database, or
56655  ** false for a file-based database.
56656  */
56657#ifdef SQLITE_OMIT_MEMORYDB
56658  const int isMemdb = 0;
56659#else
56660  const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
56661                       || (isTempDb && sqlite3TempInMemory(db))
56662                       || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
56663#endif
56664
56665  assert( db!=0 );
56666  assert( pVfs!=0 );
56667  assert( sqlite3_mutex_held(db->mutex) );
56668  assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
56669
56670  /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
56671  assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
56672
56673  /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
56674  assert( (flags & BTREE_SINGLE)==0 || isTempDb );
56675
56676  if( isMemdb ){
56677    flags |= BTREE_MEMORY;
56678  }
56679  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
56680    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
56681  }
56682  p = sqlite3MallocZero(sizeof(Btree));
56683  if( !p ){
56684    return SQLITE_NOMEM;
56685  }
56686  p->inTrans = TRANS_NONE;
56687  p->db = db;
56688#ifndef SQLITE_OMIT_SHARED_CACHE
56689  p->lock.pBtree = p;
56690  p->lock.iTable = 1;
56691#endif
56692
56693#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
56694  /*
56695  ** If this Btree is a candidate for shared cache, try to find an
56696  ** existing BtShared object that we can share with
56697  */
56698  if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
56699    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
56700      int nFilename = sqlite3Strlen30(zFilename)+1;
56701      int nFullPathname = pVfs->mxPathname+1;
56702      char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
56703      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
56704
56705      p->sharable = 1;
56706      if( !zFullPathname ){
56707        sqlite3_free(p);
56708        return SQLITE_NOMEM;
56709      }
56710      if( isMemdb ){
56711        memcpy(zFullPathname, zFilename, nFilename);
56712      }else{
56713        rc = sqlite3OsFullPathname(pVfs, zFilename,
56714                                   nFullPathname, zFullPathname);
56715        if( rc ){
56716          sqlite3_free(zFullPathname);
56717          sqlite3_free(p);
56718          return rc;
56719        }
56720      }
56721#if SQLITE_THREADSAFE
56722      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
56723      sqlite3_mutex_enter(mutexOpen);
56724      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
56725      sqlite3_mutex_enter(mutexShared);
56726#endif
56727      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
56728        assert( pBt->nRef>0 );
56729        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
56730                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
56731          int iDb;
56732          for(iDb=db->nDb-1; iDb>=0; iDb--){
56733            Btree *pExisting = db->aDb[iDb].pBt;
56734            if( pExisting && pExisting->pBt==pBt ){
56735              sqlite3_mutex_leave(mutexShared);
56736              sqlite3_mutex_leave(mutexOpen);
56737              sqlite3_free(zFullPathname);
56738              sqlite3_free(p);
56739              return SQLITE_CONSTRAINT;
56740            }
56741          }
56742          p->pBt = pBt;
56743          pBt->nRef++;
56744          break;
56745        }
56746      }
56747      sqlite3_mutex_leave(mutexShared);
56748      sqlite3_free(zFullPathname);
56749    }
56750#ifdef SQLITE_DEBUG
56751    else{
56752      /* In debug mode, we mark all persistent databases as sharable
56753      ** even when they are not.  This exercises the locking code and
56754      ** gives more opportunity for asserts(sqlite3_mutex_held())
56755      ** statements to find locking problems.
56756      */
56757      p->sharable = 1;
56758    }
56759#endif
56760  }
56761#endif
56762  if( pBt==0 ){
56763    /*
56764    ** The following asserts make sure that structures used by the btree are
56765    ** the right size.  This is to guard against size changes that result
56766    ** when compiling on a different architecture.
56767    */
56768    assert( sizeof(i64)==8 );
56769    assert( sizeof(u64)==8 );
56770    assert( sizeof(u32)==4 );
56771    assert( sizeof(u16)==2 );
56772    assert( sizeof(Pgno)==4 );
56773
56774    pBt = sqlite3MallocZero( sizeof(*pBt) );
56775    if( pBt==0 ){
56776      rc = SQLITE_NOMEM;
56777      goto btree_open_out;
56778    }
56779    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
56780                          EXTRA_SIZE, flags, vfsFlags, pageReinit);
56781    if( rc==SQLITE_OK ){
56782      sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
56783      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
56784    }
56785    if( rc!=SQLITE_OK ){
56786      goto btree_open_out;
56787    }
56788    pBt->openFlags = (u8)flags;
56789    pBt->db = db;
56790    sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
56791    p->pBt = pBt;
56792
56793    pBt->pCursor = 0;
56794    pBt->pPage1 = 0;
56795    if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
56796#ifdef SQLITE_SECURE_DELETE
56797    pBt->btsFlags |= BTS_SECURE_DELETE;
56798#endif
56799    /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
56800    ** determined by the 2-byte integer located at an offset of 16 bytes from
56801    ** the beginning of the database file. */
56802    pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
56803    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
56804         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
56805      pBt->pageSize = 0;
56806#ifndef SQLITE_OMIT_AUTOVACUUM
56807      /* If the magic name ":memory:" will create an in-memory database, then
56808      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
56809      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
56810      ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
56811      ** regular file-name. In this case the auto-vacuum applies as per normal.
56812      */
56813      if( zFilename && !isMemdb ){
56814        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
56815        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
56816      }
56817#endif
56818      nReserve = 0;
56819    }else{
56820      /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
56821      ** determined by the one-byte unsigned integer found at an offset of 20
56822      ** into the database file header. */
56823      nReserve = zDbHeader[20];
56824      pBt->btsFlags |= BTS_PAGESIZE_FIXED;
56825#ifndef SQLITE_OMIT_AUTOVACUUM
56826      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
56827      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
56828#endif
56829    }
56830    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
56831    if( rc ) goto btree_open_out;
56832    pBt->usableSize = pBt->pageSize - nReserve;
56833    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
56834
56835#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
56836    /* Add the new BtShared object to the linked list sharable BtShareds.
56837    */
56838    if( p->sharable ){
56839      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
56840      pBt->nRef = 1;
56841      MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
56842      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
56843        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
56844        if( pBt->mutex==0 ){
56845          rc = SQLITE_NOMEM;
56846          db->mallocFailed = 0;
56847          goto btree_open_out;
56848        }
56849      }
56850      sqlite3_mutex_enter(mutexShared);
56851      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
56852      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
56853      sqlite3_mutex_leave(mutexShared);
56854    }
56855#endif
56856  }
56857
56858#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
56859  /* If the new Btree uses a sharable pBtShared, then link the new
56860  ** Btree into the list of all sharable Btrees for the same connection.
56861  ** The list is kept in ascending order by pBt address.
56862  */
56863  if( p->sharable ){
56864    int i;
56865    Btree *pSib;
56866    for(i=0; i<db->nDb; i++){
56867      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
56868        while( pSib->pPrev ){ pSib = pSib->pPrev; }
56869        if( p->pBt<pSib->pBt ){
56870          p->pNext = pSib;
56871          p->pPrev = 0;
56872          pSib->pPrev = p;
56873        }else{
56874          while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
56875            pSib = pSib->pNext;
56876          }
56877          p->pNext = pSib->pNext;
56878          p->pPrev = pSib;
56879          if( p->pNext ){
56880            p->pNext->pPrev = p;
56881          }
56882          pSib->pNext = p;
56883        }
56884        break;
56885      }
56886    }
56887  }
56888#endif
56889  *ppBtree = p;
56890
56891btree_open_out:
56892  if( rc!=SQLITE_OK ){
56893    if( pBt && pBt->pPager ){
56894      sqlite3PagerClose(pBt->pPager);
56895    }
56896    sqlite3_free(pBt);
56897    sqlite3_free(p);
56898    *ppBtree = 0;
56899  }else{
56900    /* If the B-Tree was successfully opened, set the pager-cache size to the
56901    ** default value. Except, when opening on an existing shared pager-cache,
56902    ** do not change the pager-cache size.
56903    */
56904    if( sqlite3BtreeSchema(p, 0, 0)==0 ){
56905      sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
56906    }
56907  }
56908  if( mutexOpen ){
56909    assert( sqlite3_mutex_held(mutexOpen) );
56910    sqlite3_mutex_leave(mutexOpen);
56911  }
56912  return rc;
56913}
56914
56915/*
56916** Decrement the BtShared.nRef counter.  When it reaches zero,
56917** remove the BtShared structure from the sharing list.  Return
56918** true if the BtShared.nRef counter reaches zero and return
56919** false if it is still positive.
56920*/
56921static int removeFromSharingList(BtShared *pBt){
56922#ifndef SQLITE_OMIT_SHARED_CACHE
56923  MUTEX_LOGIC( sqlite3_mutex *pMaster; )
56924  BtShared *pList;
56925  int removed = 0;
56926
56927  assert( sqlite3_mutex_notheld(pBt->mutex) );
56928  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
56929  sqlite3_mutex_enter(pMaster);
56930  pBt->nRef--;
56931  if( pBt->nRef<=0 ){
56932    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
56933      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
56934    }else{
56935      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
56936      while( ALWAYS(pList) && pList->pNext!=pBt ){
56937        pList=pList->pNext;
56938      }
56939      if( ALWAYS(pList) ){
56940        pList->pNext = pBt->pNext;
56941      }
56942    }
56943    if( SQLITE_THREADSAFE ){
56944      sqlite3_mutex_free(pBt->mutex);
56945    }
56946    removed = 1;
56947  }
56948  sqlite3_mutex_leave(pMaster);
56949  return removed;
56950#else
56951  return 1;
56952#endif
56953}
56954
56955/*
56956** Make sure pBt->pTmpSpace points to an allocation of
56957** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
56958** pointer.
56959*/
56960static void allocateTempSpace(BtShared *pBt){
56961  if( !pBt->pTmpSpace ){
56962    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
56963
56964    /* One of the uses of pBt->pTmpSpace is to format cells before
56965    ** inserting them into a leaf page (function fillInCell()). If
56966    ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
56967    ** by the various routines that manipulate binary cells. Which
56968    ** can mean that fillInCell() only initializes the first 2 or 3
56969    ** bytes of pTmpSpace, but that the first 4 bytes are copied from
56970    ** it into a database page. This is not actually a problem, but it
56971    ** does cause a valgrind error when the 1 or 2 bytes of unitialized
56972    ** data is passed to system call write(). So to avoid this error,
56973    ** zero the first 4 bytes of temp space here.
56974    **
56975    ** Also:  Provide four bytes of initialized space before the
56976    ** beginning of pTmpSpace as an area available to prepend the
56977    ** left-child pointer to the beginning of a cell.
56978    */
56979    if( pBt->pTmpSpace ){
56980      memset(pBt->pTmpSpace, 0, 8);
56981      pBt->pTmpSpace += 4;
56982    }
56983  }
56984}
56985
56986/*
56987** Free the pBt->pTmpSpace allocation
56988*/
56989static void freeTempSpace(BtShared *pBt){
56990  if( pBt->pTmpSpace ){
56991    pBt->pTmpSpace -= 4;
56992    sqlite3PageFree(pBt->pTmpSpace);
56993    pBt->pTmpSpace = 0;
56994  }
56995}
56996
56997/*
56998** Close an open database and invalidate all cursors.
56999*/
57000SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
57001  BtShared *pBt = p->pBt;
57002  BtCursor *pCur;
57003
57004  /* Close all cursors opened via this handle.  */
57005  assert( sqlite3_mutex_held(p->db->mutex) );
57006  sqlite3BtreeEnter(p);
57007  pCur = pBt->pCursor;
57008  while( pCur ){
57009    BtCursor *pTmp = pCur;
57010    pCur = pCur->pNext;
57011    if( pTmp->pBtree==p ){
57012      sqlite3BtreeCloseCursor(pTmp);
57013    }
57014  }
57015
57016  /* Rollback any active transaction and free the handle structure.
57017  ** The call to sqlite3BtreeRollback() drops any table-locks held by
57018  ** this handle.
57019  */
57020  sqlite3BtreeRollback(p, SQLITE_OK, 0);
57021  sqlite3BtreeLeave(p);
57022
57023  /* If there are still other outstanding references to the shared-btree
57024  ** structure, return now. The remainder of this procedure cleans
57025  ** up the shared-btree.
57026  */
57027  assert( p->wantToLock==0 && p->locked==0 );
57028  if( !p->sharable || removeFromSharingList(pBt) ){
57029    /* The pBt is no longer on the sharing list, so we can access
57030    ** it without having to hold the mutex.
57031    **
57032    ** Clean out and delete the BtShared object.
57033    */
57034    assert( !pBt->pCursor );
57035    sqlite3PagerClose(pBt->pPager);
57036    if( pBt->xFreeSchema && pBt->pSchema ){
57037      pBt->xFreeSchema(pBt->pSchema);
57038    }
57039    sqlite3DbFree(0, pBt->pSchema);
57040    freeTempSpace(pBt);
57041    sqlite3_free(pBt);
57042  }
57043
57044#ifndef SQLITE_OMIT_SHARED_CACHE
57045  assert( p->wantToLock==0 );
57046  assert( p->locked==0 );
57047  if( p->pPrev ) p->pPrev->pNext = p->pNext;
57048  if( p->pNext ) p->pNext->pPrev = p->pPrev;
57049#endif
57050
57051  sqlite3_free(p);
57052  return SQLITE_OK;
57053}
57054
57055/*
57056** Change the limit on the number of pages allowed in the cache.
57057**
57058** The maximum number of cache pages is set to the absolute
57059** value of mxPage.  If mxPage is negative, the pager will
57060** operate asynchronously - it will not stop to do fsync()s
57061** to insure data is written to the disk surface before
57062** continuing.  Transactions still work if synchronous is off,
57063** and the database cannot be corrupted if this program
57064** crashes.  But if the operating system crashes or there is
57065** an abrupt power failure when synchronous is off, the database
57066** could be left in an inconsistent and unrecoverable state.
57067** Synchronous is on by default so database corruption is not
57068** normally a worry.
57069*/
57070SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
57071  BtShared *pBt = p->pBt;
57072  assert( sqlite3_mutex_held(p->db->mutex) );
57073  sqlite3BtreeEnter(p);
57074  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
57075  sqlite3BtreeLeave(p);
57076  return SQLITE_OK;
57077}
57078
57079#if SQLITE_MAX_MMAP_SIZE>0
57080/*
57081** Change the limit on the amount of the database file that may be
57082** memory mapped.
57083*/
57084SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
57085  BtShared *pBt = p->pBt;
57086  assert( sqlite3_mutex_held(p->db->mutex) );
57087  sqlite3BtreeEnter(p);
57088  sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
57089  sqlite3BtreeLeave(p);
57090  return SQLITE_OK;
57091}
57092#endif /* SQLITE_MAX_MMAP_SIZE>0 */
57093
57094/*
57095** Change the way data is synced to disk in order to increase or decrease
57096** how well the database resists damage due to OS crashes and power
57097** failures.  Level 1 is the same as asynchronous (no syncs() occur and
57098** there is a high probability of damage)  Level 2 is the default.  There
57099** is a very low but non-zero probability of damage.  Level 3 reduces the
57100** probability of damage to near zero but with a write performance reduction.
57101*/
57102#ifndef SQLITE_OMIT_PAGER_PRAGMAS
57103SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
57104  Btree *p,              /* The btree to set the safety level on */
57105  unsigned pgFlags       /* Various PAGER_* flags */
57106){
57107  BtShared *pBt = p->pBt;
57108  assert( sqlite3_mutex_held(p->db->mutex) );
57109  sqlite3BtreeEnter(p);
57110  sqlite3PagerSetFlags(pBt->pPager, pgFlags);
57111  sqlite3BtreeLeave(p);
57112  return SQLITE_OK;
57113}
57114#endif
57115
57116/*
57117** Return TRUE if the given btree is set to safety level 1.  In other
57118** words, return TRUE if no sync() occurs on the disk files.
57119*/
57120SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
57121  BtShared *pBt = p->pBt;
57122  int rc;
57123  assert( sqlite3_mutex_held(p->db->mutex) );
57124  sqlite3BtreeEnter(p);
57125  assert( pBt && pBt->pPager );
57126  rc = sqlite3PagerNosync(pBt->pPager);
57127  sqlite3BtreeLeave(p);
57128  return rc;
57129}
57130
57131/*
57132** Change the default pages size and the number of reserved bytes per page.
57133** Or, if the page size has already been fixed, return SQLITE_READONLY
57134** without changing anything.
57135**
57136** The page size must be a power of 2 between 512 and 65536.  If the page
57137** size supplied does not meet this constraint then the page size is not
57138** changed.
57139**
57140** Page sizes are constrained to be a power of two so that the region
57141** of the database file used for locking (beginning at PENDING_BYTE,
57142** the first byte past the 1GB boundary, 0x40000000) needs to occur
57143** at the beginning of a page.
57144**
57145** If parameter nReserve is less than zero, then the number of reserved
57146** bytes per page is left unchanged.
57147**
57148** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
57149** and autovacuum mode can no longer be changed.
57150*/
57151SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
57152  int rc = SQLITE_OK;
57153  BtShared *pBt = p->pBt;
57154  assert( nReserve>=-1 && nReserve<=255 );
57155  sqlite3BtreeEnter(p);
57156#if SQLITE_HAS_CODEC
57157  if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
57158#endif
57159  if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
57160    sqlite3BtreeLeave(p);
57161    return SQLITE_READONLY;
57162  }
57163  if( nReserve<0 ){
57164    nReserve = pBt->pageSize - pBt->usableSize;
57165  }
57166  assert( nReserve>=0 && nReserve<=255 );
57167  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
57168        ((pageSize-1)&pageSize)==0 ){
57169    assert( (pageSize & 7)==0 );
57170    assert( !pBt->pCursor );
57171    pBt->pageSize = (u32)pageSize;
57172    freeTempSpace(pBt);
57173  }
57174  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
57175  pBt->usableSize = pBt->pageSize - (u16)nReserve;
57176  if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
57177  sqlite3BtreeLeave(p);
57178  return rc;
57179}
57180
57181/*
57182** Return the currently defined page size
57183*/
57184SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
57185  return p->pBt->pageSize;
57186}
57187
57188/*
57189** This function is similar to sqlite3BtreeGetReserve(), except that it
57190** may only be called if it is guaranteed that the b-tree mutex is already
57191** held.
57192**
57193** This is useful in one special case in the backup API code where it is
57194** known that the shared b-tree mutex is held, but the mutex on the
57195** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
57196** were to be called, it might collide with some other operation on the
57197** database handle that owns *p, causing undefined behavior.
57198*/
57199SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
57200  int n;
57201  assert( sqlite3_mutex_held(p->pBt->mutex) );
57202  n = p->pBt->pageSize - p->pBt->usableSize;
57203  return n;
57204}
57205
57206/*
57207** Return the number of bytes of space at the end of every page that
57208** are intentually left unused.  This is the "reserved" space that is
57209** sometimes used by extensions.
57210**
57211** If SQLITE_HAS_MUTEX is defined then the number returned is the
57212** greater of the current reserved space and the maximum requested
57213** reserve space.
57214*/
57215SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
57216  int n;
57217  sqlite3BtreeEnter(p);
57218  n = sqlite3BtreeGetReserveNoMutex(p);
57219#ifdef SQLITE_HAS_CODEC
57220  if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
57221#endif
57222  sqlite3BtreeLeave(p);
57223  return n;
57224}
57225
57226
57227/*
57228** Set the maximum page count for a database if mxPage is positive.
57229** No changes are made if mxPage is 0 or negative.
57230** Regardless of the value of mxPage, return the maximum page count.
57231*/
57232SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
57233  int n;
57234  sqlite3BtreeEnter(p);
57235  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
57236  sqlite3BtreeLeave(p);
57237  return n;
57238}
57239
57240/*
57241** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
57242** then make no changes.  Always return the value of the BTS_SECURE_DELETE
57243** setting after the change.
57244*/
57245SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
57246  int b;
57247  if( p==0 ) return 0;
57248  sqlite3BtreeEnter(p);
57249  if( newFlag>=0 ){
57250    p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
57251    if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
57252  }
57253  b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
57254  sqlite3BtreeLeave(p);
57255  return b;
57256}
57257
57258/*
57259** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
57260** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
57261** is disabled. The default value for the auto-vacuum property is
57262** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
57263*/
57264SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
57265#ifdef SQLITE_OMIT_AUTOVACUUM
57266  return SQLITE_READONLY;
57267#else
57268  BtShared *pBt = p->pBt;
57269  int rc = SQLITE_OK;
57270  u8 av = (u8)autoVacuum;
57271
57272  sqlite3BtreeEnter(p);
57273  if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
57274    rc = SQLITE_READONLY;
57275  }else{
57276    pBt->autoVacuum = av ?1:0;
57277    pBt->incrVacuum = av==2 ?1:0;
57278  }
57279  sqlite3BtreeLeave(p);
57280  return rc;
57281#endif
57282}
57283
57284/*
57285** Return the value of the 'auto-vacuum' property. If auto-vacuum is
57286** enabled 1 is returned. Otherwise 0.
57287*/
57288SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
57289#ifdef SQLITE_OMIT_AUTOVACUUM
57290  return BTREE_AUTOVACUUM_NONE;
57291#else
57292  int rc;
57293  sqlite3BtreeEnter(p);
57294  rc = (
57295    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
57296    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
57297    BTREE_AUTOVACUUM_INCR
57298  );
57299  sqlite3BtreeLeave(p);
57300  return rc;
57301#endif
57302}
57303
57304
57305/*
57306** Get a reference to pPage1 of the database file.  This will
57307** also acquire a readlock on that file.
57308**
57309** SQLITE_OK is returned on success.  If the file is not a
57310** well-formed database file, then SQLITE_CORRUPT is returned.
57311** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
57312** is returned if we run out of memory.
57313*/
57314static int lockBtree(BtShared *pBt){
57315  int rc;              /* Result code from subfunctions */
57316  MemPage *pPage1;     /* Page 1 of the database file */
57317  int nPage;           /* Number of pages in the database */
57318  int nPageFile = 0;   /* Number of pages in the database file */
57319  int nPageHeader;     /* Number of pages in the database according to hdr */
57320
57321  assert( sqlite3_mutex_held(pBt->mutex) );
57322  assert( pBt->pPage1==0 );
57323  rc = sqlite3PagerSharedLock(pBt->pPager);
57324  if( rc!=SQLITE_OK ) return rc;
57325  rc = btreeGetPage(pBt, 1, &pPage1, 0);
57326  if( rc!=SQLITE_OK ) return rc;
57327
57328  /* Do some checking to help insure the file we opened really is
57329  ** a valid database file.
57330  */
57331  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
57332  sqlite3PagerPagecount(pBt->pPager, &nPageFile);
57333  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
57334    nPage = nPageFile;
57335  }
57336  if( nPage>0 ){
57337    u32 pageSize;
57338    u32 usableSize;
57339    u8 *page1 = pPage1->aData;
57340    rc = SQLITE_NOTADB;
57341    /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
57342    ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
57343    ** 61 74 20 33 00. */
57344    if( memcmp(page1, zMagicHeader, 16)!=0 ){
57345      goto page1_init_failed;
57346    }
57347
57348#ifdef SQLITE_OMIT_WAL
57349    if( page1[18]>1 ){
57350      pBt->btsFlags |= BTS_READ_ONLY;
57351    }
57352    if( page1[19]>1 ){
57353      goto page1_init_failed;
57354    }
57355#else
57356    if( page1[18]>2 ){
57357      pBt->btsFlags |= BTS_READ_ONLY;
57358    }
57359    if( page1[19]>2 ){
57360      goto page1_init_failed;
57361    }
57362
57363    /* If the write version is set to 2, this database should be accessed
57364    ** in WAL mode. If the log is not already open, open it now. Then
57365    ** return SQLITE_OK and return without populating BtShared.pPage1.
57366    ** The caller detects this and calls this function again. This is
57367    ** required as the version of page 1 currently in the page1 buffer
57368    ** may not be the latest version - there may be a newer one in the log
57369    ** file.
57370    */
57371    if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
57372      int isOpen = 0;
57373      rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
57374      if( rc!=SQLITE_OK ){
57375        goto page1_init_failed;
57376      }else if( isOpen==0 ){
57377        releasePage(pPage1);
57378        return SQLITE_OK;
57379      }
57380      rc = SQLITE_NOTADB;
57381    }
57382#endif
57383
57384    /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
57385    ** fractions and the leaf payload fraction values must be 64, 32, and 32.
57386    **
57387    ** The original design allowed these amounts to vary, but as of
57388    ** version 3.6.0, we require them to be fixed.
57389    */
57390    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
57391      goto page1_init_failed;
57392    }
57393    /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
57394    ** determined by the 2-byte integer located at an offset of 16 bytes from
57395    ** the beginning of the database file. */
57396    pageSize = (page1[16]<<8) | (page1[17]<<16);
57397    /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
57398    ** between 512 and 65536 inclusive. */
57399    if( ((pageSize-1)&pageSize)!=0
57400     || pageSize>SQLITE_MAX_PAGE_SIZE
57401     || pageSize<=256
57402    ){
57403      goto page1_init_failed;
57404    }
57405    assert( (pageSize & 7)==0 );
57406    /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
57407    ** integer at offset 20 is the number of bytes of space at the end of
57408    ** each page to reserve for extensions.
57409    **
57410    ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
57411    ** determined by the one-byte unsigned integer found at an offset of 20
57412    ** into the database file header. */
57413    usableSize = pageSize - page1[20];
57414    if( (u32)pageSize!=pBt->pageSize ){
57415      /* After reading the first page of the database assuming a page size
57416      ** of BtShared.pageSize, we have discovered that the page-size is
57417      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
57418      ** zero and return SQLITE_OK. The caller will call this function
57419      ** again with the correct page-size.
57420      */
57421      releasePage(pPage1);
57422      pBt->usableSize = usableSize;
57423      pBt->pageSize = pageSize;
57424      freeTempSpace(pBt);
57425      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
57426                                   pageSize-usableSize);
57427      return rc;
57428    }
57429    if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
57430      rc = SQLITE_CORRUPT_BKPT;
57431      goto page1_init_failed;
57432    }
57433    /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
57434    ** be less than 480. In other words, if the page size is 512, then the
57435    ** reserved space size cannot exceed 32. */
57436    if( usableSize<480 ){
57437      goto page1_init_failed;
57438    }
57439    pBt->pageSize = pageSize;
57440    pBt->usableSize = usableSize;
57441#ifndef SQLITE_OMIT_AUTOVACUUM
57442    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
57443    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
57444#endif
57445  }
57446
57447  /* maxLocal is the maximum amount of payload to store locally for
57448  ** a cell.  Make sure it is small enough so that at least minFanout
57449  ** cells can will fit on one page.  We assume a 10-byte page header.
57450  ** Besides the payload, the cell must store:
57451  **     2-byte pointer to the cell
57452  **     4-byte child pointer
57453  **     9-byte nKey value
57454  **     4-byte nData value
57455  **     4-byte overflow page pointer
57456  ** So a cell consists of a 2-byte pointer, a header which is as much as
57457  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
57458  ** page pointer.
57459  */
57460  pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
57461  pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
57462  pBt->maxLeaf = (u16)(pBt->usableSize - 35);
57463  pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
57464  if( pBt->maxLocal>127 ){
57465    pBt->max1bytePayload = 127;
57466  }else{
57467    pBt->max1bytePayload = (u8)pBt->maxLocal;
57468  }
57469  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
57470  pBt->pPage1 = pPage1;
57471  pBt->nPage = nPage;
57472  return SQLITE_OK;
57473
57474page1_init_failed:
57475  releasePage(pPage1);
57476  pBt->pPage1 = 0;
57477  return rc;
57478}
57479
57480#ifndef NDEBUG
57481/*
57482** Return the number of cursors open on pBt. This is for use
57483** in assert() expressions, so it is only compiled if NDEBUG is not
57484** defined.
57485**
57486** Only write cursors are counted if wrOnly is true.  If wrOnly is
57487** false then all cursors are counted.
57488**
57489** For the purposes of this routine, a cursor is any cursor that
57490** is capable of reading or writing to the database.  Cursors that
57491** have been tripped into the CURSOR_FAULT state are not counted.
57492*/
57493static int countValidCursors(BtShared *pBt, int wrOnly){
57494  BtCursor *pCur;
57495  int r = 0;
57496  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
57497    if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
57498     && pCur->eState!=CURSOR_FAULT ) r++;
57499  }
57500  return r;
57501}
57502#endif
57503
57504/*
57505** If there are no outstanding cursors and we are not in the middle
57506** of a transaction but there is a read lock on the database, then
57507** this routine unrefs the first page of the database file which
57508** has the effect of releasing the read lock.
57509**
57510** If there is a transaction in progress, this routine is a no-op.
57511*/
57512static void unlockBtreeIfUnused(BtShared *pBt){
57513  assert( sqlite3_mutex_held(pBt->mutex) );
57514  assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
57515  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
57516    MemPage *pPage1 = pBt->pPage1;
57517    assert( pPage1->aData );
57518    assert( sqlite3PagerRefcount(pBt->pPager)==1 );
57519    pBt->pPage1 = 0;
57520    releasePageNotNull(pPage1);
57521  }
57522}
57523
57524/*
57525** If pBt points to an empty file then convert that empty file
57526** into a new empty database by initializing the first page of
57527** the database.
57528*/
57529static int newDatabase(BtShared *pBt){
57530  MemPage *pP1;
57531  unsigned char *data;
57532  int rc;
57533
57534  assert( sqlite3_mutex_held(pBt->mutex) );
57535  if( pBt->nPage>0 ){
57536    return SQLITE_OK;
57537  }
57538  pP1 = pBt->pPage1;
57539  assert( pP1!=0 );
57540  data = pP1->aData;
57541  rc = sqlite3PagerWrite(pP1->pDbPage);
57542  if( rc ) return rc;
57543  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
57544  assert( sizeof(zMagicHeader)==16 );
57545  data[16] = (u8)((pBt->pageSize>>8)&0xff);
57546  data[17] = (u8)((pBt->pageSize>>16)&0xff);
57547  data[18] = 1;
57548  data[19] = 1;
57549  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
57550  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
57551  data[21] = 64;
57552  data[22] = 32;
57553  data[23] = 32;
57554  memset(&data[24], 0, 100-24);
57555  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
57556  pBt->btsFlags |= BTS_PAGESIZE_FIXED;
57557#ifndef SQLITE_OMIT_AUTOVACUUM
57558  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
57559  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
57560  put4byte(&data[36 + 4*4], pBt->autoVacuum);
57561  put4byte(&data[36 + 7*4], pBt->incrVacuum);
57562#endif
57563  pBt->nPage = 1;
57564  data[31] = 1;
57565  return SQLITE_OK;
57566}
57567
57568/*
57569** Initialize the first page of the database file (creating a database
57570** consisting of a single page and no schema objects). Return SQLITE_OK
57571** if successful, or an SQLite error code otherwise.
57572*/
57573SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
57574  int rc;
57575  sqlite3BtreeEnter(p);
57576  p->pBt->nPage = 0;
57577  rc = newDatabase(p->pBt);
57578  sqlite3BtreeLeave(p);
57579  return rc;
57580}
57581
57582/*
57583** Attempt to start a new transaction. A write-transaction
57584** is started if the second argument is nonzero, otherwise a read-
57585** transaction.  If the second argument is 2 or more and exclusive
57586** transaction is started, meaning that no other process is allowed
57587** to access the database.  A preexisting transaction may not be
57588** upgraded to exclusive by calling this routine a second time - the
57589** exclusivity flag only works for a new transaction.
57590**
57591** A write-transaction must be started before attempting any
57592** changes to the database.  None of the following routines
57593** will work unless a transaction is started first:
57594**
57595**      sqlite3BtreeCreateTable()
57596**      sqlite3BtreeCreateIndex()
57597**      sqlite3BtreeClearTable()
57598**      sqlite3BtreeDropTable()
57599**      sqlite3BtreeInsert()
57600**      sqlite3BtreeDelete()
57601**      sqlite3BtreeUpdateMeta()
57602**
57603** If an initial attempt to acquire the lock fails because of lock contention
57604** and the database was previously unlocked, then invoke the busy handler
57605** if there is one.  But if there was previously a read-lock, do not
57606** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
57607** returned when there is already a read-lock in order to avoid a deadlock.
57608**
57609** Suppose there are two processes A and B.  A has a read lock and B has
57610** a reserved lock.  B tries to promote to exclusive but is blocked because
57611** of A's read lock.  A tries to promote to reserved but is blocked by B.
57612** One or the other of the two processes must give way or there can be
57613** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
57614** when A already has a read lock, we encourage A to give up and let B
57615** proceed.
57616*/
57617SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
57618  sqlite3 *pBlock = 0;
57619  BtShared *pBt = p->pBt;
57620  int rc = SQLITE_OK;
57621
57622  sqlite3BtreeEnter(p);
57623  btreeIntegrity(p);
57624
57625  /* If the btree is already in a write-transaction, or it
57626  ** is already in a read-transaction and a read-transaction
57627  ** is requested, this is a no-op.
57628  */
57629  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
57630    goto trans_begun;
57631  }
57632  assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
57633
57634  /* Write transactions are not possible on a read-only database */
57635  if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
57636    rc = SQLITE_READONLY;
57637    goto trans_begun;
57638  }
57639
57640#ifndef SQLITE_OMIT_SHARED_CACHE
57641  /* If another database handle has already opened a write transaction
57642  ** on this shared-btree structure and a second write transaction is
57643  ** requested, return SQLITE_LOCKED.
57644  */
57645  if( (wrflag && pBt->inTransaction==TRANS_WRITE)
57646   || (pBt->btsFlags & BTS_PENDING)!=0
57647  ){
57648    pBlock = pBt->pWriter->db;
57649  }else if( wrflag>1 ){
57650    BtLock *pIter;
57651    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
57652      if( pIter->pBtree!=p ){
57653        pBlock = pIter->pBtree->db;
57654        break;
57655      }
57656    }
57657  }
57658  if( pBlock ){
57659    sqlite3ConnectionBlocked(p->db, pBlock);
57660    rc = SQLITE_LOCKED_SHAREDCACHE;
57661    goto trans_begun;
57662  }
57663#endif
57664
57665  /* Any read-only or read-write transaction implies a read-lock on
57666  ** page 1. So if some other shared-cache client already has a write-lock
57667  ** on page 1, the transaction cannot be opened. */
57668  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
57669  if( SQLITE_OK!=rc ) goto trans_begun;
57670
57671  pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
57672  if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
57673  do {
57674    /* Call lockBtree() until either pBt->pPage1 is populated or
57675    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
57676    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
57677    ** reading page 1 it discovers that the page-size of the database
57678    ** file is not pBt->pageSize. In this case lockBtree() will update
57679    ** pBt->pageSize to the page-size of the file on disk.
57680    */
57681    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
57682
57683    if( rc==SQLITE_OK && wrflag ){
57684      if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
57685        rc = SQLITE_READONLY;
57686      }else{
57687        rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
57688        if( rc==SQLITE_OK ){
57689          rc = newDatabase(pBt);
57690        }
57691      }
57692    }
57693
57694    if( rc!=SQLITE_OK ){
57695      unlockBtreeIfUnused(pBt);
57696    }
57697  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
57698          btreeInvokeBusyHandler(pBt) );
57699
57700  if( rc==SQLITE_OK ){
57701    if( p->inTrans==TRANS_NONE ){
57702      pBt->nTransaction++;
57703#ifndef SQLITE_OMIT_SHARED_CACHE
57704      if( p->sharable ){
57705        assert( p->lock.pBtree==p && p->lock.iTable==1 );
57706        p->lock.eLock = READ_LOCK;
57707        p->lock.pNext = pBt->pLock;
57708        pBt->pLock = &p->lock;
57709      }
57710#endif
57711    }
57712    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
57713    if( p->inTrans>pBt->inTransaction ){
57714      pBt->inTransaction = p->inTrans;
57715    }
57716    if( wrflag ){
57717      MemPage *pPage1 = pBt->pPage1;
57718#ifndef SQLITE_OMIT_SHARED_CACHE
57719      assert( !pBt->pWriter );
57720      pBt->pWriter = p;
57721      pBt->btsFlags &= ~BTS_EXCLUSIVE;
57722      if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
57723#endif
57724
57725      /* If the db-size header field is incorrect (as it may be if an old
57726      ** client has been writing the database file), update it now. Doing
57727      ** this sooner rather than later means the database size can safely
57728      ** re-read the database size from page 1 if a savepoint or transaction
57729      ** rollback occurs within the transaction.
57730      */
57731      if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
57732        rc = sqlite3PagerWrite(pPage1->pDbPage);
57733        if( rc==SQLITE_OK ){
57734          put4byte(&pPage1->aData[28], pBt->nPage);
57735        }
57736      }
57737    }
57738  }
57739
57740
57741trans_begun:
57742  if( rc==SQLITE_OK && wrflag ){
57743    /* This call makes sure that the pager has the correct number of
57744    ** open savepoints. If the second parameter is greater than 0 and
57745    ** the sub-journal is not already open, then it will be opened here.
57746    */
57747    rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
57748  }
57749
57750  btreeIntegrity(p);
57751  sqlite3BtreeLeave(p);
57752  return rc;
57753}
57754
57755#ifndef SQLITE_OMIT_AUTOVACUUM
57756
57757/*
57758** Set the pointer-map entries for all children of page pPage. Also, if
57759** pPage contains cells that point to overflow pages, set the pointer
57760** map entries for the overflow pages as well.
57761*/
57762static int setChildPtrmaps(MemPage *pPage){
57763  int i;                             /* Counter variable */
57764  int nCell;                         /* Number of cells in page pPage */
57765  int rc;                            /* Return code */
57766  BtShared *pBt = pPage->pBt;
57767  u8 isInitOrig = pPage->isInit;
57768  Pgno pgno = pPage->pgno;
57769
57770  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
57771  rc = btreeInitPage(pPage);
57772  if( rc!=SQLITE_OK ){
57773    goto set_child_ptrmaps_out;
57774  }
57775  nCell = pPage->nCell;
57776
57777  for(i=0; i<nCell; i++){
57778    u8 *pCell = findCell(pPage, i);
57779
57780    ptrmapPutOvflPtr(pPage, pCell, &rc);
57781
57782    if( !pPage->leaf ){
57783      Pgno childPgno = get4byte(pCell);
57784      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
57785    }
57786  }
57787
57788  if( !pPage->leaf ){
57789    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
57790    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
57791  }
57792
57793set_child_ptrmaps_out:
57794  pPage->isInit = isInitOrig;
57795  return rc;
57796}
57797
57798/*
57799** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
57800** that it points to iTo. Parameter eType describes the type of pointer to
57801** be modified, as  follows:
57802**
57803** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
57804**                   page of pPage.
57805**
57806** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
57807**                   page pointed to by one of the cells on pPage.
57808**
57809** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
57810**                   overflow page in the list.
57811*/
57812static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
57813  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
57814  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
57815  if( eType==PTRMAP_OVERFLOW2 ){
57816    /* The pointer is always the first 4 bytes of the page in this case.  */
57817    if( get4byte(pPage->aData)!=iFrom ){
57818      return SQLITE_CORRUPT_BKPT;
57819    }
57820    put4byte(pPage->aData, iTo);
57821  }else{
57822    u8 isInitOrig = pPage->isInit;
57823    int i;
57824    int nCell;
57825    int rc;
57826
57827    rc = btreeInitPage(pPage);
57828    if( rc ) return rc;
57829    nCell = pPage->nCell;
57830
57831    for(i=0; i<nCell; i++){
57832      u8 *pCell = findCell(pPage, i);
57833      if( eType==PTRMAP_OVERFLOW1 ){
57834        CellInfo info;
57835        pPage->xParseCell(pPage, pCell, &info);
57836        if( info.iOverflow
57837         && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
57838         && iFrom==get4byte(&pCell[info.iOverflow])
57839        ){
57840          put4byte(&pCell[info.iOverflow], iTo);
57841          break;
57842        }
57843      }else{
57844        if( get4byte(pCell)==iFrom ){
57845          put4byte(pCell, iTo);
57846          break;
57847        }
57848      }
57849    }
57850
57851    if( i==nCell ){
57852      if( eType!=PTRMAP_BTREE ||
57853          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
57854        return SQLITE_CORRUPT_BKPT;
57855      }
57856      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
57857    }
57858
57859    pPage->isInit = isInitOrig;
57860  }
57861  return SQLITE_OK;
57862}
57863
57864
57865/*
57866** Move the open database page pDbPage to location iFreePage in the
57867** database. The pDbPage reference remains valid.
57868**
57869** The isCommit flag indicates that there is no need to remember that
57870** the journal needs to be sync()ed before database page pDbPage->pgno
57871** can be written to. The caller has already promised not to write to that
57872** page.
57873*/
57874static int relocatePage(
57875  BtShared *pBt,           /* Btree */
57876  MemPage *pDbPage,        /* Open page to move */
57877  u8 eType,                /* Pointer map 'type' entry for pDbPage */
57878  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
57879  Pgno iFreePage,          /* The location to move pDbPage to */
57880  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
57881){
57882  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
57883  Pgno iDbPage = pDbPage->pgno;
57884  Pager *pPager = pBt->pPager;
57885  int rc;
57886
57887  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
57888      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
57889  assert( sqlite3_mutex_held(pBt->mutex) );
57890  assert( pDbPage->pBt==pBt );
57891
57892  /* Move page iDbPage from its current location to page number iFreePage */
57893  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
57894      iDbPage, iFreePage, iPtrPage, eType));
57895  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
57896  if( rc!=SQLITE_OK ){
57897    return rc;
57898  }
57899  pDbPage->pgno = iFreePage;
57900
57901  /* If pDbPage was a btree-page, then it may have child pages and/or cells
57902  ** that point to overflow pages. The pointer map entries for all these
57903  ** pages need to be changed.
57904  **
57905  ** If pDbPage is an overflow page, then the first 4 bytes may store a
57906  ** pointer to a subsequent overflow page. If this is the case, then
57907  ** the pointer map needs to be updated for the subsequent overflow page.
57908  */
57909  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
57910    rc = setChildPtrmaps(pDbPage);
57911    if( rc!=SQLITE_OK ){
57912      return rc;
57913    }
57914  }else{
57915    Pgno nextOvfl = get4byte(pDbPage->aData);
57916    if( nextOvfl!=0 ){
57917      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
57918      if( rc!=SQLITE_OK ){
57919        return rc;
57920      }
57921    }
57922  }
57923
57924  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
57925  ** that it points at iFreePage. Also fix the pointer map entry for
57926  ** iPtrPage.
57927  */
57928  if( eType!=PTRMAP_ROOTPAGE ){
57929    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
57930    if( rc!=SQLITE_OK ){
57931      return rc;
57932    }
57933    rc = sqlite3PagerWrite(pPtrPage->pDbPage);
57934    if( rc!=SQLITE_OK ){
57935      releasePage(pPtrPage);
57936      return rc;
57937    }
57938    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
57939    releasePage(pPtrPage);
57940    if( rc==SQLITE_OK ){
57941      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
57942    }
57943  }
57944  return rc;
57945}
57946
57947/* Forward declaration required by incrVacuumStep(). */
57948static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
57949
57950/*
57951** Perform a single step of an incremental-vacuum. If successful, return
57952** SQLITE_OK. If there is no work to do (and therefore no point in
57953** calling this function again), return SQLITE_DONE. Or, if an error
57954** occurs, return some other error code.
57955**
57956** More specifically, this function attempts to re-organize the database so
57957** that the last page of the file currently in use is no longer in use.
57958**
57959** Parameter nFin is the number of pages that this database would contain
57960** were this function called until it returns SQLITE_DONE.
57961**
57962** If the bCommit parameter is non-zero, this function assumes that the
57963** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
57964** or an error. bCommit is passed true for an auto-vacuum-on-commit
57965** operation, or false for an incremental vacuum.
57966*/
57967static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
57968  Pgno nFreeList;           /* Number of pages still on the free-list */
57969  int rc;
57970
57971  assert( sqlite3_mutex_held(pBt->mutex) );
57972  assert( iLastPg>nFin );
57973
57974  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
57975    u8 eType;
57976    Pgno iPtrPage;
57977
57978    nFreeList = get4byte(&pBt->pPage1->aData[36]);
57979    if( nFreeList==0 ){
57980      return SQLITE_DONE;
57981    }
57982
57983    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
57984    if( rc!=SQLITE_OK ){
57985      return rc;
57986    }
57987    if( eType==PTRMAP_ROOTPAGE ){
57988      return SQLITE_CORRUPT_BKPT;
57989    }
57990
57991    if( eType==PTRMAP_FREEPAGE ){
57992      if( bCommit==0 ){
57993        /* Remove the page from the files free-list. This is not required
57994        ** if bCommit is non-zero. In that case, the free-list will be
57995        ** truncated to zero after this function returns, so it doesn't
57996        ** matter if it still contains some garbage entries.
57997        */
57998        Pgno iFreePg;
57999        MemPage *pFreePg;
58000        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
58001        if( rc!=SQLITE_OK ){
58002          return rc;
58003        }
58004        assert( iFreePg==iLastPg );
58005        releasePage(pFreePg);
58006      }
58007    } else {
58008      Pgno iFreePg;             /* Index of free page to move pLastPg to */
58009      MemPage *pLastPg;
58010      u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
58011      Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
58012
58013      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
58014      if( rc!=SQLITE_OK ){
58015        return rc;
58016      }
58017
58018      /* If bCommit is zero, this loop runs exactly once and page pLastPg
58019      ** is swapped with the first free page pulled off the free list.
58020      **
58021      ** On the other hand, if bCommit is greater than zero, then keep
58022      ** looping until a free-page located within the first nFin pages
58023      ** of the file is found.
58024      */
58025      if( bCommit==0 ){
58026        eMode = BTALLOC_LE;
58027        iNear = nFin;
58028      }
58029      do {
58030        MemPage *pFreePg;
58031        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
58032        if( rc!=SQLITE_OK ){
58033          releasePage(pLastPg);
58034          return rc;
58035        }
58036        releasePage(pFreePg);
58037      }while( bCommit && iFreePg>nFin );
58038      assert( iFreePg<iLastPg );
58039
58040      rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
58041      releasePage(pLastPg);
58042      if( rc!=SQLITE_OK ){
58043        return rc;
58044      }
58045    }
58046  }
58047
58048  if( bCommit==0 ){
58049    do {
58050      iLastPg--;
58051    }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
58052    pBt->bDoTruncate = 1;
58053    pBt->nPage = iLastPg;
58054  }
58055  return SQLITE_OK;
58056}
58057
58058/*
58059** The database opened by the first argument is an auto-vacuum database
58060** nOrig pages in size containing nFree free pages. Return the expected
58061** size of the database in pages following an auto-vacuum operation.
58062*/
58063static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
58064  int nEntry;                     /* Number of entries on one ptrmap page */
58065  Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
58066  Pgno nFin;                      /* Return value */
58067
58068  nEntry = pBt->usableSize/5;
58069  nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
58070  nFin = nOrig - nFree - nPtrmap;
58071  if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
58072    nFin--;
58073  }
58074  while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
58075    nFin--;
58076  }
58077
58078  return nFin;
58079}
58080
58081/*
58082** A write-transaction must be opened before calling this function.
58083** It performs a single unit of work towards an incremental vacuum.
58084**
58085** If the incremental vacuum is finished after this function has run,
58086** SQLITE_DONE is returned. If it is not finished, but no error occurred,
58087** SQLITE_OK is returned. Otherwise an SQLite error code.
58088*/
58089SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
58090  int rc;
58091  BtShared *pBt = p->pBt;
58092
58093  sqlite3BtreeEnter(p);
58094  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
58095  if( !pBt->autoVacuum ){
58096    rc = SQLITE_DONE;
58097  }else{
58098    Pgno nOrig = btreePagecount(pBt);
58099    Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
58100    Pgno nFin = finalDbSize(pBt, nOrig, nFree);
58101
58102    if( nOrig<nFin ){
58103      rc = SQLITE_CORRUPT_BKPT;
58104    }else if( nFree>0 ){
58105      rc = saveAllCursors(pBt, 0, 0);
58106      if( rc==SQLITE_OK ){
58107        invalidateAllOverflowCache(pBt);
58108        rc = incrVacuumStep(pBt, nFin, nOrig, 0);
58109      }
58110      if( rc==SQLITE_OK ){
58111        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
58112        put4byte(&pBt->pPage1->aData[28], pBt->nPage);
58113      }
58114    }else{
58115      rc = SQLITE_DONE;
58116    }
58117  }
58118  sqlite3BtreeLeave(p);
58119  return rc;
58120}
58121
58122/*
58123** This routine is called prior to sqlite3PagerCommit when a transaction
58124** is committed for an auto-vacuum database.
58125**
58126** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
58127** the database file should be truncated to during the commit process.
58128** i.e. the database has been reorganized so that only the first *pnTrunc
58129** pages are in use.
58130*/
58131static int autoVacuumCommit(BtShared *pBt){
58132  int rc = SQLITE_OK;
58133  Pager *pPager = pBt->pPager;
58134  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
58135
58136  assert( sqlite3_mutex_held(pBt->mutex) );
58137  invalidateAllOverflowCache(pBt);
58138  assert(pBt->autoVacuum);
58139  if( !pBt->incrVacuum ){
58140    Pgno nFin;         /* Number of pages in database after autovacuuming */
58141    Pgno nFree;        /* Number of pages on the freelist initially */
58142    Pgno iFree;        /* The next page to be freed */
58143    Pgno nOrig;        /* Database size before freeing */
58144
58145    nOrig = btreePagecount(pBt);
58146    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
58147      /* It is not possible to create a database for which the final page
58148      ** is either a pointer-map page or the pending-byte page. If one
58149      ** is encountered, this indicates corruption.
58150      */
58151      return SQLITE_CORRUPT_BKPT;
58152    }
58153
58154    nFree = get4byte(&pBt->pPage1->aData[36]);
58155    nFin = finalDbSize(pBt, nOrig, nFree);
58156    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
58157    if( nFin<nOrig ){
58158      rc = saveAllCursors(pBt, 0, 0);
58159    }
58160    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
58161      rc = incrVacuumStep(pBt, nFin, iFree, 1);
58162    }
58163    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
58164      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
58165      put4byte(&pBt->pPage1->aData[32], 0);
58166      put4byte(&pBt->pPage1->aData[36], 0);
58167      put4byte(&pBt->pPage1->aData[28], nFin);
58168      pBt->bDoTruncate = 1;
58169      pBt->nPage = nFin;
58170    }
58171    if( rc!=SQLITE_OK ){
58172      sqlite3PagerRollback(pPager);
58173    }
58174  }
58175
58176  assert( nRef>=sqlite3PagerRefcount(pPager) );
58177  return rc;
58178}
58179
58180#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
58181# define setChildPtrmaps(x) SQLITE_OK
58182#endif
58183
58184/*
58185** This routine does the first phase of a two-phase commit.  This routine
58186** causes a rollback journal to be created (if it does not already exist)
58187** and populated with enough information so that if a power loss occurs
58188** the database can be restored to its original state by playing back
58189** the journal.  Then the contents of the journal are flushed out to
58190** the disk.  After the journal is safely on oxide, the changes to the
58191** database are written into the database file and flushed to oxide.
58192** At the end of this call, the rollback journal still exists on the
58193** disk and we are still holding all locks, so the transaction has not
58194** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
58195** commit process.
58196**
58197** This call is a no-op if no write-transaction is currently active on pBt.
58198**
58199** Otherwise, sync the database file for the btree pBt. zMaster points to
58200** the name of a master journal file that should be written into the
58201** individual journal file, or is NULL, indicating no master journal file
58202** (single database transaction).
58203**
58204** When this is called, the master journal should already have been
58205** created, populated with this journal pointer and synced to disk.
58206**
58207** Once this is routine has returned, the only thing required to commit
58208** the write-transaction for this database file is to delete the journal.
58209*/
58210SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
58211  int rc = SQLITE_OK;
58212  if( p->inTrans==TRANS_WRITE ){
58213    BtShared *pBt = p->pBt;
58214    sqlite3BtreeEnter(p);
58215#ifndef SQLITE_OMIT_AUTOVACUUM
58216    if( pBt->autoVacuum ){
58217      rc = autoVacuumCommit(pBt);
58218      if( rc!=SQLITE_OK ){
58219        sqlite3BtreeLeave(p);
58220        return rc;
58221      }
58222    }
58223    if( pBt->bDoTruncate ){
58224      sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
58225    }
58226#endif
58227    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
58228    sqlite3BtreeLeave(p);
58229  }
58230  return rc;
58231}
58232
58233/*
58234** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
58235** at the conclusion of a transaction.
58236*/
58237static void btreeEndTransaction(Btree *p){
58238  BtShared *pBt = p->pBt;
58239  sqlite3 *db = p->db;
58240  assert( sqlite3BtreeHoldsMutex(p) );
58241
58242#ifndef SQLITE_OMIT_AUTOVACUUM
58243  pBt->bDoTruncate = 0;
58244#endif
58245  if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
58246    /* If there are other active statements that belong to this database
58247    ** handle, downgrade to a read-only transaction. The other statements
58248    ** may still be reading from the database.  */
58249    downgradeAllSharedCacheTableLocks(p);
58250    p->inTrans = TRANS_READ;
58251  }else{
58252    /* If the handle had any kind of transaction open, decrement the
58253    ** transaction count of the shared btree. If the transaction count
58254    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
58255    ** call below will unlock the pager.  */
58256    if( p->inTrans!=TRANS_NONE ){
58257      clearAllSharedCacheTableLocks(p);
58258      pBt->nTransaction--;
58259      if( 0==pBt->nTransaction ){
58260        pBt->inTransaction = TRANS_NONE;
58261      }
58262    }
58263
58264    /* Set the current transaction state to TRANS_NONE and unlock the
58265    ** pager if this call closed the only read or write transaction.  */
58266    p->inTrans = TRANS_NONE;
58267    unlockBtreeIfUnused(pBt);
58268  }
58269
58270  btreeIntegrity(p);
58271}
58272
58273/*
58274** Commit the transaction currently in progress.
58275**
58276** This routine implements the second phase of a 2-phase commit.  The
58277** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
58278** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
58279** routine did all the work of writing information out to disk and flushing the
58280** contents so that they are written onto the disk platter.  All this
58281** routine has to do is delete or truncate or zero the header in the
58282** the rollback journal (which causes the transaction to commit) and
58283** drop locks.
58284**
58285** Normally, if an error occurs while the pager layer is attempting to
58286** finalize the underlying journal file, this function returns an error and
58287** the upper layer will attempt a rollback. However, if the second argument
58288** is non-zero then this b-tree transaction is part of a multi-file
58289** transaction. In this case, the transaction has already been committed
58290** (by deleting a master journal file) and the caller will ignore this
58291** functions return code. So, even if an error occurs in the pager layer,
58292** reset the b-tree objects internal state to indicate that the write
58293** transaction has been closed. This is quite safe, as the pager will have
58294** transitioned to the error state.
58295**
58296** This will release the write lock on the database file.  If there
58297** are no active cursors, it also releases the read lock.
58298*/
58299SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
58300
58301  if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
58302  sqlite3BtreeEnter(p);
58303  btreeIntegrity(p);
58304
58305  /* If the handle has a write-transaction open, commit the shared-btrees
58306  ** transaction and set the shared state to TRANS_READ.
58307  */
58308  if( p->inTrans==TRANS_WRITE ){
58309    int rc;
58310    BtShared *pBt = p->pBt;
58311    assert( pBt->inTransaction==TRANS_WRITE );
58312    assert( pBt->nTransaction>0 );
58313    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
58314    if( rc!=SQLITE_OK && bCleanup==0 ){
58315      sqlite3BtreeLeave(p);
58316      return rc;
58317    }
58318    p->iDataVersion--;  /* Compensate for pPager->iDataVersion++; */
58319    pBt->inTransaction = TRANS_READ;
58320    btreeClearHasContent(pBt);
58321  }
58322
58323  btreeEndTransaction(p);
58324  sqlite3BtreeLeave(p);
58325  return SQLITE_OK;
58326}
58327
58328/*
58329** Do both phases of a commit.
58330*/
58331SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
58332  int rc;
58333  sqlite3BtreeEnter(p);
58334  rc = sqlite3BtreeCommitPhaseOne(p, 0);
58335  if( rc==SQLITE_OK ){
58336    rc = sqlite3BtreeCommitPhaseTwo(p, 0);
58337  }
58338  sqlite3BtreeLeave(p);
58339  return rc;
58340}
58341
58342/*
58343** This routine sets the state to CURSOR_FAULT and the error
58344** code to errCode for every cursor on any BtShared that pBtree
58345** references.  Or if the writeOnly flag is set to 1, then only
58346** trip write cursors and leave read cursors unchanged.
58347**
58348** Every cursor is a candidate to be tripped, including cursors
58349** that belong to other database connections that happen to be
58350** sharing the cache with pBtree.
58351**
58352** This routine gets called when a rollback occurs. If the writeOnly
58353** flag is true, then only write-cursors need be tripped - read-only
58354** cursors save their current positions so that they may continue
58355** following the rollback. Or, if writeOnly is false, all cursors are
58356** tripped. In general, writeOnly is false if the transaction being
58357** rolled back modified the database schema. In this case b-tree root
58358** pages may be moved or deleted from the database altogether, making
58359** it unsafe for read cursors to continue.
58360**
58361** If the writeOnly flag is true and an error is encountered while
58362** saving the current position of a read-only cursor, all cursors,
58363** including all read-cursors are tripped.
58364**
58365** SQLITE_OK is returned if successful, or if an error occurs while
58366** saving a cursor position, an SQLite error code.
58367*/
58368SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
58369  BtCursor *p;
58370  int rc = SQLITE_OK;
58371
58372  assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
58373  if( pBtree ){
58374    sqlite3BtreeEnter(pBtree);
58375    for(p=pBtree->pBt->pCursor; p; p=p->pNext){
58376      int i;
58377      if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
58378        if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
58379          rc = saveCursorPosition(p);
58380          if( rc!=SQLITE_OK ){
58381            (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
58382            break;
58383          }
58384        }
58385      }else{
58386        sqlite3BtreeClearCursor(p);
58387        p->eState = CURSOR_FAULT;
58388        p->skipNext = errCode;
58389      }
58390      for(i=0; i<=p->iPage; i++){
58391        releasePage(p->apPage[i]);
58392        p->apPage[i] = 0;
58393      }
58394    }
58395    sqlite3BtreeLeave(pBtree);
58396  }
58397  return rc;
58398}
58399
58400/*
58401** Rollback the transaction in progress.
58402**
58403** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
58404** Only write cursors are tripped if writeOnly is true but all cursors are
58405** tripped if writeOnly is false.  Any attempt to use
58406** a tripped cursor will result in an error.
58407**
58408** This will release the write lock on the database file.  If there
58409** are no active cursors, it also releases the read lock.
58410*/
58411SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
58412  int rc;
58413  BtShared *pBt = p->pBt;
58414  MemPage *pPage1;
58415
58416  assert( writeOnly==1 || writeOnly==0 );
58417  assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
58418  sqlite3BtreeEnter(p);
58419  if( tripCode==SQLITE_OK ){
58420    rc = tripCode = saveAllCursors(pBt, 0, 0);
58421    if( rc ) writeOnly = 0;
58422  }else{
58423    rc = SQLITE_OK;
58424  }
58425  if( tripCode ){
58426    int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
58427    assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
58428    if( rc2!=SQLITE_OK ) rc = rc2;
58429  }
58430  btreeIntegrity(p);
58431
58432  if( p->inTrans==TRANS_WRITE ){
58433    int rc2;
58434
58435    assert( TRANS_WRITE==pBt->inTransaction );
58436    rc2 = sqlite3PagerRollback(pBt->pPager);
58437    if( rc2!=SQLITE_OK ){
58438      rc = rc2;
58439    }
58440
58441    /* The rollback may have destroyed the pPage1->aData value.  So
58442    ** call btreeGetPage() on page 1 again to make
58443    ** sure pPage1->aData is set correctly. */
58444    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
58445      int nPage = get4byte(28+(u8*)pPage1->aData);
58446      testcase( nPage==0 );
58447      if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
58448      testcase( pBt->nPage!=nPage );
58449      pBt->nPage = nPage;
58450      releasePage(pPage1);
58451    }
58452    assert( countValidCursors(pBt, 1)==0 );
58453    pBt->inTransaction = TRANS_READ;
58454    btreeClearHasContent(pBt);
58455  }
58456
58457  btreeEndTransaction(p);
58458  sqlite3BtreeLeave(p);
58459  return rc;
58460}
58461
58462/*
58463** Start a statement subtransaction. The subtransaction can be rolled
58464** back independently of the main transaction. You must start a transaction
58465** before starting a subtransaction. The subtransaction is ended automatically
58466** if the main transaction commits or rolls back.
58467**
58468** Statement subtransactions are used around individual SQL statements
58469** that are contained within a BEGIN...COMMIT block.  If a constraint
58470** error occurs within the statement, the effect of that one statement
58471** can be rolled back without having to rollback the entire transaction.
58472**
58473** A statement sub-transaction is implemented as an anonymous savepoint. The
58474** value passed as the second parameter is the total number of savepoints,
58475** including the new anonymous savepoint, open on the B-Tree. i.e. if there
58476** are no active savepoints and no other statement-transactions open,
58477** iStatement is 1. This anonymous savepoint can be released or rolled back
58478** using the sqlite3BtreeSavepoint() function.
58479*/
58480SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
58481  int rc;
58482  BtShared *pBt = p->pBt;
58483  sqlite3BtreeEnter(p);
58484  assert( p->inTrans==TRANS_WRITE );
58485  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
58486  assert( iStatement>0 );
58487  assert( iStatement>p->db->nSavepoint );
58488  assert( pBt->inTransaction==TRANS_WRITE );
58489  /* At the pager level, a statement transaction is a savepoint with
58490  ** an index greater than all savepoints created explicitly using
58491  ** SQL statements. It is illegal to open, release or rollback any
58492  ** such savepoints while the statement transaction savepoint is active.
58493  */
58494  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
58495  sqlite3BtreeLeave(p);
58496  return rc;
58497}
58498
58499/*
58500** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
58501** or SAVEPOINT_RELEASE. This function either releases or rolls back the
58502** savepoint identified by parameter iSavepoint, depending on the value
58503** of op.
58504**
58505** Normally, iSavepoint is greater than or equal to zero. However, if op is
58506** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
58507** contents of the entire transaction are rolled back. This is different
58508** from a normal transaction rollback, as no locks are released and the
58509** transaction remains open.
58510*/
58511SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
58512  int rc = SQLITE_OK;
58513  if( p && p->inTrans==TRANS_WRITE ){
58514    BtShared *pBt = p->pBt;
58515    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
58516    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
58517    sqlite3BtreeEnter(p);
58518    rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
58519    if( rc==SQLITE_OK ){
58520      if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
58521        pBt->nPage = 0;
58522      }
58523      rc = newDatabase(pBt);
58524      pBt->nPage = get4byte(28 + pBt->pPage1->aData);
58525
58526      /* The database size was written into the offset 28 of the header
58527      ** when the transaction started, so we know that the value at offset
58528      ** 28 is nonzero. */
58529      assert( pBt->nPage>0 );
58530    }
58531    sqlite3BtreeLeave(p);
58532  }
58533  return rc;
58534}
58535
58536/*
58537** Create a new cursor for the BTree whose root is on the page
58538** iTable. If a read-only cursor is requested, it is assumed that
58539** the caller already has at least a read-only transaction open
58540** on the database already. If a write-cursor is requested, then
58541** the caller is assumed to have an open write transaction.
58542**
58543** If wrFlag==0, then the cursor can only be used for reading.
58544** If wrFlag==1, then the cursor can be used for reading or for
58545** writing if other conditions for writing are also met.  These
58546** are the conditions that must be met in order for writing to
58547** be allowed:
58548**
58549** 1:  The cursor must have been opened with wrFlag==1
58550**
58551** 2:  Other database connections that share the same pager cache
58552**     but which are not in the READ_UNCOMMITTED state may not have
58553**     cursors open with wrFlag==0 on the same table.  Otherwise
58554**     the changes made by this write cursor would be visible to
58555**     the read cursors in the other database connection.
58556**
58557** 3:  The database must be writable (not on read-only media)
58558**
58559** 4:  There must be an active transaction.
58560**
58561** No checking is done to make sure that page iTable really is the
58562** root page of a b-tree.  If it is not, then the cursor acquired
58563** will not work correctly.
58564**
58565** It is assumed that the sqlite3BtreeCursorZero() has been called
58566** on pCur to initialize the memory space prior to invoking this routine.
58567*/
58568static int btreeCursor(
58569  Btree *p,                              /* The btree */
58570  int iTable,                            /* Root page of table to open */
58571  int wrFlag,                            /* 1 to write. 0 read-only */
58572  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
58573  BtCursor *pCur                         /* Space for new cursor */
58574){
58575  BtShared *pBt = p->pBt;                /* Shared b-tree handle */
58576  BtCursor *pX;                          /* Looping over other all cursors */
58577
58578  assert( sqlite3BtreeHoldsMutex(p) );
58579  assert( wrFlag==0 || wrFlag==1 );
58580
58581  /* The following assert statements verify that if this is a sharable
58582  ** b-tree database, the connection is holding the required table locks,
58583  ** and that no other connection has any open cursor that conflicts with
58584  ** this lock.  */
58585  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
58586  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
58587
58588  /* Assert that the caller has opened the required transaction. */
58589  assert( p->inTrans>TRANS_NONE );
58590  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
58591  assert( pBt->pPage1 && pBt->pPage1->aData );
58592  assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
58593
58594  if( wrFlag ){
58595    allocateTempSpace(pBt);
58596    if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM;
58597  }
58598  if( iTable==1 && btreePagecount(pBt)==0 ){
58599    assert( wrFlag==0 );
58600    iTable = 0;
58601  }
58602
58603  /* Now that no other errors can occur, finish filling in the BtCursor
58604  ** variables and link the cursor into the BtShared list.  */
58605  pCur->pgnoRoot = (Pgno)iTable;
58606  pCur->iPage = -1;
58607  pCur->pKeyInfo = pKeyInfo;
58608  pCur->pBtree = p;
58609  pCur->pBt = pBt;
58610  assert( wrFlag==0 || wrFlag==BTCF_WriteFlag );
58611  pCur->curFlags = wrFlag;
58612  pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
58613  /* If there are two or more cursors on the same btree, then all such
58614  ** cursors *must* have the BTCF_Multiple flag set. */
58615  for(pX=pBt->pCursor; pX; pX=pX->pNext){
58616    if( pX->pgnoRoot==(Pgno)iTable ){
58617      pX->curFlags |= BTCF_Multiple;
58618      pCur->curFlags |= BTCF_Multiple;
58619    }
58620  }
58621  pCur->pNext = pBt->pCursor;
58622  pBt->pCursor = pCur;
58623  pCur->eState = CURSOR_INVALID;
58624  return SQLITE_OK;
58625}
58626SQLITE_PRIVATE int sqlite3BtreeCursor(
58627  Btree *p,                                   /* The btree */
58628  int iTable,                                 /* Root page of table to open */
58629  int wrFlag,                                 /* 1 to write. 0 read-only */
58630  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
58631  BtCursor *pCur                              /* Write new cursor here */
58632){
58633  int rc;
58634  if( iTable<1 ){
58635    rc = SQLITE_CORRUPT_BKPT;
58636  }else{
58637    sqlite3BtreeEnter(p);
58638    rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
58639    sqlite3BtreeLeave(p);
58640  }
58641  return rc;
58642}
58643
58644/*
58645** Return the size of a BtCursor object in bytes.
58646**
58647** This interfaces is needed so that users of cursors can preallocate
58648** sufficient storage to hold a cursor.  The BtCursor object is opaque
58649** to users so they cannot do the sizeof() themselves - they must call
58650** this routine.
58651*/
58652SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
58653  return ROUND8(sizeof(BtCursor));
58654}
58655
58656/*
58657** Initialize memory that will be converted into a BtCursor object.
58658**
58659** The simple approach here would be to memset() the entire object
58660** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
58661** do not need to be zeroed and they are large, so we can save a lot
58662** of run-time by skipping the initialization of those elements.
58663*/
58664SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
58665  memset(p, 0, offsetof(BtCursor, iPage));
58666}
58667
58668/*
58669** Close a cursor.  The read lock on the database file is released
58670** when the last cursor is closed.
58671*/
58672SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
58673  Btree *pBtree = pCur->pBtree;
58674  if( pBtree ){
58675    int i;
58676    BtShared *pBt = pCur->pBt;
58677    sqlite3BtreeEnter(pBtree);
58678    sqlite3BtreeClearCursor(pCur);
58679    assert( pBt->pCursor!=0 );
58680    if( pBt->pCursor==pCur ){
58681      pBt->pCursor = pCur->pNext;
58682    }else{
58683      BtCursor *pPrev = pBt->pCursor;
58684      do{
58685        if( pPrev->pNext==pCur ){
58686          pPrev->pNext = pCur->pNext;
58687          break;
58688        }
58689        pPrev = pPrev->pNext;
58690      }while( ALWAYS(pPrev) );
58691    }
58692    for(i=0; i<=pCur->iPage; i++){
58693      releasePage(pCur->apPage[i]);
58694    }
58695    unlockBtreeIfUnused(pBt);
58696    sqlite3_free(pCur->aOverflow);
58697    /* sqlite3_free(pCur); */
58698    sqlite3BtreeLeave(pBtree);
58699  }
58700  return SQLITE_OK;
58701}
58702
58703/*
58704** Make sure the BtCursor* given in the argument has a valid
58705** BtCursor.info structure.  If it is not already valid, call
58706** btreeParseCell() to fill it in.
58707**
58708** BtCursor.info is a cache of the information in the current cell.
58709** Using this cache reduces the number of calls to btreeParseCell().
58710*/
58711#ifndef NDEBUG
58712  static void assertCellInfo(BtCursor *pCur){
58713    CellInfo info;
58714    int iPage = pCur->iPage;
58715    memset(&info, 0, sizeof(info));
58716    btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
58717    assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
58718  }
58719#else
58720  #define assertCellInfo(x)
58721#endif
58722static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
58723  if( pCur->info.nSize==0 ){
58724    int iPage = pCur->iPage;
58725    pCur->curFlags |= BTCF_ValidNKey;
58726    btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
58727  }else{
58728    assertCellInfo(pCur);
58729  }
58730}
58731
58732#ifndef NDEBUG  /* The next routine used only within assert() statements */
58733/*
58734** Return true if the given BtCursor is valid.  A valid cursor is one
58735** that is currently pointing to a row in a (non-empty) table.
58736** This is a verification routine is used only within assert() statements.
58737*/
58738SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
58739  return pCur && pCur->eState==CURSOR_VALID;
58740}
58741#endif /* NDEBUG */
58742
58743/*
58744** Set *pSize to the size of the buffer needed to hold the value of
58745** the key for the current entry.  If the cursor is not pointing
58746** to a valid entry, *pSize is set to 0.
58747**
58748** For a table with the INTKEY flag set, this routine returns the key
58749** itself, not the number of bytes in the key.
58750**
58751** The caller must position the cursor prior to invoking this routine.
58752**
58753** This routine cannot fail.  It always returns SQLITE_OK.
58754*/
58755SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
58756  assert( cursorHoldsMutex(pCur) );
58757  assert( pCur->eState==CURSOR_VALID );
58758  getCellInfo(pCur);
58759  *pSize = pCur->info.nKey;
58760  return SQLITE_OK;
58761}
58762
58763/*
58764** Set *pSize to the number of bytes of data in the entry the
58765** cursor currently points to.
58766**
58767** The caller must guarantee that the cursor is pointing to a non-NULL
58768** valid entry.  In other words, the calling procedure must guarantee
58769** that the cursor has Cursor.eState==CURSOR_VALID.
58770**
58771** Failure is not possible.  This function always returns SQLITE_OK.
58772** It might just as well be a procedure (returning void) but we continue
58773** to return an integer result code for historical reasons.
58774*/
58775SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
58776  assert( cursorHoldsMutex(pCur) );
58777  assert( pCur->eState==CURSOR_VALID );
58778  assert( pCur->iPage>=0 );
58779  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
58780  assert( pCur->apPage[pCur->iPage]->intKeyLeaf==1 );
58781  getCellInfo(pCur);
58782  *pSize = pCur->info.nPayload;
58783  return SQLITE_OK;
58784}
58785
58786/*
58787** Given the page number of an overflow page in the database (parameter
58788** ovfl), this function finds the page number of the next page in the
58789** linked list of overflow pages. If possible, it uses the auto-vacuum
58790** pointer-map data instead of reading the content of page ovfl to do so.
58791**
58792** If an error occurs an SQLite error code is returned. Otherwise:
58793**
58794** The page number of the next overflow page in the linked list is
58795** written to *pPgnoNext. If page ovfl is the last page in its linked
58796** list, *pPgnoNext is set to zero.
58797**
58798** If ppPage is not NULL, and a reference to the MemPage object corresponding
58799** to page number pOvfl was obtained, then *ppPage is set to point to that
58800** reference. It is the responsibility of the caller to call releasePage()
58801** on *ppPage to free the reference. In no reference was obtained (because
58802** the pointer-map was used to obtain the value for *pPgnoNext), then
58803** *ppPage is set to zero.
58804*/
58805static int getOverflowPage(
58806  BtShared *pBt,               /* The database file */
58807  Pgno ovfl,                   /* Current overflow page number */
58808  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
58809  Pgno *pPgnoNext              /* OUT: Next overflow page number */
58810){
58811  Pgno next = 0;
58812  MemPage *pPage = 0;
58813  int rc = SQLITE_OK;
58814
58815  assert( sqlite3_mutex_held(pBt->mutex) );
58816  assert(pPgnoNext);
58817
58818#ifndef SQLITE_OMIT_AUTOVACUUM
58819  /* Try to find the next page in the overflow list using the
58820  ** autovacuum pointer-map pages. Guess that the next page in
58821  ** the overflow list is page number (ovfl+1). If that guess turns
58822  ** out to be wrong, fall back to loading the data of page
58823  ** number ovfl to determine the next page number.
58824  */
58825  if( pBt->autoVacuum ){
58826    Pgno pgno;
58827    Pgno iGuess = ovfl+1;
58828    u8 eType;
58829
58830    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
58831      iGuess++;
58832    }
58833
58834    if( iGuess<=btreePagecount(pBt) ){
58835      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
58836      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
58837        next = iGuess;
58838        rc = SQLITE_DONE;
58839      }
58840    }
58841  }
58842#endif
58843
58844  assert( next==0 || rc==SQLITE_DONE );
58845  if( rc==SQLITE_OK ){
58846    rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
58847    assert( rc==SQLITE_OK || pPage==0 );
58848    if( rc==SQLITE_OK ){
58849      next = get4byte(pPage->aData);
58850    }
58851  }
58852
58853  *pPgnoNext = next;
58854  if( ppPage ){
58855    *ppPage = pPage;
58856  }else{
58857    releasePage(pPage);
58858  }
58859  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
58860}
58861
58862/*
58863** Copy data from a buffer to a page, or from a page to a buffer.
58864**
58865** pPayload is a pointer to data stored on database page pDbPage.
58866** If argument eOp is false, then nByte bytes of data are copied
58867** from pPayload to the buffer pointed at by pBuf. If eOp is true,
58868** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
58869** of data are copied from the buffer pBuf to pPayload.
58870**
58871** SQLITE_OK is returned on success, otherwise an error code.
58872*/
58873static int copyPayload(
58874  void *pPayload,           /* Pointer to page data */
58875  void *pBuf,               /* Pointer to buffer */
58876  int nByte,                /* Number of bytes to copy */
58877  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
58878  DbPage *pDbPage           /* Page containing pPayload */
58879){
58880  if( eOp ){
58881    /* Copy data from buffer to page (a write operation) */
58882    int rc = sqlite3PagerWrite(pDbPage);
58883    if( rc!=SQLITE_OK ){
58884      return rc;
58885    }
58886    memcpy(pPayload, pBuf, nByte);
58887  }else{
58888    /* Copy data from page to buffer (a read operation) */
58889    memcpy(pBuf, pPayload, nByte);
58890  }
58891  return SQLITE_OK;
58892}
58893
58894/*
58895** This function is used to read or overwrite payload information
58896** for the entry that the pCur cursor is pointing to. The eOp
58897** argument is interpreted as follows:
58898**
58899**   0: The operation is a read. Populate the overflow cache.
58900**   1: The operation is a write. Populate the overflow cache.
58901**   2: The operation is a read. Do not populate the overflow cache.
58902**
58903** A total of "amt" bytes are read or written beginning at "offset".
58904** Data is read to or from the buffer pBuf.
58905**
58906** The content being read or written might appear on the main page
58907** or be scattered out on multiple overflow pages.
58908**
58909** If the current cursor entry uses one or more overflow pages and the
58910** eOp argument is not 2, this function may allocate space for and lazily
58911** populates the overflow page-list cache array (BtCursor.aOverflow).
58912** Subsequent calls use this cache to make seeking to the supplied offset
58913** more efficient.
58914**
58915** Once an overflow page-list cache has been allocated, it may be
58916** invalidated if some other cursor writes to the same table, or if
58917** the cursor is moved to a different row. Additionally, in auto-vacuum
58918** mode, the following events may invalidate an overflow page-list cache.
58919**
58920**   * An incremental vacuum,
58921**   * A commit in auto_vacuum="full" mode,
58922**   * Creating a table (may require moving an overflow page).
58923*/
58924static int accessPayload(
58925  BtCursor *pCur,      /* Cursor pointing to entry to read from */
58926  u32 offset,          /* Begin reading this far into payload */
58927  u32 amt,             /* Read this many bytes */
58928  unsigned char *pBuf, /* Write the bytes into this buffer */
58929  int eOp              /* zero to read. non-zero to write. */
58930){
58931  unsigned char *aPayload;
58932  int rc = SQLITE_OK;
58933  int iIdx = 0;
58934  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
58935  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
58936#ifdef SQLITE_DIRECT_OVERFLOW_READ
58937  unsigned char * const pBufStart = pBuf;
58938  int bEnd;                                 /* True if reading to end of data */
58939#endif
58940
58941  assert( pPage );
58942  assert( pCur->eState==CURSOR_VALID );
58943  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
58944  assert( cursorHoldsMutex(pCur) );
58945  assert( eOp!=2 || offset==0 );    /* Always start from beginning for eOp==2 */
58946
58947  getCellInfo(pCur);
58948  aPayload = pCur->info.pPayload;
58949#ifdef SQLITE_DIRECT_OVERFLOW_READ
58950  bEnd = offset+amt==pCur->info.nPayload;
58951#endif
58952  assert( offset+amt <= pCur->info.nPayload );
58953
58954  if( &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ){
58955    /* Trying to read or write past the end of the data is an error */
58956    return SQLITE_CORRUPT_BKPT;
58957  }
58958
58959  /* Check if data must be read/written to/from the btree page itself. */
58960  if( offset<pCur->info.nLocal ){
58961    int a = amt;
58962    if( a+offset>pCur->info.nLocal ){
58963      a = pCur->info.nLocal - offset;
58964    }
58965    rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
58966    offset = 0;
58967    pBuf += a;
58968    amt -= a;
58969  }else{
58970    offset -= pCur->info.nLocal;
58971  }
58972
58973
58974  if( rc==SQLITE_OK && amt>0 ){
58975    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
58976    Pgno nextPage;
58977
58978    nextPage = get4byte(&aPayload[pCur->info.nLocal]);
58979
58980    /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
58981    ** Except, do not allocate aOverflow[] for eOp==2.
58982    **
58983    ** The aOverflow[] array is sized at one entry for each overflow page
58984    ** in the overflow chain. The page number of the first overflow page is
58985    ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
58986    ** means "not yet known" (the cache is lazily populated).
58987    */
58988    if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
58989      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
58990      if( nOvfl>pCur->nOvflAlloc ){
58991        Pgno *aNew = (Pgno*)sqlite3Realloc(
58992            pCur->aOverflow, nOvfl*2*sizeof(Pgno)
58993        );
58994        if( aNew==0 ){
58995          rc = SQLITE_NOMEM;
58996        }else{
58997          pCur->nOvflAlloc = nOvfl*2;
58998          pCur->aOverflow = aNew;
58999        }
59000      }
59001      if( rc==SQLITE_OK ){
59002        memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
59003        pCur->curFlags |= BTCF_ValidOvfl;
59004      }
59005    }
59006
59007    /* If the overflow page-list cache has been allocated and the
59008    ** entry for the first required overflow page is valid, skip
59009    ** directly to it.
59010    */
59011    if( (pCur->curFlags & BTCF_ValidOvfl)!=0
59012     && pCur->aOverflow[offset/ovflSize]
59013    ){
59014      iIdx = (offset/ovflSize);
59015      nextPage = pCur->aOverflow[iIdx];
59016      offset = (offset%ovflSize);
59017    }
59018
59019    for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
59020
59021      /* If required, populate the overflow page-list cache. */
59022      if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
59023        assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
59024        pCur->aOverflow[iIdx] = nextPage;
59025      }
59026
59027      if( offset>=ovflSize ){
59028        /* The only reason to read this page is to obtain the page
59029        ** number for the next page in the overflow chain. The page
59030        ** data is not required. So first try to lookup the overflow
59031        ** page-list cache, if any, then fall back to the getOverflowPage()
59032        ** function.
59033        **
59034        ** Note that the aOverflow[] array must be allocated because eOp!=2
59035        ** here.  If eOp==2, then offset==0 and this branch is never taken.
59036        */
59037        assert( eOp!=2 );
59038        assert( pCur->curFlags & BTCF_ValidOvfl );
59039        assert( pCur->pBtree->db==pBt->db );
59040        if( pCur->aOverflow[iIdx+1] ){
59041          nextPage = pCur->aOverflow[iIdx+1];
59042        }else{
59043          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
59044        }
59045        offset -= ovflSize;
59046      }else{
59047        /* Need to read this page properly. It contains some of the
59048        ** range of data that is being read (eOp==0) or written (eOp!=0).
59049        */
59050#ifdef SQLITE_DIRECT_OVERFLOW_READ
59051        sqlite3_file *fd;
59052#endif
59053        int a = amt;
59054        if( a + offset > ovflSize ){
59055          a = ovflSize - offset;
59056        }
59057
59058#ifdef SQLITE_DIRECT_OVERFLOW_READ
59059        /* If all the following are true:
59060        **
59061        **   1) this is a read operation, and
59062        **   2) data is required from the start of this overflow page, and
59063        **   3) the database is file-backed, and
59064        **   4) there is no open write-transaction, and
59065        **   5) the database is not a WAL database,
59066        **   6) all data from the page is being read.
59067        **   7) at least 4 bytes have already been read into the output buffer
59068        **
59069        ** then data can be read directly from the database file into the
59070        ** output buffer, bypassing the page-cache altogether. This speeds
59071        ** up loading large records that span many overflow pages.
59072        */
59073        if( (eOp&0x01)==0                                      /* (1) */
59074         && offset==0                                          /* (2) */
59075         && (bEnd || a==ovflSize)                              /* (6) */
59076         && pBt->inTransaction==TRANS_READ                     /* (4) */
59077         && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
59078         && pBt->pPage1->aData[19]==0x01                       /* (5) */
59079         && &pBuf[-4]>=pBufStart                               /* (7) */
59080        ){
59081          u8 aSave[4];
59082          u8 *aWrite = &pBuf[-4];
59083          assert( aWrite>=pBufStart );                         /* hence (7) */
59084          memcpy(aSave, aWrite, 4);
59085          rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
59086          nextPage = get4byte(aWrite);
59087          memcpy(aWrite, aSave, 4);
59088        }else
59089#endif
59090
59091        {
59092          DbPage *pDbPage;
59093          rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
59094              ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
59095          );
59096          if( rc==SQLITE_OK ){
59097            aPayload = sqlite3PagerGetData(pDbPage);
59098            nextPage = get4byte(aPayload);
59099            rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
59100            sqlite3PagerUnref(pDbPage);
59101            offset = 0;
59102          }
59103        }
59104        amt -= a;
59105        pBuf += a;
59106      }
59107    }
59108  }
59109
59110  if( rc==SQLITE_OK && amt>0 ){
59111    return SQLITE_CORRUPT_BKPT;
59112  }
59113  return rc;
59114}
59115
59116/*
59117** Read part of the key associated with cursor pCur.  Exactly
59118** "amt" bytes will be transferred into pBuf[].  The transfer
59119** begins at "offset".
59120**
59121** The caller must ensure that pCur is pointing to a valid row
59122** in the table.
59123**
59124** Return SQLITE_OK on success or an error code if anything goes
59125** wrong.  An error is returned if "offset+amt" is larger than
59126** the available payload.
59127*/
59128SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
59129  assert( cursorHoldsMutex(pCur) );
59130  assert( pCur->eState==CURSOR_VALID );
59131  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
59132  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
59133  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
59134}
59135
59136/*
59137** Read part of the data associated with cursor pCur.  Exactly
59138** "amt" bytes will be transfered into pBuf[].  The transfer
59139** begins at "offset".
59140**
59141** Return SQLITE_OK on success or an error code if anything goes
59142** wrong.  An error is returned if "offset+amt" is larger than
59143** the available payload.
59144*/
59145SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
59146  int rc;
59147
59148#ifndef SQLITE_OMIT_INCRBLOB
59149  if ( pCur->eState==CURSOR_INVALID ){
59150    return SQLITE_ABORT;
59151  }
59152#endif
59153
59154  assert( cursorHoldsMutex(pCur) );
59155  rc = restoreCursorPosition(pCur);
59156  if( rc==SQLITE_OK ){
59157    assert( pCur->eState==CURSOR_VALID );
59158    assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
59159    assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
59160    rc = accessPayload(pCur, offset, amt, pBuf, 0);
59161  }
59162  return rc;
59163}
59164
59165/*
59166** Return a pointer to payload information from the entry that the
59167** pCur cursor is pointing to.  The pointer is to the beginning of
59168** the key if index btrees (pPage->intKey==0) and is the data for
59169** table btrees (pPage->intKey==1). The number of bytes of available
59170** key/data is written into *pAmt.  If *pAmt==0, then the value
59171** returned will not be a valid pointer.
59172**
59173** This routine is an optimization.  It is common for the entire key
59174** and data to fit on the local page and for there to be no overflow
59175** pages.  When that is so, this routine can be used to access the
59176** key and data without making a copy.  If the key and/or data spills
59177** onto overflow pages, then accessPayload() must be used to reassemble
59178** the key/data and copy it into a preallocated buffer.
59179**
59180** The pointer returned by this routine looks directly into the cached
59181** page of the database.  The data might change or move the next time
59182** any btree routine is called.
59183*/
59184static const void *fetchPayload(
59185  BtCursor *pCur,      /* Cursor pointing to entry to read from */
59186  u32 *pAmt            /* Write the number of available bytes here */
59187){
59188  u32 amt;
59189  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
59190  assert( pCur->eState==CURSOR_VALID );
59191  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
59192  assert( cursorHoldsMutex(pCur) );
59193  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
59194  assert( pCur->info.nSize>0 );
59195  assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB );
59196  assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB);
59197  amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload);
59198  if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
59199  *pAmt = amt;
59200  return (void*)pCur->info.pPayload;
59201}
59202
59203
59204/*
59205** For the entry that cursor pCur is point to, return as
59206** many bytes of the key or data as are available on the local
59207** b-tree page.  Write the number of available bytes into *pAmt.
59208**
59209** The pointer returned is ephemeral.  The key/data may move
59210** or be destroyed on the next call to any Btree routine,
59211** including calls from other threads against the same cache.
59212** Hence, a mutex on the BtShared should be held prior to calling
59213** this routine.
59214**
59215** These routines is used to get quick access to key and data
59216** in the common case where no overflow pages are used.
59217*/
59218SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
59219  return fetchPayload(pCur, pAmt);
59220}
59221SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
59222  return fetchPayload(pCur, pAmt);
59223}
59224
59225
59226/*
59227** Move the cursor down to a new child page.  The newPgno argument is the
59228** page number of the child page to move to.
59229**
59230** This function returns SQLITE_CORRUPT if the page-header flags field of
59231** the new child page does not match the flags field of the parent (i.e.
59232** if an intkey page appears to be the parent of a non-intkey page, or
59233** vice-versa).
59234*/
59235static int moveToChild(BtCursor *pCur, u32 newPgno){
59236  BtShared *pBt = pCur->pBt;
59237
59238  assert( cursorHoldsMutex(pCur) );
59239  assert( pCur->eState==CURSOR_VALID );
59240  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
59241  assert( pCur->iPage>=0 );
59242  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
59243    return SQLITE_CORRUPT_BKPT;
59244  }
59245  pCur->info.nSize = 0;
59246  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
59247  pCur->iPage++;
59248  pCur->aiIdx[pCur->iPage] = 0;
59249  return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage],
59250                        pCur, pCur->curPagerFlags);
59251}
59252
59253#if SQLITE_DEBUG
59254/*
59255** Page pParent is an internal (non-leaf) tree page. This function
59256** asserts that page number iChild is the left-child if the iIdx'th
59257** cell in page pParent. Or, if iIdx is equal to the total number of
59258** cells in pParent, that page number iChild is the right-child of
59259** the page.
59260*/
59261static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
59262  if( CORRUPT_DB ) return;  /* The conditions tested below might not be true
59263                            ** in a corrupt database */
59264  assert( iIdx<=pParent->nCell );
59265  if( iIdx==pParent->nCell ){
59266    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
59267  }else{
59268    assert( get4byte(findCell(pParent, iIdx))==iChild );
59269  }
59270}
59271#else
59272#  define assertParentIndex(x,y,z)
59273#endif
59274
59275/*
59276** Move the cursor up to the parent page.
59277**
59278** pCur->idx is set to the cell index that contains the pointer
59279** to the page we are coming from.  If we are coming from the
59280** right-most child page then pCur->idx is set to one more than
59281** the largest cell index.
59282*/
59283static void moveToParent(BtCursor *pCur){
59284  assert( cursorHoldsMutex(pCur) );
59285  assert( pCur->eState==CURSOR_VALID );
59286  assert( pCur->iPage>0 );
59287  assert( pCur->apPage[pCur->iPage] );
59288  assertParentIndex(
59289    pCur->apPage[pCur->iPage-1],
59290    pCur->aiIdx[pCur->iPage-1],
59291    pCur->apPage[pCur->iPage]->pgno
59292  );
59293  testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
59294  pCur->info.nSize = 0;
59295  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
59296  releasePageNotNull(pCur->apPage[pCur->iPage--]);
59297}
59298
59299/*
59300** Move the cursor to point to the root page of its b-tree structure.
59301**
59302** If the table has a virtual root page, then the cursor is moved to point
59303** to the virtual root page instead of the actual root page. A table has a
59304** virtual root page when the actual root page contains no cells and a
59305** single child page. This can only happen with the table rooted at page 1.
59306**
59307** If the b-tree structure is empty, the cursor state is set to
59308** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
59309** cell located on the root (or virtual root) page and the cursor state
59310** is set to CURSOR_VALID.
59311**
59312** If this function returns successfully, it may be assumed that the
59313** page-header flags indicate that the [virtual] root-page is the expected
59314** kind of b-tree page (i.e. if when opening the cursor the caller did not
59315** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
59316** indicating a table b-tree, or if the caller did specify a KeyInfo
59317** structure the flags byte is set to 0x02 or 0x0A, indicating an index
59318** b-tree).
59319*/
59320static int moveToRoot(BtCursor *pCur){
59321  MemPage *pRoot;
59322  int rc = SQLITE_OK;
59323
59324  assert( cursorHoldsMutex(pCur) );
59325  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
59326  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
59327  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
59328  if( pCur->eState>=CURSOR_REQUIRESEEK ){
59329    if( pCur->eState==CURSOR_FAULT ){
59330      assert( pCur->skipNext!=SQLITE_OK );
59331      return pCur->skipNext;
59332    }
59333    sqlite3BtreeClearCursor(pCur);
59334  }
59335
59336  if( pCur->iPage>=0 ){
59337    while( pCur->iPage ){
59338      assert( pCur->apPage[pCur->iPage]!=0 );
59339      releasePageNotNull(pCur->apPage[pCur->iPage--]);
59340    }
59341  }else if( pCur->pgnoRoot==0 ){
59342    pCur->eState = CURSOR_INVALID;
59343    return SQLITE_OK;
59344  }else{
59345    assert( pCur->iPage==(-1) );
59346    rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
59347                        0, pCur->curPagerFlags);
59348    if( rc!=SQLITE_OK ){
59349      pCur->eState = CURSOR_INVALID;
59350      return rc;
59351    }
59352    pCur->iPage = 0;
59353    pCur->curIntKey = pCur->apPage[0]->intKey;
59354  }
59355  pRoot = pCur->apPage[0];
59356  assert( pRoot->pgno==pCur->pgnoRoot );
59357
59358  /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
59359  ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
59360  ** NULL, the caller expects a table b-tree. If this is not the case,
59361  ** return an SQLITE_CORRUPT error.
59362  **
59363  ** Earlier versions of SQLite assumed that this test could not fail
59364  ** if the root page was already loaded when this function was called (i.e.
59365  ** if pCur->iPage>=0). But this is not so if the database is corrupted
59366  ** in such a way that page pRoot is linked into a second b-tree table
59367  ** (or the freelist).  */
59368  assert( pRoot->intKey==1 || pRoot->intKey==0 );
59369  if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
59370    return SQLITE_CORRUPT_BKPT;
59371  }
59372
59373  pCur->aiIdx[0] = 0;
59374  pCur->info.nSize = 0;
59375  pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
59376
59377  if( pRoot->nCell>0 ){
59378    pCur->eState = CURSOR_VALID;
59379  }else if( !pRoot->leaf ){
59380    Pgno subpage;
59381    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
59382    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
59383    pCur->eState = CURSOR_VALID;
59384    rc = moveToChild(pCur, subpage);
59385  }else{
59386    pCur->eState = CURSOR_INVALID;
59387  }
59388  return rc;
59389}
59390
59391/*
59392** Move the cursor down to the left-most leaf entry beneath the
59393** entry to which it is currently pointing.
59394**
59395** The left-most leaf is the one with the smallest key - the first
59396** in ascending order.
59397*/
59398static int moveToLeftmost(BtCursor *pCur){
59399  Pgno pgno;
59400  int rc = SQLITE_OK;
59401  MemPage *pPage;
59402
59403  assert( cursorHoldsMutex(pCur) );
59404  assert( pCur->eState==CURSOR_VALID );
59405  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
59406    assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
59407    pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
59408    rc = moveToChild(pCur, pgno);
59409  }
59410  return rc;
59411}
59412
59413/*
59414** Move the cursor down to the right-most leaf entry beneath the
59415** page to which it is currently pointing.  Notice the difference
59416** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
59417** finds the left-most entry beneath the *entry* whereas moveToRightmost()
59418** finds the right-most entry beneath the *page*.
59419**
59420** The right-most entry is the one with the largest key - the last
59421** key in ascending order.
59422*/
59423static int moveToRightmost(BtCursor *pCur){
59424  Pgno pgno;
59425  int rc = SQLITE_OK;
59426  MemPage *pPage = 0;
59427
59428  assert( cursorHoldsMutex(pCur) );
59429  assert( pCur->eState==CURSOR_VALID );
59430  while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
59431    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
59432    pCur->aiIdx[pCur->iPage] = pPage->nCell;
59433    rc = moveToChild(pCur, pgno);
59434    if( rc ) return rc;
59435  }
59436  pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
59437  assert( pCur->info.nSize==0 );
59438  assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
59439  return SQLITE_OK;
59440}
59441
59442/* Move the cursor to the first entry in the table.  Return SQLITE_OK
59443** on success.  Set *pRes to 0 if the cursor actually points to something
59444** or set *pRes to 1 if the table is empty.
59445*/
59446SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
59447  int rc;
59448
59449  assert( cursorHoldsMutex(pCur) );
59450  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
59451  rc = moveToRoot(pCur);
59452  if( rc==SQLITE_OK ){
59453    if( pCur->eState==CURSOR_INVALID ){
59454      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
59455      *pRes = 1;
59456    }else{
59457      assert( pCur->apPage[pCur->iPage]->nCell>0 );
59458      *pRes = 0;
59459      rc = moveToLeftmost(pCur);
59460    }
59461  }
59462  return rc;
59463}
59464
59465/* Move the cursor to the last entry in the table.  Return SQLITE_OK
59466** on success.  Set *pRes to 0 if the cursor actually points to something
59467** or set *pRes to 1 if the table is empty.
59468*/
59469SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
59470  int rc;
59471
59472  assert( cursorHoldsMutex(pCur) );
59473  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
59474
59475  /* If the cursor already points to the last entry, this is a no-op. */
59476  if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
59477#ifdef SQLITE_DEBUG
59478    /* This block serves to assert() that the cursor really does point
59479    ** to the last entry in the b-tree. */
59480    int ii;
59481    for(ii=0; ii<pCur->iPage; ii++){
59482      assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
59483    }
59484    assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
59485    assert( pCur->apPage[pCur->iPage]->leaf );
59486#endif
59487    return SQLITE_OK;
59488  }
59489
59490  rc = moveToRoot(pCur);
59491  if( rc==SQLITE_OK ){
59492    if( CURSOR_INVALID==pCur->eState ){
59493      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
59494      *pRes = 1;
59495    }else{
59496      assert( pCur->eState==CURSOR_VALID );
59497      *pRes = 0;
59498      rc = moveToRightmost(pCur);
59499      if( rc==SQLITE_OK ){
59500        pCur->curFlags |= BTCF_AtLast;
59501      }else{
59502        pCur->curFlags &= ~BTCF_AtLast;
59503      }
59504
59505    }
59506  }
59507  return rc;
59508}
59509
59510/* Move the cursor so that it points to an entry near the key
59511** specified by pIdxKey or intKey.   Return a success code.
59512**
59513** For INTKEY tables, the intKey parameter is used.  pIdxKey
59514** must be NULL.  For index tables, pIdxKey is used and intKey
59515** is ignored.
59516**
59517** If an exact match is not found, then the cursor is always
59518** left pointing at a leaf page which would hold the entry if it
59519** were present.  The cursor might point to an entry that comes
59520** before or after the key.
59521**
59522** An integer is written into *pRes which is the result of
59523** comparing the key with the entry to which the cursor is
59524** pointing.  The meaning of the integer written into
59525** *pRes is as follows:
59526**
59527**     *pRes<0      The cursor is left pointing at an entry that
59528**                  is smaller than intKey/pIdxKey or if the table is empty
59529**                  and the cursor is therefore left point to nothing.
59530**
59531**     *pRes==0     The cursor is left pointing at an entry that
59532**                  exactly matches intKey/pIdxKey.
59533**
59534**     *pRes>0      The cursor is left pointing at an entry that
59535**                  is larger than intKey/pIdxKey.
59536**
59537*/
59538SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
59539  BtCursor *pCur,          /* The cursor to be moved */
59540  UnpackedRecord *pIdxKey, /* Unpacked index key */
59541  i64 intKey,              /* The table key */
59542  int biasRight,           /* If true, bias the search to the high end */
59543  int *pRes                /* Write search results here */
59544){
59545  int rc;
59546  RecordCompare xRecordCompare;
59547
59548  assert( cursorHoldsMutex(pCur) );
59549  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
59550  assert( pRes );
59551  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
59552
59553  /* If the cursor is already positioned at the point we are trying
59554  ** to move to, then just return without doing any work */
59555  if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
59556   && pCur->curIntKey
59557  ){
59558    if( pCur->info.nKey==intKey ){
59559      *pRes = 0;
59560      return SQLITE_OK;
59561    }
59562    if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
59563      *pRes = -1;
59564      return SQLITE_OK;
59565    }
59566  }
59567
59568  if( pIdxKey ){
59569    xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
59570    pIdxKey->errCode = 0;
59571    assert( pIdxKey->default_rc==1
59572         || pIdxKey->default_rc==0
59573         || pIdxKey->default_rc==-1
59574    );
59575  }else{
59576    xRecordCompare = 0; /* All keys are integers */
59577  }
59578
59579  rc = moveToRoot(pCur);
59580  if( rc ){
59581    return rc;
59582  }
59583  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
59584  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
59585  assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
59586  if( pCur->eState==CURSOR_INVALID ){
59587    *pRes = -1;
59588    assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
59589    return SQLITE_OK;
59590  }
59591  assert( pCur->apPage[0]->intKey==pCur->curIntKey );
59592  assert( pCur->curIntKey || pIdxKey );
59593  for(;;){
59594    int lwr, upr, idx, c;
59595    Pgno chldPg;
59596    MemPage *pPage = pCur->apPage[pCur->iPage];
59597    u8 *pCell;                          /* Pointer to current cell in pPage */
59598
59599    /* pPage->nCell must be greater than zero. If this is the root-page
59600    ** the cursor would have been INVALID above and this for(;;) loop
59601    ** not run. If this is not the root-page, then the moveToChild() routine
59602    ** would have already detected db corruption. Similarly, pPage must
59603    ** be the right kind (index or table) of b-tree page. Otherwise
59604    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
59605    assert( pPage->nCell>0 );
59606    assert( pPage->intKey==(pIdxKey==0) );
59607    lwr = 0;
59608    upr = pPage->nCell-1;
59609    assert( biasRight==0 || biasRight==1 );
59610    idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
59611    pCur->aiIdx[pCur->iPage] = (u16)idx;
59612    if( xRecordCompare==0 ){
59613      for(;;){
59614        i64 nCellKey;
59615        pCell = findCellPastPtr(pPage, idx);
59616        if( pPage->intKeyLeaf ){
59617          while( 0x80 <= *(pCell++) ){
59618            if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
59619          }
59620        }
59621        getVarint(pCell, (u64*)&nCellKey);
59622        if( nCellKey<intKey ){
59623          lwr = idx+1;
59624          if( lwr>upr ){ c = -1; break; }
59625        }else if( nCellKey>intKey ){
59626          upr = idx-1;
59627          if( lwr>upr ){ c = +1; break; }
59628        }else{
59629          assert( nCellKey==intKey );
59630          pCur->curFlags |= BTCF_ValidNKey;
59631          pCur->info.nKey = nCellKey;
59632          pCur->aiIdx[pCur->iPage] = (u16)idx;
59633          if( !pPage->leaf ){
59634            lwr = idx;
59635            goto moveto_next_layer;
59636          }else{
59637            *pRes = 0;
59638            rc = SQLITE_OK;
59639            goto moveto_finish;
59640          }
59641        }
59642        assert( lwr+upr>=0 );
59643        idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
59644      }
59645    }else{
59646      for(;;){
59647        int nCell;  /* Size of the pCell cell in bytes */
59648        pCell = findCellPastPtr(pPage, idx);
59649
59650        /* The maximum supported page-size is 65536 bytes. This means that
59651        ** the maximum number of record bytes stored on an index B-Tree
59652        ** page is less than 16384 bytes and may be stored as a 2-byte
59653        ** varint. This information is used to attempt to avoid parsing
59654        ** the entire cell by checking for the cases where the record is
59655        ** stored entirely within the b-tree page by inspecting the first
59656        ** 2 bytes of the cell.
59657        */
59658        nCell = pCell[0];
59659        if( nCell<=pPage->max1bytePayload ){
59660          /* This branch runs if the record-size field of the cell is a
59661          ** single byte varint and the record fits entirely on the main
59662          ** b-tree page.  */
59663          testcase( pCell+nCell+1==pPage->aDataEnd );
59664          c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
59665        }else if( !(pCell[1] & 0x80)
59666          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
59667        ){
59668          /* The record-size field is a 2 byte varint and the record
59669          ** fits entirely on the main b-tree page.  */
59670          testcase( pCell+nCell+2==pPage->aDataEnd );
59671          c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
59672        }else{
59673          /* The record flows over onto one or more overflow pages. In
59674          ** this case the whole cell needs to be parsed, a buffer allocated
59675          ** and accessPayload() used to retrieve the record into the
59676          ** buffer before VdbeRecordCompare() can be called.
59677          **
59678          ** If the record is corrupt, the xRecordCompare routine may read
59679          ** up to two varints past the end of the buffer. An extra 18
59680          ** bytes of padding is allocated at the end of the buffer in
59681          ** case this happens.  */
59682          void *pCellKey;
59683          u8 * const pCellBody = pCell - pPage->childPtrSize;
59684          pPage->xParseCell(pPage, pCellBody, &pCur->info);
59685          nCell = (int)pCur->info.nKey;
59686          testcase( nCell<0 );   /* True if key size is 2^32 or more */
59687          testcase( nCell==0 );  /* Invalid key size:  0x80 0x80 0x00 */
59688          testcase( nCell==1 );  /* Invalid key size:  0x80 0x80 0x01 */
59689          testcase( nCell==2 );  /* Minimum legal index key size */
59690          if( nCell<2 ){
59691            rc = SQLITE_CORRUPT_BKPT;
59692            goto moveto_finish;
59693          }
59694          pCellKey = sqlite3Malloc( nCell+18 );
59695          if( pCellKey==0 ){
59696            rc = SQLITE_NOMEM;
59697            goto moveto_finish;
59698          }
59699          pCur->aiIdx[pCur->iPage] = (u16)idx;
59700          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
59701          if( rc ){
59702            sqlite3_free(pCellKey);
59703            goto moveto_finish;
59704          }
59705          c = xRecordCompare(nCell, pCellKey, pIdxKey);
59706          sqlite3_free(pCellKey);
59707        }
59708        assert(
59709            (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
59710         && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
59711        );
59712        if( c<0 ){
59713          lwr = idx+1;
59714        }else if( c>0 ){
59715          upr = idx-1;
59716        }else{
59717          assert( c==0 );
59718          *pRes = 0;
59719          rc = SQLITE_OK;
59720          pCur->aiIdx[pCur->iPage] = (u16)idx;
59721          if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
59722          goto moveto_finish;
59723        }
59724        if( lwr>upr ) break;
59725        assert( lwr+upr>=0 );
59726        idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
59727      }
59728    }
59729    assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
59730    assert( pPage->isInit );
59731    if( pPage->leaf ){
59732      assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
59733      pCur->aiIdx[pCur->iPage] = (u16)idx;
59734      *pRes = c;
59735      rc = SQLITE_OK;
59736      goto moveto_finish;
59737    }
59738moveto_next_layer:
59739    if( lwr>=pPage->nCell ){
59740      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
59741    }else{
59742      chldPg = get4byte(findCell(pPage, lwr));
59743    }
59744    pCur->aiIdx[pCur->iPage] = (u16)lwr;
59745    rc = moveToChild(pCur, chldPg);
59746    if( rc ) break;
59747  }
59748moveto_finish:
59749  pCur->info.nSize = 0;
59750  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
59751  return rc;
59752}
59753
59754
59755/*
59756** Return TRUE if the cursor is not pointing at an entry of the table.
59757**
59758** TRUE will be returned after a call to sqlite3BtreeNext() moves
59759** past the last entry in the table or sqlite3BtreePrev() moves past
59760** the first entry.  TRUE is also returned if the table is empty.
59761*/
59762SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
59763  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
59764  ** have been deleted? This API will need to change to return an error code
59765  ** as well as the boolean result value.
59766  */
59767  return (CURSOR_VALID!=pCur->eState);
59768}
59769
59770/*
59771** Advance the cursor to the next entry in the database.  If
59772** successful then set *pRes=0.  If the cursor
59773** was already pointing to the last entry in the database before
59774** this routine was called, then set *pRes=1.
59775**
59776** The main entry point is sqlite3BtreeNext().  That routine is optimized
59777** for the common case of merely incrementing the cell counter BtCursor.aiIdx
59778** to the next cell on the current page.  The (slower) btreeNext() helper
59779** routine is called when it is necessary to move to a different page or
59780** to restore the cursor.
59781**
59782** The calling function will set *pRes to 0 or 1.  The initial *pRes value
59783** will be 1 if the cursor being stepped corresponds to an SQL index and
59784** if this routine could have been skipped if that SQL index had been
59785** a unique index.  Otherwise the caller will have set *pRes to zero.
59786** Zero is the common case. The btree implementation is free to use the
59787** initial *pRes value as a hint to improve performance, but the current
59788** SQLite btree implementation does not. (Note that the comdb2 btree
59789** implementation does use this hint, however.)
59790*/
59791static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
59792  int rc;
59793  int idx;
59794  MemPage *pPage;
59795
59796  assert( cursorHoldsMutex(pCur) );
59797  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
59798  assert( *pRes==0 );
59799  if( pCur->eState!=CURSOR_VALID ){
59800    assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
59801    rc = restoreCursorPosition(pCur);
59802    if( rc!=SQLITE_OK ){
59803      return rc;
59804    }
59805    if( CURSOR_INVALID==pCur->eState ){
59806      *pRes = 1;
59807      return SQLITE_OK;
59808    }
59809    if( pCur->skipNext ){
59810      assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
59811      pCur->eState = CURSOR_VALID;
59812      if( pCur->skipNext>0 ){
59813        pCur->skipNext = 0;
59814        return SQLITE_OK;
59815      }
59816      pCur->skipNext = 0;
59817    }
59818  }
59819
59820  pPage = pCur->apPage[pCur->iPage];
59821  idx = ++pCur->aiIdx[pCur->iPage];
59822  assert( pPage->isInit );
59823
59824  /* If the database file is corrupt, it is possible for the value of idx
59825  ** to be invalid here. This can only occur if a second cursor modifies
59826  ** the page while cursor pCur is holding a reference to it. Which can
59827  ** only happen if the database is corrupt in such a way as to link the
59828  ** page into more than one b-tree structure. */
59829  testcase( idx>pPage->nCell );
59830
59831  if( idx>=pPage->nCell ){
59832    if( !pPage->leaf ){
59833      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
59834      if( rc ) return rc;
59835      return moveToLeftmost(pCur);
59836    }
59837    do{
59838      if( pCur->iPage==0 ){
59839        *pRes = 1;
59840        pCur->eState = CURSOR_INVALID;
59841        return SQLITE_OK;
59842      }
59843      moveToParent(pCur);
59844      pPage = pCur->apPage[pCur->iPage];
59845    }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
59846    if( pPage->intKey ){
59847      return sqlite3BtreeNext(pCur, pRes);
59848    }else{
59849      return SQLITE_OK;
59850    }
59851  }
59852  if( pPage->leaf ){
59853    return SQLITE_OK;
59854  }else{
59855    return moveToLeftmost(pCur);
59856  }
59857}
59858SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
59859  MemPage *pPage;
59860  assert( cursorHoldsMutex(pCur) );
59861  assert( pRes!=0 );
59862  assert( *pRes==0 || *pRes==1 );
59863  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
59864  pCur->info.nSize = 0;
59865  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
59866  *pRes = 0;
59867  if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
59868  pPage = pCur->apPage[pCur->iPage];
59869  if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
59870    pCur->aiIdx[pCur->iPage]--;
59871    return btreeNext(pCur, pRes);
59872  }
59873  if( pPage->leaf ){
59874    return SQLITE_OK;
59875  }else{
59876    return moveToLeftmost(pCur);
59877  }
59878}
59879
59880/*
59881** Step the cursor to the back to the previous entry in the database.  If
59882** successful then set *pRes=0.  If the cursor
59883** was already pointing to the first entry in the database before
59884** this routine was called, then set *pRes=1.
59885**
59886** The main entry point is sqlite3BtreePrevious().  That routine is optimized
59887** for the common case of merely decrementing the cell counter BtCursor.aiIdx
59888** to the previous cell on the current page.  The (slower) btreePrevious()
59889** helper routine is called when it is necessary to move to a different page
59890** or to restore the cursor.
59891**
59892** The calling function will set *pRes to 0 or 1.  The initial *pRes value
59893** will be 1 if the cursor being stepped corresponds to an SQL index and
59894** if this routine could have been skipped if that SQL index had been
59895** a unique index.  Otherwise the caller will have set *pRes to zero.
59896** Zero is the common case. The btree implementation is free to use the
59897** initial *pRes value as a hint to improve performance, but the current
59898** SQLite btree implementation does not. (Note that the comdb2 btree
59899** implementation does use this hint, however.)
59900*/
59901static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
59902  int rc;
59903  MemPage *pPage;
59904
59905  assert( cursorHoldsMutex(pCur) );
59906  assert( pRes!=0 );
59907  assert( *pRes==0 );
59908  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
59909  assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
59910  assert( pCur->info.nSize==0 );
59911  if( pCur->eState!=CURSOR_VALID ){
59912    rc = restoreCursorPosition(pCur);
59913    if( rc!=SQLITE_OK ){
59914      return rc;
59915    }
59916    if( CURSOR_INVALID==pCur->eState ){
59917      *pRes = 1;
59918      return SQLITE_OK;
59919    }
59920    if( pCur->skipNext ){
59921      assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
59922      pCur->eState = CURSOR_VALID;
59923      if( pCur->skipNext<0 ){
59924        pCur->skipNext = 0;
59925        return SQLITE_OK;
59926      }
59927      pCur->skipNext = 0;
59928    }
59929  }
59930
59931  pPage = pCur->apPage[pCur->iPage];
59932  assert( pPage->isInit );
59933  if( !pPage->leaf ){
59934    int idx = pCur->aiIdx[pCur->iPage];
59935    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
59936    if( rc ) return rc;
59937    rc = moveToRightmost(pCur);
59938  }else{
59939    while( pCur->aiIdx[pCur->iPage]==0 ){
59940      if( pCur->iPage==0 ){
59941        pCur->eState = CURSOR_INVALID;
59942        *pRes = 1;
59943        return SQLITE_OK;
59944      }
59945      moveToParent(pCur);
59946    }
59947    assert( pCur->info.nSize==0 );
59948    assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
59949
59950    pCur->aiIdx[pCur->iPage]--;
59951    pPage = pCur->apPage[pCur->iPage];
59952    if( pPage->intKey && !pPage->leaf ){
59953      rc = sqlite3BtreePrevious(pCur, pRes);
59954    }else{
59955      rc = SQLITE_OK;
59956    }
59957  }
59958  return rc;
59959}
59960SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
59961  assert( cursorHoldsMutex(pCur) );
59962  assert( pRes!=0 );
59963  assert( *pRes==0 || *pRes==1 );
59964  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
59965  *pRes = 0;
59966  pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
59967  pCur->info.nSize = 0;
59968  if( pCur->eState!=CURSOR_VALID
59969   || pCur->aiIdx[pCur->iPage]==0
59970   || pCur->apPage[pCur->iPage]->leaf==0
59971  ){
59972    return btreePrevious(pCur, pRes);
59973  }
59974  pCur->aiIdx[pCur->iPage]--;
59975  return SQLITE_OK;
59976}
59977
59978/*
59979** Allocate a new page from the database file.
59980**
59981** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
59982** has already been called on the new page.)  The new page has also
59983** been referenced and the calling routine is responsible for calling
59984** sqlite3PagerUnref() on the new page when it is done.
59985**
59986** SQLITE_OK is returned on success.  Any other return value indicates
59987** an error.  *ppPage is set to NULL in the event of an error.
59988**
59989** If the "nearby" parameter is not 0, then an effort is made to
59990** locate a page close to the page number "nearby".  This can be used in an
59991** attempt to keep related pages close to each other in the database file,
59992** which in turn can make database access faster.
59993**
59994** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
59995** anywhere on the free-list, then it is guaranteed to be returned.  If
59996** eMode is BTALLOC_LT then the page returned will be less than or equal
59997** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
59998** are no restrictions on which page is returned.
59999*/
60000static int allocateBtreePage(
60001  BtShared *pBt,         /* The btree */
60002  MemPage **ppPage,      /* Store pointer to the allocated page here */
60003  Pgno *pPgno,           /* Store the page number here */
60004  Pgno nearby,           /* Search for a page near this one */
60005  u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
60006){
60007  MemPage *pPage1;
60008  int rc;
60009  u32 n;     /* Number of pages on the freelist */
60010  u32 k;     /* Number of leaves on the trunk of the freelist */
60011  MemPage *pTrunk = 0;
60012  MemPage *pPrevTrunk = 0;
60013  Pgno mxPage;     /* Total size of the database file */
60014
60015  assert( sqlite3_mutex_held(pBt->mutex) );
60016  assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
60017  pPage1 = pBt->pPage1;
60018  mxPage = btreePagecount(pBt);
60019  /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
60020  ** stores stores the total number of pages on the freelist. */
60021  n = get4byte(&pPage1->aData[36]);
60022  testcase( n==mxPage-1 );
60023  if( n>=mxPage ){
60024    return SQLITE_CORRUPT_BKPT;
60025  }
60026  if( n>0 ){
60027    /* There are pages on the freelist.  Reuse one of those pages. */
60028    Pgno iTrunk;
60029    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
60030    u32 nSearch = 0;   /* Count of the number of search attempts */
60031
60032    /* If eMode==BTALLOC_EXACT and a query of the pointer-map
60033    ** shows that the page 'nearby' is somewhere on the free-list, then
60034    ** the entire-list will be searched for that page.
60035    */
60036#ifndef SQLITE_OMIT_AUTOVACUUM
60037    if( eMode==BTALLOC_EXACT ){
60038      if( nearby<=mxPage ){
60039        u8 eType;
60040        assert( nearby>0 );
60041        assert( pBt->autoVacuum );
60042        rc = ptrmapGet(pBt, nearby, &eType, 0);
60043        if( rc ) return rc;
60044        if( eType==PTRMAP_FREEPAGE ){
60045          searchList = 1;
60046        }
60047      }
60048    }else if( eMode==BTALLOC_LE ){
60049      searchList = 1;
60050    }
60051#endif
60052
60053    /* Decrement the free-list count by 1. Set iTrunk to the index of the
60054    ** first free-list trunk page. iPrevTrunk is initially 1.
60055    */
60056    rc = sqlite3PagerWrite(pPage1->pDbPage);
60057    if( rc ) return rc;
60058    put4byte(&pPage1->aData[36], n-1);
60059
60060    /* The code within this loop is run only once if the 'searchList' variable
60061    ** is not true. Otherwise, it runs once for each trunk-page on the
60062    ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
60063    ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
60064    */
60065    do {
60066      pPrevTrunk = pTrunk;
60067      if( pPrevTrunk ){
60068        /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
60069        ** is the page number of the next freelist trunk page in the list or
60070        ** zero if this is the last freelist trunk page. */
60071        iTrunk = get4byte(&pPrevTrunk->aData[0]);
60072      }else{
60073        /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
60074        ** stores the page number of the first page of the freelist, or zero if
60075        ** the freelist is empty. */
60076        iTrunk = get4byte(&pPage1->aData[32]);
60077      }
60078      testcase( iTrunk==mxPage );
60079      if( iTrunk>mxPage || nSearch++ > n ){
60080        rc = SQLITE_CORRUPT_BKPT;
60081      }else{
60082        rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
60083      }
60084      if( rc ){
60085        pTrunk = 0;
60086        goto end_allocate_page;
60087      }
60088      assert( pTrunk!=0 );
60089      assert( pTrunk->aData!=0 );
60090      /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
60091      ** is the number of leaf page pointers to follow. */
60092      k = get4byte(&pTrunk->aData[4]);
60093      if( k==0 && !searchList ){
60094        /* The trunk has no leaves and the list is not being searched.
60095        ** So extract the trunk page itself and use it as the newly
60096        ** allocated page */
60097        assert( pPrevTrunk==0 );
60098        rc = sqlite3PagerWrite(pTrunk->pDbPage);
60099        if( rc ){
60100          goto end_allocate_page;
60101        }
60102        *pPgno = iTrunk;
60103        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
60104        *ppPage = pTrunk;
60105        pTrunk = 0;
60106        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
60107      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
60108        /* Value of k is out of range.  Database corruption */
60109        rc = SQLITE_CORRUPT_BKPT;
60110        goto end_allocate_page;
60111#ifndef SQLITE_OMIT_AUTOVACUUM
60112      }else if( searchList
60113            && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
60114      ){
60115        /* The list is being searched and this trunk page is the page
60116        ** to allocate, regardless of whether it has leaves.
60117        */
60118        *pPgno = iTrunk;
60119        *ppPage = pTrunk;
60120        searchList = 0;
60121        rc = sqlite3PagerWrite(pTrunk->pDbPage);
60122        if( rc ){
60123          goto end_allocate_page;
60124        }
60125        if( k==0 ){
60126          if( !pPrevTrunk ){
60127            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
60128          }else{
60129            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
60130            if( rc!=SQLITE_OK ){
60131              goto end_allocate_page;
60132            }
60133            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
60134          }
60135        }else{
60136          /* The trunk page is required by the caller but it contains
60137          ** pointers to free-list leaves. The first leaf becomes a trunk
60138          ** page in this case.
60139          */
60140          MemPage *pNewTrunk;
60141          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
60142          if( iNewTrunk>mxPage ){
60143            rc = SQLITE_CORRUPT_BKPT;
60144            goto end_allocate_page;
60145          }
60146          testcase( iNewTrunk==mxPage );
60147          rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
60148          if( rc!=SQLITE_OK ){
60149            goto end_allocate_page;
60150          }
60151          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
60152          if( rc!=SQLITE_OK ){
60153            releasePage(pNewTrunk);
60154            goto end_allocate_page;
60155          }
60156          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
60157          put4byte(&pNewTrunk->aData[4], k-1);
60158          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
60159          releasePage(pNewTrunk);
60160          if( !pPrevTrunk ){
60161            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
60162            put4byte(&pPage1->aData[32], iNewTrunk);
60163          }else{
60164            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
60165            if( rc ){
60166              goto end_allocate_page;
60167            }
60168            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
60169          }
60170        }
60171        pTrunk = 0;
60172        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
60173#endif
60174      }else if( k>0 ){
60175        /* Extract a leaf from the trunk */
60176        u32 closest;
60177        Pgno iPage;
60178        unsigned char *aData = pTrunk->aData;
60179        if( nearby>0 ){
60180          u32 i;
60181          closest = 0;
60182          if( eMode==BTALLOC_LE ){
60183            for(i=0; i<k; i++){
60184              iPage = get4byte(&aData[8+i*4]);
60185              if( iPage<=nearby ){
60186                closest = i;
60187                break;
60188              }
60189            }
60190          }else{
60191            int dist;
60192            dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
60193            for(i=1; i<k; i++){
60194              int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
60195              if( d2<dist ){
60196                closest = i;
60197                dist = d2;
60198              }
60199            }
60200          }
60201        }else{
60202          closest = 0;
60203        }
60204
60205        iPage = get4byte(&aData[8+closest*4]);
60206        testcase( iPage==mxPage );
60207        if( iPage>mxPage ){
60208          rc = SQLITE_CORRUPT_BKPT;
60209          goto end_allocate_page;
60210        }
60211        testcase( iPage==mxPage );
60212        if( !searchList
60213         || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
60214        ){
60215          int noContent;
60216          *pPgno = iPage;
60217          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
60218                 ": %d more free pages\n",
60219                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
60220          rc = sqlite3PagerWrite(pTrunk->pDbPage);
60221          if( rc ) goto end_allocate_page;
60222          if( closest<k-1 ){
60223            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
60224          }
60225          put4byte(&aData[4], k-1);
60226          noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
60227          rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
60228          if( rc==SQLITE_OK ){
60229            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
60230            if( rc!=SQLITE_OK ){
60231              releasePage(*ppPage);
60232              *ppPage = 0;
60233            }
60234          }
60235          searchList = 0;
60236        }
60237      }
60238      releasePage(pPrevTrunk);
60239      pPrevTrunk = 0;
60240    }while( searchList );
60241  }else{
60242    /* There are no pages on the freelist, so append a new page to the
60243    ** database image.
60244    **
60245    ** Normally, new pages allocated by this block can be requested from the
60246    ** pager layer with the 'no-content' flag set. This prevents the pager
60247    ** from trying to read the pages content from disk. However, if the
60248    ** current transaction has already run one or more incremental-vacuum
60249    ** steps, then the page we are about to allocate may contain content
60250    ** that is required in the event of a rollback. In this case, do
60251    ** not set the no-content flag. This causes the pager to load and journal
60252    ** the current page content before overwriting it.
60253    **
60254    ** Note that the pager will not actually attempt to load or journal
60255    ** content for any page that really does lie past the end of the database
60256    ** file on disk. So the effects of disabling the no-content optimization
60257    ** here are confined to those pages that lie between the end of the
60258    ** database image and the end of the database file.
60259    */
60260    int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
60261
60262    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
60263    if( rc ) return rc;
60264    pBt->nPage++;
60265    if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
60266
60267#ifndef SQLITE_OMIT_AUTOVACUUM
60268    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
60269      /* If *pPgno refers to a pointer-map page, allocate two new pages
60270      ** at the end of the file instead of one. The first allocated page
60271      ** becomes a new pointer-map page, the second is used by the caller.
60272      */
60273      MemPage *pPg = 0;
60274      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
60275      assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
60276      rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
60277      if( rc==SQLITE_OK ){
60278        rc = sqlite3PagerWrite(pPg->pDbPage);
60279        releasePage(pPg);
60280      }
60281      if( rc ) return rc;
60282      pBt->nPage++;
60283      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
60284    }
60285#endif
60286    put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
60287    *pPgno = pBt->nPage;
60288
60289    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
60290    rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
60291    if( rc ) return rc;
60292    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
60293    if( rc!=SQLITE_OK ){
60294      releasePage(*ppPage);
60295      *ppPage = 0;
60296    }
60297    TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
60298  }
60299
60300  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
60301
60302end_allocate_page:
60303  releasePage(pTrunk);
60304  releasePage(pPrevTrunk);
60305  assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
60306  assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
60307  return rc;
60308}
60309
60310/*
60311** This function is used to add page iPage to the database file free-list.
60312** It is assumed that the page is not already a part of the free-list.
60313**
60314** The value passed as the second argument to this function is optional.
60315** If the caller happens to have a pointer to the MemPage object
60316** corresponding to page iPage handy, it may pass it as the second value.
60317** Otherwise, it may pass NULL.
60318**
60319** If a pointer to a MemPage object is passed as the second argument,
60320** its reference count is not altered by this function.
60321*/
60322static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
60323  MemPage *pTrunk = 0;                /* Free-list trunk page */
60324  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
60325  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
60326  MemPage *pPage;                     /* Page being freed. May be NULL. */
60327  int rc;                             /* Return Code */
60328  int nFree;                          /* Initial number of pages on free-list */
60329
60330  assert( sqlite3_mutex_held(pBt->mutex) );
60331  assert( CORRUPT_DB || iPage>1 );
60332  assert( !pMemPage || pMemPage->pgno==iPage );
60333
60334  if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
60335  if( pMemPage ){
60336    pPage = pMemPage;
60337    sqlite3PagerRef(pPage->pDbPage);
60338  }else{
60339    pPage = btreePageLookup(pBt, iPage);
60340  }
60341
60342  /* Increment the free page count on pPage1 */
60343  rc = sqlite3PagerWrite(pPage1->pDbPage);
60344  if( rc ) goto freepage_out;
60345  nFree = get4byte(&pPage1->aData[36]);
60346  put4byte(&pPage1->aData[36], nFree+1);
60347
60348  if( pBt->btsFlags & BTS_SECURE_DELETE ){
60349    /* If the secure_delete option is enabled, then
60350    ** always fully overwrite deleted information with zeros.
60351    */
60352    if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
60353     ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
60354    ){
60355      goto freepage_out;
60356    }
60357    memset(pPage->aData, 0, pPage->pBt->pageSize);
60358  }
60359
60360  /* If the database supports auto-vacuum, write an entry in the pointer-map
60361  ** to indicate that the page is free.
60362  */
60363  if( ISAUTOVACUUM ){
60364    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
60365    if( rc ) goto freepage_out;
60366  }
60367
60368  /* Now manipulate the actual database free-list structure. There are two
60369  ** possibilities. If the free-list is currently empty, or if the first
60370  ** trunk page in the free-list is full, then this page will become a
60371  ** new free-list trunk page. Otherwise, it will become a leaf of the
60372  ** first trunk page in the current free-list. This block tests if it
60373  ** is possible to add the page as a new free-list leaf.
60374  */
60375  if( nFree!=0 ){
60376    u32 nLeaf;                /* Initial number of leaf cells on trunk page */
60377
60378    iTrunk = get4byte(&pPage1->aData[32]);
60379    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
60380    if( rc!=SQLITE_OK ){
60381      goto freepage_out;
60382    }
60383
60384    nLeaf = get4byte(&pTrunk->aData[4]);
60385    assert( pBt->usableSize>32 );
60386    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
60387      rc = SQLITE_CORRUPT_BKPT;
60388      goto freepage_out;
60389    }
60390    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
60391      /* In this case there is room on the trunk page to insert the page
60392      ** being freed as a new leaf.
60393      **
60394      ** Note that the trunk page is not really full until it contains
60395      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
60396      ** coded.  But due to a coding error in versions of SQLite prior to
60397      ** 3.6.0, databases with freelist trunk pages holding more than
60398      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
60399      ** to maintain backwards compatibility with older versions of SQLite,
60400      ** we will continue to restrict the number of entries to usableSize/4 - 8
60401      ** for now.  At some point in the future (once everyone has upgraded
60402      ** to 3.6.0 or later) we should consider fixing the conditional above
60403      ** to read "usableSize/4-2" instead of "usableSize/4-8".
60404      **
60405      ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
60406      ** avoid using the last six entries in the freelist trunk page array in
60407      ** order that database files created by newer versions of SQLite can be
60408      ** read by older versions of SQLite.
60409      */
60410      rc = sqlite3PagerWrite(pTrunk->pDbPage);
60411      if( rc==SQLITE_OK ){
60412        put4byte(&pTrunk->aData[4], nLeaf+1);
60413        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
60414        if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
60415          sqlite3PagerDontWrite(pPage->pDbPage);
60416        }
60417        rc = btreeSetHasContent(pBt, iPage);
60418      }
60419      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
60420      goto freepage_out;
60421    }
60422  }
60423
60424  /* If control flows to this point, then it was not possible to add the
60425  ** the page being freed as a leaf page of the first trunk in the free-list.
60426  ** Possibly because the free-list is empty, or possibly because the
60427  ** first trunk in the free-list is full. Either way, the page being freed
60428  ** will become the new first trunk page in the free-list.
60429  */
60430  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
60431    goto freepage_out;
60432  }
60433  rc = sqlite3PagerWrite(pPage->pDbPage);
60434  if( rc!=SQLITE_OK ){
60435    goto freepage_out;
60436  }
60437  put4byte(pPage->aData, iTrunk);
60438  put4byte(&pPage->aData[4], 0);
60439  put4byte(&pPage1->aData[32], iPage);
60440  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
60441
60442freepage_out:
60443  if( pPage ){
60444    pPage->isInit = 0;
60445  }
60446  releasePage(pPage);
60447  releasePage(pTrunk);
60448  return rc;
60449}
60450static void freePage(MemPage *pPage, int *pRC){
60451  if( (*pRC)==SQLITE_OK ){
60452    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
60453  }
60454}
60455
60456/*
60457** Free any overflow pages associated with the given Cell.  Write the
60458** local Cell size (the number of bytes on the original page, omitting
60459** overflow) into *pnSize.
60460*/
60461static int clearCell(
60462  MemPage *pPage,          /* The page that contains the Cell */
60463  unsigned char *pCell,    /* First byte of the Cell */
60464  u16 *pnSize              /* Write the size of the Cell here */
60465){
60466  BtShared *pBt = pPage->pBt;
60467  CellInfo info;
60468  Pgno ovflPgno;
60469  int rc;
60470  int nOvfl;
60471  u32 ovflPageSize;
60472
60473  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60474  pPage->xParseCell(pPage, pCell, &info);
60475  *pnSize = info.nSize;
60476  if( info.iOverflow==0 ){
60477    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
60478  }
60479  if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
60480    return SQLITE_CORRUPT_BKPT;  /* Cell extends past end of page */
60481  }
60482  ovflPgno = get4byte(&pCell[info.iOverflow]);
60483  assert( pBt->usableSize > 4 );
60484  ovflPageSize = pBt->usableSize - 4;
60485  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
60486  assert( nOvfl>0 ||
60487    (CORRUPT_DB && (info.nPayload + ovflPageSize)<ovflPageSize)
60488  );
60489  while( nOvfl-- ){
60490    Pgno iNext = 0;
60491    MemPage *pOvfl = 0;
60492    if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
60493      /* 0 is not a legal page number and page 1 cannot be an
60494      ** overflow page. Therefore if ovflPgno<2 or past the end of the
60495      ** file the database must be corrupt. */
60496      return SQLITE_CORRUPT_BKPT;
60497    }
60498    if( nOvfl ){
60499      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
60500      if( rc ) return rc;
60501    }
60502
60503    if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
60504     && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
60505    ){
60506      /* There is no reason any cursor should have an outstanding reference
60507      ** to an overflow page belonging to a cell that is being deleted/updated.
60508      ** So if there exists more than one reference to this page, then it
60509      ** must not really be an overflow page and the database must be corrupt.
60510      ** It is helpful to detect this before calling freePage2(), as
60511      ** freePage2() may zero the page contents if secure-delete mode is
60512      ** enabled. If this 'overflow' page happens to be a page that the
60513      ** caller is iterating through or using in some other way, this
60514      ** can be problematic.
60515      */
60516      rc = SQLITE_CORRUPT_BKPT;
60517    }else{
60518      rc = freePage2(pBt, pOvfl, ovflPgno);
60519    }
60520
60521    if( pOvfl ){
60522      sqlite3PagerUnref(pOvfl->pDbPage);
60523    }
60524    if( rc ) return rc;
60525    ovflPgno = iNext;
60526  }
60527  return SQLITE_OK;
60528}
60529
60530/*
60531** Create the byte sequence used to represent a cell on page pPage
60532** and write that byte sequence into pCell[].  Overflow pages are
60533** allocated and filled in as necessary.  The calling procedure
60534** is responsible for making sure sufficient space has been allocated
60535** for pCell[].
60536**
60537** Note that pCell does not necessary need to point to the pPage->aData
60538** area.  pCell might point to some temporary storage.  The cell will
60539** be constructed in this temporary area then copied into pPage->aData
60540** later.
60541*/
60542static int fillInCell(
60543  MemPage *pPage,                /* The page that contains the cell */
60544  unsigned char *pCell,          /* Complete text of the cell */
60545  const void *pKey, i64 nKey,    /* The key */
60546  const void *pData,int nData,   /* The data */
60547  int nZero,                     /* Extra zero bytes to append to pData */
60548  int *pnSize                    /* Write cell size here */
60549){
60550  int nPayload;
60551  const u8 *pSrc;
60552  int nSrc, n, rc;
60553  int spaceLeft;
60554  MemPage *pOvfl = 0;
60555  MemPage *pToRelease = 0;
60556  unsigned char *pPrior;
60557  unsigned char *pPayload;
60558  BtShared *pBt = pPage->pBt;
60559  Pgno pgnoOvfl = 0;
60560  int nHeader;
60561
60562  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60563
60564  /* pPage is not necessarily writeable since pCell might be auxiliary
60565  ** buffer space that is separate from the pPage buffer area */
60566  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
60567            || sqlite3PagerIswriteable(pPage->pDbPage) );
60568
60569  /* Fill in the header. */
60570  nHeader = pPage->childPtrSize;
60571  nPayload = nData + nZero;
60572  if( pPage->intKeyLeaf ){
60573    nHeader += putVarint32(&pCell[nHeader], nPayload);
60574  }else{
60575    assert( nData==0 );
60576    assert( nZero==0 );
60577  }
60578  nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
60579
60580  /* Fill in the payload size */
60581  if( pPage->intKey ){
60582    pSrc = pData;
60583    nSrc = nData;
60584    nData = 0;
60585  }else{
60586    assert( nKey<=0x7fffffff && pKey!=0 );
60587    nPayload = (int)nKey;
60588    pSrc = pKey;
60589    nSrc = (int)nKey;
60590  }
60591  if( nPayload<=pPage->maxLocal ){
60592    n = nHeader + nPayload;
60593    testcase( n==3 );
60594    testcase( n==4 );
60595    if( n<4 ) n = 4;
60596    *pnSize = n;
60597    spaceLeft = nPayload;
60598    pPrior = pCell;
60599  }else{
60600    int mn = pPage->minLocal;
60601    n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
60602    testcase( n==pPage->maxLocal );
60603    testcase( n==pPage->maxLocal+1 );
60604    if( n > pPage->maxLocal ) n = mn;
60605    spaceLeft = n;
60606    *pnSize = n + nHeader + 4;
60607    pPrior = &pCell[nHeader+n];
60608  }
60609  pPayload = &pCell[nHeader];
60610
60611  /* At this point variables should be set as follows:
60612  **
60613  **   nPayload           Total payload size in bytes
60614  **   pPayload           Begin writing payload here
60615  **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
60616  **                      that means content must spill into overflow pages.
60617  **   *pnSize            Size of the local cell (not counting overflow pages)
60618  **   pPrior             Where to write the pgno of the first overflow page
60619  **
60620  ** Use a call to btreeParseCellPtr() to verify that the values above
60621  ** were computed correctly.
60622  */
60623#if SQLITE_DEBUG
60624  {
60625    CellInfo info;
60626    pPage->xParseCell(pPage, pCell, &info);
60627    assert( nHeader=(int)(info.pPayload - pCell) );
60628    assert( info.nKey==nKey );
60629    assert( *pnSize == info.nSize );
60630    assert( spaceLeft == info.nLocal );
60631    assert( pPrior == &pCell[info.iOverflow] );
60632  }
60633#endif
60634
60635  /* Write the payload into the local Cell and any extra into overflow pages */
60636  while( nPayload>0 ){
60637    if( spaceLeft==0 ){
60638#ifndef SQLITE_OMIT_AUTOVACUUM
60639      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
60640      if( pBt->autoVacuum ){
60641        do{
60642          pgnoOvfl++;
60643        } while(
60644          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
60645        );
60646      }
60647#endif
60648      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
60649#ifndef SQLITE_OMIT_AUTOVACUUM
60650      /* If the database supports auto-vacuum, and the second or subsequent
60651      ** overflow page is being allocated, add an entry to the pointer-map
60652      ** for that page now.
60653      **
60654      ** If this is the first overflow page, then write a partial entry
60655      ** to the pointer-map. If we write nothing to this pointer-map slot,
60656      ** then the optimistic overflow chain processing in clearCell()
60657      ** may misinterpret the uninitialized values and delete the
60658      ** wrong pages from the database.
60659      */
60660      if( pBt->autoVacuum && rc==SQLITE_OK ){
60661        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
60662        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
60663        if( rc ){
60664          releasePage(pOvfl);
60665        }
60666      }
60667#endif
60668      if( rc ){
60669        releasePage(pToRelease);
60670        return rc;
60671      }
60672
60673      /* If pToRelease is not zero than pPrior points into the data area
60674      ** of pToRelease.  Make sure pToRelease is still writeable. */
60675      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
60676
60677      /* If pPrior is part of the data area of pPage, then make sure pPage
60678      ** is still writeable */
60679      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
60680            || sqlite3PagerIswriteable(pPage->pDbPage) );
60681
60682      put4byte(pPrior, pgnoOvfl);
60683      releasePage(pToRelease);
60684      pToRelease = pOvfl;
60685      pPrior = pOvfl->aData;
60686      put4byte(pPrior, 0);
60687      pPayload = &pOvfl->aData[4];
60688      spaceLeft = pBt->usableSize - 4;
60689    }
60690    n = nPayload;
60691    if( n>spaceLeft ) n = spaceLeft;
60692
60693    /* If pToRelease is not zero than pPayload points into the data area
60694    ** of pToRelease.  Make sure pToRelease is still writeable. */
60695    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
60696
60697    /* If pPayload is part of the data area of pPage, then make sure pPage
60698    ** is still writeable */
60699    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
60700            || sqlite3PagerIswriteable(pPage->pDbPage) );
60701
60702    if( nSrc>0 ){
60703      if( n>nSrc ) n = nSrc;
60704      assert( pSrc );
60705      memcpy(pPayload, pSrc, n);
60706    }else{
60707      memset(pPayload, 0, n);
60708    }
60709    nPayload -= n;
60710    pPayload += n;
60711    pSrc += n;
60712    nSrc -= n;
60713    spaceLeft -= n;
60714    if( nSrc==0 ){
60715      nSrc = nData;
60716      pSrc = pData;
60717    }
60718  }
60719  releasePage(pToRelease);
60720  return SQLITE_OK;
60721}
60722
60723/*
60724** Remove the i-th cell from pPage.  This routine effects pPage only.
60725** The cell content is not freed or deallocated.  It is assumed that
60726** the cell content has been copied someplace else.  This routine just
60727** removes the reference to the cell from pPage.
60728**
60729** "sz" must be the number of bytes in the cell.
60730*/
60731static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
60732  u32 pc;         /* Offset to cell content of cell being deleted */
60733  u8 *data;       /* pPage->aData */
60734  u8 *ptr;        /* Used to move bytes around within data[] */
60735  int rc;         /* The return code */
60736  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
60737
60738  if( *pRC ) return;
60739
60740  assert( idx>=0 && idx<pPage->nCell );
60741  assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
60742  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
60743  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60744  data = pPage->aData;
60745  ptr = &pPage->aCellIdx[2*idx];
60746  pc = get2byte(ptr);
60747  hdr = pPage->hdrOffset;
60748  testcase( pc==get2byte(&data[hdr+5]) );
60749  testcase( pc+sz==pPage->pBt->usableSize );
60750  if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
60751    *pRC = SQLITE_CORRUPT_BKPT;
60752    return;
60753  }
60754  rc = freeSpace(pPage, pc, sz);
60755  if( rc ){
60756    *pRC = rc;
60757    return;
60758  }
60759  pPage->nCell--;
60760  if( pPage->nCell==0 ){
60761    memset(&data[hdr+1], 0, 4);
60762    data[hdr+7] = 0;
60763    put2byte(&data[hdr+5], pPage->pBt->usableSize);
60764    pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
60765                       - pPage->childPtrSize - 8;
60766  }else{
60767    memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
60768    put2byte(&data[hdr+3], pPage->nCell);
60769    pPage->nFree += 2;
60770  }
60771}
60772
60773/*
60774** Insert a new cell on pPage at cell index "i".  pCell points to the
60775** content of the cell.
60776**
60777** If the cell content will fit on the page, then put it there.  If it
60778** will not fit, then make a copy of the cell content into pTemp if
60779** pTemp is not null.  Regardless of pTemp, allocate a new entry
60780** in pPage->apOvfl[] and make it point to the cell content (either
60781** in pTemp or the original pCell) and also record its index.
60782** Allocating a new entry in pPage->aCell[] implies that
60783** pPage->nOverflow is incremented.
60784*/
60785static void insertCell(
60786  MemPage *pPage,   /* Page into which we are copying */
60787  int i,            /* New cell becomes the i-th cell of the page */
60788  u8 *pCell,        /* Content of the new cell */
60789  int sz,           /* Bytes of content in pCell */
60790  u8 *pTemp,        /* Temp storage space for pCell, if needed */
60791  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
60792  int *pRC          /* Read and write return code from here */
60793){
60794  int idx = 0;      /* Where to write new cell content in data[] */
60795  int j;            /* Loop counter */
60796  u8 *data;         /* The content of the whole page */
60797  u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */
60798
60799  if( *pRC ) return;
60800
60801  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
60802  assert( MX_CELL(pPage->pBt)<=10921 );
60803  assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
60804  assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
60805  assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
60806  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60807  /* The cell should normally be sized correctly.  However, when moving a
60808  ** malformed cell from a leaf page to an interior page, if the cell size
60809  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
60810  ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
60811  ** the term after the || in the following assert(). */
60812  assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
60813  if( pPage->nOverflow || sz+2>pPage->nFree ){
60814    if( pTemp ){
60815      memcpy(pTemp, pCell, sz);
60816      pCell = pTemp;
60817    }
60818    if( iChild ){
60819      put4byte(pCell, iChild);
60820    }
60821    j = pPage->nOverflow++;
60822    assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
60823    pPage->apOvfl[j] = pCell;
60824    pPage->aiOvfl[j] = (u16)i;
60825
60826    /* When multiple overflows occur, they are always sequential and in
60827    ** sorted order.  This invariants arise because multiple overflows can
60828    ** only occur when inserting divider cells into the parent page during
60829    ** balancing, and the dividers are adjacent and sorted.
60830    */
60831    assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
60832    assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */
60833  }else{
60834    int rc = sqlite3PagerWrite(pPage->pDbPage);
60835    if( rc!=SQLITE_OK ){
60836      *pRC = rc;
60837      return;
60838    }
60839    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
60840    data = pPage->aData;
60841    assert( &data[pPage->cellOffset]==pPage->aCellIdx );
60842    rc = allocateSpace(pPage, sz, &idx);
60843    if( rc ){ *pRC = rc; return; }
60844    /* The allocateSpace() routine guarantees the following properties
60845    ** if it returns successfully */
60846    assert( idx >= 0 );
60847    assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
60848    assert( idx+sz <= (int)pPage->pBt->usableSize );
60849    pPage->nFree -= (u16)(2 + sz);
60850    memcpy(&data[idx], pCell, sz);
60851    if( iChild ){
60852      put4byte(&data[idx], iChild);
60853    }
60854    pIns = pPage->aCellIdx + i*2;
60855    memmove(pIns+2, pIns, 2*(pPage->nCell - i));
60856    put2byte(pIns, idx);
60857    pPage->nCell++;
60858    /* increment the cell count */
60859    if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
60860    assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
60861#ifndef SQLITE_OMIT_AUTOVACUUM
60862    if( pPage->pBt->autoVacuum ){
60863      /* The cell may contain a pointer to an overflow page. If so, write
60864      ** the entry for the overflow page into the pointer map.
60865      */
60866      ptrmapPutOvflPtr(pPage, pCell, pRC);
60867    }
60868#endif
60869  }
60870}
60871
60872/*
60873** A CellArray object contains a cache of pointers and sizes for a
60874** consecutive sequence of cells that might be held multiple pages.
60875*/
60876typedef struct CellArray CellArray;
60877struct CellArray {
60878  int nCell;              /* Number of cells in apCell[] */
60879  MemPage *pRef;          /* Reference page */
60880  u8 **apCell;            /* All cells begin balanced */
60881  u16 *szCell;            /* Local size of all cells in apCell[] */
60882};
60883
60884/*
60885** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
60886** computed.
60887*/
60888static void populateCellCache(CellArray *p, int idx, int N){
60889  assert( idx>=0 && idx+N<=p->nCell );
60890  while( N>0 ){
60891    assert( p->apCell[idx]!=0 );
60892    if( p->szCell[idx]==0 ){
60893      p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
60894    }else{
60895      assert( CORRUPT_DB ||
60896              p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
60897    }
60898    idx++;
60899    N--;
60900  }
60901}
60902
60903/*
60904** Return the size of the Nth element of the cell array
60905*/
60906static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
60907  assert( N>=0 && N<p->nCell );
60908  assert( p->szCell[N]==0 );
60909  p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
60910  return p->szCell[N];
60911}
60912static u16 cachedCellSize(CellArray *p, int N){
60913  assert( N>=0 && N<p->nCell );
60914  if( p->szCell[N] ) return p->szCell[N];
60915  return computeCellSize(p, N);
60916}
60917
60918/*
60919** Array apCell[] contains pointers to nCell b-tree page cells. The
60920** szCell[] array contains the size in bytes of each cell. This function
60921** replaces the current contents of page pPg with the contents of the cell
60922** array.
60923**
60924** Some of the cells in apCell[] may currently be stored in pPg. This
60925** function works around problems caused by this by making a copy of any
60926** such cells before overwriting the page data.
60927**
60928** The MemPage.nFree field is invalidated by this function. It is the
60929** responsibility of the caller to set it correctly.
60930*/
60931static int rebuildPage(
60932  MemPage *pPg,                   /* Edit this page */
60933  int nCell,                      /* Final number of cells on page */
60934  u8 **apCell,                    /* Array of cells */
60935  u16 *szCell                     /* Array of cell sizes */
60936){
60937  const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */
60938  u8 * const aData = pPg->aData;           /* Pointer to data for pPg */
60939  const int usableSize = pPg->pBt->usableSize;
60940  u8 * const pEnd = &aData[usableSize];
60941  int i;
60942  u8 *pCellptr = pPg->aCellIdx;
60943  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
60944  u8 *pData;
60945
60946  i = get2byte(&aData[hdr+5]);
60947  memcpy(&pTmp[i], &aData[i], usableSize - i);
60948
60949  pData = pEnd;
60950  for(i=0; i<nCell; i++){
60951    u8 *pCell = apCell[i];
60952    if( pCell>aData && pCell<pEnd ){
60953      pCell = &pTmp[pCell - aData];
60954    }
60955    pData -= szCell[i];
60956    put2byte(pCellptr, (pData - aData));
60957    pCellptr += 2;
60958    if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
60959    memcpy(pData, pCell, szCell[i]);
60960    assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
60961    testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
60962  }
60963
60964  /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
60965  pPg->nCell = nCell;
60966  pPg->nOverflow = 0;
60967
60968  put2byte(&aData[hdr+1], 0);
60969  put2byte(&aData[hdr+3], pPg->nCell);
60970  put2byte(&aData[hdr+5], pData - aData);
60971  aData[hdr+7] = 0x00;
60972  return SQLITE_OK;
60973}
60974
60975/*
60976** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
60977** contains the size in bytes of each such cell. This function attempts to
60978** add the cells stored in the array to page pPg. If it cannot (because
60979** the page needs to be defragmented before the cells will fit), non-zero
60980** is returned. Otherwise, if the cells are added successfully, zero is
60981** returned.
60982**
60983** Argument pCellptr points to the first entry in the cell-pointer array
60984** (part of page pPg) to populate. After cell apCell[0] is written to the
60985** page body, a 16-bit offset is written to pCellptr. And so on, for each
60986** cell in the array. It is the responsibility of the caller to ensure
60987** that it is safe to overwrite this part of the cell-pointer array.
60988**
60989** When this function is called, *ppData points to the start of the
60990** content area on page pPg. If the size of the content area is extended,
60991** *ppData is updated to point to the new start of the content area
60992** before returning.
60993**
60994** Finally, argument pBegin points to the byte immediately following the
60995** end of the space required by this page for the cell-pointer area (for
60996** all cells - not just those inserted by the current call). If the content
60997** area must be extended to before this point in order to accomodate all
60998** cells in apCell[], then the cells do not fit and non-zero is returned.
60999*/
61000static int pageInsertArray(
61001  MemPage *pPg,                   /* Page to add cells to */
61002  u8 *pBegin,                     /* End of cell-pointer array */
61003  u8 **ppData,                    /* IN/OUT: Page content -area pointer */
61004  u8 *pCellptr,                   /* Pointer to cell-pointer area */
61005  int iFirst,                     /* Index of first cell to add */
61006  int nCell,                      /* Number of cells to add to pPg */
61007  CellArray *pCArray              /* Array of cells */
61008){
61009  int i;
61010  u8 *aData = pPg->aData;
61011  u8 *pData = *ppData;
61012  int iEnd = iFirst + nCell;
61013  assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
61014  for(i=iFirst; i<iEnd; i++){
61015    int sz, rc;
61016    u8 *pSlot;
61017    sz = cachedCellSize(pCArray, i);
61018    if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
61019      pData -= sz;
61020      if( pData<pBegin ) return 1;
61021      pSlot = pData;
61022    }
61023    /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
61024    ** database.  But they might for a corrupt database.  Hence use memmove()
61025    ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
61026    assert( (pSlot+sz)<=pCArray->apCell[i]
61027         || pSlot>=(pCArray->apCell[i]+sz)
61028         || CORRUPT_DB );
61029    memmove(pSlot, pCArray->apCell[i], sz);
61030    put2byte(pCellptr, (pSlot - aData));
61031    pCellptr += 2;
61032  }
61033  *ppData = pData;
61034  return 0;
61035}
61036
61037/*
61038** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
61039** contains the size in bytes of each such cell. This function adds the
61040** space associated with each cell in the array that is currently stored
61041** within the body of pPg to the pPg free-list. The cell-pointers and other
61042** fields of the page are not updated.
61043**
61044** This function returns the total number of cells added to the free-list.
61045*/
61046static int pageFreeArray(
61047  MemPage *pPg,                   /* Page to edit */
61048  int iFirst,                     /* First cell to delete */
61049  int nCell,                      /* Cells to delete */
61050  CellArray *pCArray              /* Array of cells */
61051){
61052  u8 * const aData = pPg->aData;
61053  u8 * const pEnd = &aData[pPg->pBt->usableSize];
61054  u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
61055  int nRet = 0;
61056  int i;
61057  int iEnd = iFirst + nCell;
61058  u8 *pFree = 0;
61059  int szFree = 0;
61060
61061  for(i=iFirst; i<iEnd; i++){
61062    u8 *pCell = pCArray->apCell[i];
61063    if( pCell>=pStart && pCell<pEnd ){
61064      int sz;
61065      /* No need to use cachedCellSize() here.  The sizes of all cells that
61066      ** are to be freed have already been computing while deciding which
61067      ** cells need freeing */
61068      sz = pCArray->szCell[i];  assert( sz>0 );
61069      if( pFree!=(pCell + sz) ){
61070        if( pFree ){
61071          assert( pFree>aData && (pFree - aData)<65536 );
61072          freeSpace(pPg, (u16)(pFree - aData), szFree);
61073        }
61074        pFree = pCell;
61075        szFree = sz;
61076        if( pFree+sz>pEnd ) return 0;
61077      }else{
61078        pFree = pCell;
61079        szFree += sz;
61080      }
61081      nRet++;
61082    }
61083  }
61084  if( pFree ){
61085    assert( pFree>aData && (pFree - aData)<65536 );
61086    freeSpace(pPg, (u16)(pFree - aData), szFree);
61087  }
61088  return nRet;
61089}
61090
61091/*
61092** apCell[] and szCell[] contains pointers to and sizes of all cells in the
61093** pages being balanced.  The current page, pPg, has pPg->nCell cells starting
61094** with apCell[iOld].  After balancing, this page should hold nNew cells
61095** starting at apCell[iNew].
61096**
61097** This routine makes the necessary adjustments to pPg so that it contains
61098** the correct cells after being balanced.
61099**
61100** The pPg->nFree field is invalid when this function returns. It is the
61101** responsibility of the caller to set it correctly.
61102*/
61103static int editPage(
61104  MemPage *pPg,                   /* Edit this page */
61105  int iOld,                       /* Index of first cell currently on page */
61106  int iNew,                       /* Index of new first cell on page */
61107  int nNew,                       /* Final number of cells on page */
61108  CellArray *pCArray              /* Array of cells and sizes */
61109){
61110  u8 * const aData = pPg->aData;
61111  const int hdr = pPg->hdrOffset;
61112  u8 *pBegin = &pPg->aCellIdx[nNew * 2];
61113  int nCell = pPg->nCell;       /* Cells stored on pPg */
61114  u8 *pData;
61115  u8 *pCellptr;
61116  int i;
61117  int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
61118  int iNewEnd = iNew + nNew;
61119
61120#ifdef SQLITE_DEBUG
61121  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
61122  memcpy(pTmp, aData, pPg->pBt->usableSize);
61123#endif
61124
61125  /* Remove cells from the start and end of the page */
61126  if( iOld<iNew ){
61127    int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
61128    memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
61129    nCell -= nShift;
61130  }
61131  if( iNewEnd < iOldEnd ){
61132    nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
61133  }
61134
61135  pData = &aData[get2byteNotZero(&aData[hdr+5])];
61136  if( pData<pBegin ) goto editpage_fail;
61137
61138  /* Add cells to the start of the page */
61139  if( iNew<iOld ){
61140    int nAdd = MIN(nNew,iOld-iNew);
61141    assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
61142    pCellptr = pPg->aCellIdx;
61143    memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
61144    if( pageInsertArray(
61145          pPg, pBegin, &pData, pCellptr,
61146          iNew, nAdd, pCArray
61147    ) ) goto editpage_fail;
61148    nCell += nAdd;
61149  }
61150
61151  /* Add any overflow cells */
61152  for(i=0; i<pPg->nOverflow; i++){
61153    int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
61154    if( iCell>=0 && iCell<nNew ){
61155      pCellptr = &pPg->aCellIdx[iCell * 2];
61156      memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
61157      nCell++;
61158      if( pageInsertArray(
61159            pPg, pBegin, &pData, pCellptr,
61160            iCell+iNew, 1, pCArray
61161      ) ) goto editpage_fail;
61162    }
61163  }
61164
61165  /* Append cells to the end of the page */
61166  pCellptr = &pPg->aCellIdx[nCell*2];
61167  if( pageInsertArray(
61168        pPg, pBegin, &pData, pCellptr,
61169        iNew+nCell, nNew-nCell, pCArray
61170  ) ) goto editpage_fail;
61171
61172  pPg->nCell = nNew;
61173  pPg->nOverflow = 0;
61174
61175  put2byte(&aData[hdr+3], pPg->nCell);
61176  put2byte(&aData[hdr+5], pData - aData);
61177
61178#ifdef SQLITE_DEBUG
61179  for(i=0; i<nNew && !CORRUPT_DB; i++){
61180    u8 *pCell = pCArray->apCell[i+iNew];
61181    int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
61182    if( pCell>=aData && pCell<&aData[pPg->pBt->usableSize] ){
61183      pCell = &pTmp[pCell - aData];
61184    }
61185    assert( 0==memcmp(pCell, &aData[iOff],
61186            pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
61187  }
61188#endif
61189
61190  return SQLITE_OK;
61191 editpage_fail:
61192  /* Unable to edit this page. Rebuild it from scratch instead. */
61193  populateCellCache(pCArray, iNew, nNew);
61194  return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
61195}
61196
61197/*
61198** The following parameters determine how many adjacent pages get involved
61199** in a balancing operation.  NN is the number of neighbors on either side
61200** of the page that participate in the balancing operation.  NB is the
61201** total number of pages that participate, including the target page and
61202** NN neighbors on either side.
61203**
61204** The minimum value of NN is 1 (of course).  Increasing NN above 1
61205** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
61206** in exchange for a larger degradation in INSERT and UPDATE performance.
61207** The value of NN appears to give the best results overall.
61208*/
61209#define NN 1             /* Number of neighbors on either side of pPage */
61210#define NB (NN*2+1)      /* Total pages involved in the balance */
61211
61212
61213#ifndef SQLITE_OMIT_QUICKBALANCE
61214/*
61215** This version of balance() handles the common special case where
61216** a new entry is being inserted on the extreme right-end of the
61217** tree, in other words, when the new entry will become the largest
61218** entry in the tree.
61219**
61220** Instead of trying to balance the 3 right-most leaf pages, just add
61221** a new page to the right-hand side and put the one new entry in
61222** that page.  This leaves the right side of the tree somewhat
61223** unbalanced.  But odds are that we will be inserting new entries
61224** at the end soon afterwards so the nearly empty page will quickly
61225** fill up.  On average.
61226**
61227** pPage is the leaf page which is the right-most page in the tree.
61228** pParent is its parent.  pPage must have a single overflow entry
61229** which is also the right-most entry on the page.
61230**
61231** The pSpace buffer is used to store a temporary copy of the divider
61232** cell that will be inserted into pParent. Such a cell consists of a 4
61233** byte page number followed by a variable length integer. In other
61234** words, at most 13 bytes. Hence the pSpace buffer must be at
61235** least 13 bytes in size.
61236*/
61237static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
61238  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
61239  MemPage *pNew;                       /* Newly allocated page */
61240  int rc;                              /* Return Code */
61241  Pgno pgnoNew;                        /* Page number of pNew */
61242
61243  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61244  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
61245  assert( pPage->nOverflow==1 );
61246
61247  /* This error condition is now caught prior to reaching this function */
61248  if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
61249
61250  /* Allocate a new page. This page will become the right-sibling of
61251  ** pPage. Make the parent page writable, so that the new divider cell
61252  ** may be inserted. If both these operations are successful, proceed.
61253  */
61254  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
61255
61256  if( rc==SQLITE_OK ){
61257
61258    u8 *pOut = &pSpace[4];
61259    u8 *pCell = pPage->apOvfl[0];
61260    u16 szCell = pPage->xCellSize(pPage, pCell);
61261    u8 *pStop;
61262
61263    assert( sqlite3PagerIswriteable(pNew->pDbPage) );
61264    assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
61265    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
61266    rc = rebuildPage(pNew, 1, &pCell, &szCell);
61267    if( NEVER(rc) ) return rc;
61268    pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
61269
61270    /* If this is an auto-vacuum database, update the pointer map
61271    ** with entries for the new page, and any pointer from the
61272    ** cell on the page to an overflow page. If either of these
61273    ** operations fails, the return code is set, but the contents
61274    ** of the parent page are still manipulated by thh code below.
61275    ** That is Ok, at this point the parent page is guaranteed to
61276    ** be marked as dirty. Returning an error code will cause a
61277    ** rollback, undoing any changes made to the parent page.
61278    */
61279    if( ISAUTOVACUUM ){
61280      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
61281      if( szCell>pNew->minLocal ){
61282        ptrmapPutOvflPtr(pNew, pCell, &rc);
61283      }
61284    }
61285
61286    /* Create a divider cell to insert into pParent. The divider cell
61287    ** consists of a 4-byte page number (the page number of pPage) and
61288    ** a variable length key value (which must be the same value as the
61289    ** largest key on pPage).
61290    **
61291    ** To find the largest key value on pPage, first find the right-most
61292    ** cell on pPage. The first two fields of this cell are the
61293    ** record-length (a variable length integer at most 32-bits in size)
61294    ** and the key value (a variable length integer, may have any value).
61295    ** The first of the while(...) loops below skips over the record-length
61296    ** field. The second while(...) loop copies the key value from the
61297    ** cell on pPage into the pSpace buffer.
61298    */
61299    pCell = findCell(pPage, pPage->nCell-1);
61300    pStop = &pCell[9];
61301    while( (*(pCell++)&0x80) && pCell<pStop );
61302    pStop = &pCell[9];
61303    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
61304
61305    /* Insert the new divider cell into pParent. */
61306    insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
61307               0, pPage->pgno, &rc);
61308
61309    /* Set the right-child pointer of pParent to point to the new page. */
61310    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
61311
61312    /* Release the reference to the new page. */
61313    releasePage(pNew);
61314  }
61315
61316  return rc;
61317}
61318#endif /* SQLITE_OMIT_QUICKBALANCE */
61319
61320#if 0
61321/*
61322** This function does not contribute anything to the operation of SQLite.
61323** it is sometimes activated temporarily while debugging code responsible
61324** for setting pointer-map entries.
61325*/
61326static int ptrmapCheckPages(MemPage **apPage, int nPage){
61327  int i, j;
61328  for(i=0; i<nPage; i++){
61329    Pgno n;
61330    u8 e;
61331    MemPage *pPage = apPage[i];
61332    BtShared *pBt = pPage->pBt;
61333    assert( pPage->isInit );
61334
61335    for(j=0; j<pPage->nCell; j++){
61336      CellInfo info;
61337      u8 *z;
61338
61339      z = findCell(pPage, j);
61340      pPage->xParseCell(pPage, z, &info);
61341      if( info.iOverflow ){
61342        Pgno ovfl = get4byte(&z[info.iOverflow]);
61343        ptrmapGet(pBt, ovfl, &e, &n);
61344        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
61345      }
61346      if( !pPage->leaf ){
61347        Pgno child = get4byte(z);
61348        ptrmapGet(pBt, child, &e, &n);
61349        assert( n==pPage->pgno && e==PTRMAP_BTREE );
61350      }
61351    }
61352    if( !pPage->leaf ){
61353      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
61354      ptrmapGet(pBt, child, &e, &n);
61355      assert( n==pPage->pgno && e==PTRMAP_BTREE );
61356    }
61357  }
61358  return 1;
61359}
61360#endif
61361
61362/*
61363** This function is used to copy the contents of the b-tree node stored
61364** on page pFrom to page pTo. If page pFrom was not a leaf page, then
61365** the pointer-map entries for each child page are updated so that the
61366** parent page stored in the pointer map is page pTo. If pFrom contained
61367** any cells with overflow page pointers, then the corresponding pointer
61368** map entries are also updated so that the parent page is page pTo.
61369**
61370** If pFrom is currently carrying any overflow cells (entries in the
61371** MemPage.apOvfl[] array), they are not copied to pTo.
61372**
61373** Before returning, page pTo is reinitialized using btreeInitPage().
61374**
61375** The performance of this function is not critical. It is only used by
61376** the balance_shallower() and balance_deeper() procedures, neither of
61377** which are called often under normal circumstances.
61378*/
61379static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
61380  if( (*pRC)==SQLITE_OK ){
61381    BtShared * const pBt = pFrom->pBt;
61382    u8 * const aFrom = pFrom->aData;
61383    u8 * const aTo = pTo->aData;
61384    int const iFromHdr = pFrom->hdrOffset;
61385    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
61386    int rc;
61387    int iData;
61388
61389
61390    assert( pFrom->isInit );
61391    assert( pFrom->nFree>=iToHdr );
61392    assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
61393
61394    /* Copy the b-tree node content from page pFrom to page pTo. */
61395    iData = get2byte(&aFrom[iFromHdr+5]);
61396    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
61397    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
61398
61399    /* Reinitialize page pTo so that the contents of the MemPage structure
61400    ** match the new data. The initialization of pTo can actually fail under
61401    ** fairly obscure circumstances, even though it is a copy of initialized
61402    ** page pFrom.
61403    */
61404    pTo->isInit = 0;
61405    rc = btreeInitPage(pTo);
61406    if( rc!=SQLITE_OK ){
61407      *pRC = rc;
61408      return;
61409    }
61410
61411    /* If this is an auto-vacuum database, update the pointer-map entries
61412    ** for any b-tree or overflow pages that pTo now contains the pointers to.
61413    */
61414    if( ISAUTOVACUUM ){
61415      *pRC = setChildPtrmaps(pTo);
61416    }
61417  }
61418}
61419
61420/*
61421** This routine redistributes cells on the iParentIdx'th child of pParent
61422** (hereafter "the page") and up to 2 siblings so that all pages have about the
61423** same amount of free space. Usually a single sibling on either side of the
61424** page are used in the balancing, though both siblings might come from one
61425** side if the page is the first or last child of its parent. If the page
61426** has fewer than 2 siblings (something which can only happen if the page
61427** is a root page or a child of a root page) then all available siblings
61428** participate in the balancing.
61429**
61430** The number of siblings of the page might be increased or decreased by
61431** one or two in an effort to keep pages nearly full but not over full.
61432**
61433** Note that when this routine is called, some of the cells on the page
61434** might not actually be stored in MemPage.aData[]. This can happen
61435** if the page is overfull. This routine ensures that all cells allocated
61436** to the page and its siblings fit into MemPage.aData[] before returning.
61437**
61438** In the course of balancing the page and its siblings, cells may be
61439** inserted into or removed from the parent page (pParent). Doing so
61440** may cause the parent page to become overfull or underfull. If this
61441** happens, it is the responsibility of the caller to invoke the correct
61442** balancing routine to fix this problem (see the balance() routine).
61443**
61444** If this routine fails for any reason, it might leave the database
61445** in a corrupted state. So if this routine fails, the database should
61446** be rolled back.
61447**
61448** The third argument to this function, aOvflSpace, is a pointer to a
61449** buffer big enough to hold one page. If while inserting cells into the parent
61450** page (pParent) the parent page becomes overfull, this buffer is
61451** used to store the parent's overflow cells. Because this function inserts
61452** a maximum of four divider cells into the parent page, and the maximum
61453** size of a cell stored within an internal node is always less than 1/4
61454** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
61455** enough for all overflow cells.
61456**
61457** If aOvflSpace is set to a null pointer, this function returns
61458** SQLITE_NOMEM.
61459*/
61460#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
61461#pragma optimize("", off)
61462#endif
61463static int balance_nonroot(
61464  MemPage *pParent,               /* Parent page of siblings being balanced */
61465  int iParentIdx,                 /* Index of "the page" in pParent */
61466  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
61467  int isRoot,                     /* True if pParent is a root-page */
61468  int bBulk                       /* True if this call is part of a bulk load */
61469){
61470  BtShared *pBt;               /* The whole database */
61471  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
61472  int nNew = 0;                /* Number of pages in apNew[] */
61473  int nOld;                    /* Number of pages in apOld[] */
61474  int i, j, k;                 /* Loop counters */
61475  int nxDiv;                   /* Next divider slot in pParent->aCell[] */
61476  int rc = SQLITE_OK;          /* The return code */
61477  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
61478  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
61479  int usableSpace;             /* Bytes in pPage beyond the header */
61480  int pageFlags;               /* Value of pPage->aData[0] */
61481  int iSpace1 = 0;             /* First unused byte of aSpace1[] */
61482  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
61483  int szScratch;               /* Size of scratch memory requested */
61484  MemPage *apOld[NB];          /* pPage and up to two siblings */
61485  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
61486  u8 *pRight;                  /* Location in parent of right-sibling pointer */
61487  u8 *apDiv[NB-1];             /* Divider cells in pParent */
61488  int cntNew[NB+2];            /* Index in b.paCell[] of cell after i-th page */
61489  int cntOld[NB+2];            /* Old index in b.apCell[] */
61490  int szNew[NB+2];             /* Combined size of cells placed on i-th page */
61491  u8 *aSpace1;                 /* Space for copies of dividers cells */
61492  Pgno pgno;                   /* Temp var to store a page number in */
61493  u8 abDone[NB+2];             /* True after i'th new page is populated */
61494  Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
61495  Pgno aPgOrder[NB+2];         /* Copy of aPgno[] used for sorting pages */
61496  u16 aPgFlags[NB+2];          /* flags field of new pages before shuffling */
61497  CellArray b;                  /* Parsed information on cells being balanced */
61498
61499  memset(abDone, 0, sizeof(abDone));
61500  b.nCell = 0;
61501  b.apCell = 0;
61502  pBt = pParent->pBt;
61503  assert( sqlite3_mutex_held(pBt->mutex) );
61504  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
61505
61506#if 0
61507  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
61508#endif
61509
61510  /* At this point pParent may have at most one overflow cell. And if
61511  ** this overflow cell is present, it must be the cell with
61512  ** index iParentIdx. This scenario comes about when this function
61513  ** is called (indirectly) from sqlite3BtreeDelete().
61514  */
61515  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
61516  assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
61517
61518  if( !aOvflSpace ){
61519    return SQLITE_NOMEM;
61520  }
61521
61522  /* Find the sibling pages to balance. Also locate the cells in pParent
61523  ** that divide the siblings. An attempt is made to find NN siblings on
61524  ** either side of pPage. More siblings are taken from one side, however,
61525  ** if there are fewer than NN siblings on the other side. If pParent
61526  ** has NB or fewer children then all children of pParent are taken.
61527  **
61528  ** This loop also drops the divider cells from the parent page. This
61529  ** way, the remainder of the function does not have to deal with any
61530  ** overflow cells in the parent page, since if any existed they will
61531  ** have already been removed.
61532  */
61533  i = pParent->nOverflow + pParent->nCell;
61534  if( i<2 ){
61535    nxDiv = 0;
61536  }else{
61537    assert( bBulk==0 || bBulk==1 );
61538    if( iParentIdx==0 ){
61539      nxDiv = 0;
61540    }else if( iParentIdx==i ){
61541      nxDiv = i-2+bBulk;
61542    }else{
61543      nxDiv = iParentIdx-1;
61544    }
61545    i = 2-bBulk;
61546  }
61547  nOld = i+1;
61548  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
61549    pRight = &pParent->aData[pParent->hdrOffset+8];
61550  }else{
61551    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
61552  }
61553  pgno = get4byte(pRight);
61554  while( 1 ){
61555    rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
61556    if( rc ){
61557      memset(apOld, 0, (i+1)*sizeof(MemPage*));
61558      goto balance_cleanup;
61559    }
61560    nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
61561    if( (i--)==0 ) break;
61562
61563    if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
61564      apDiv[i] = pParent->apOvfl[0];
61565      pgno = get4byte(apDiv[i]);
61566      szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
61567      pParent->nOverflow = 0;
61568    }else{
61569      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
61570      pgno = get4byte(apDiv[i]);
61571      szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
61572
61573      /* Drop the cell from the parent page. apDiv[i] still points to
61574      ** the cell within the parent, even though it has been dropped.
61575      ** This is safe because dropping a cell only overwrites the first
61576      ** four bytes of it, and this function does not need the first
61577      ** four bytes of the divider cell. So the pointer is safe to use
61578      ** later on.
61579      **
61580      ** But not if we are in secure-delete mode. In secure-delete mode,
61581      ** the dropCell() routine will overwrite the entire cell with zeroes.
61582      ** In this case, temporarily copy the cell into the aOvflSpace[]
61583      ** buffer. It will be copied out again as soon as the aSpace[] buffer
61584      ** is allocated.  */
61585      if( pBt->btsFlags & BTS_SECURE_DELETE ){
61586        int iOff;
61587
61588        iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
61589        if( (iOff+szNew[i])>(int)pBt->usableSize ){
61590          rc = SQLITE_CORRUPT_BKPT;
61591          memset(apOld, 0, (i+1)*sizeof(MemPage*));
61592          goto balance_cleanup;
61593        }else{
61594          memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
61595          apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
61596        }
61597      }
61598      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
61599    }
61600  }
61601
61602  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
61603  ** alignment */
61604  nMaxCells = (nMaxCells + 3)&~3;
61605
61606  /*
61607  ** Allocate space for memory structures
61608  */
61609  szScratch =
61610       nMaxCells*sizeof(u8*)                       /* b.apCell */
61611     + nMaxCells*sizeof(u16)                       /* b.szCell */
61612     + pBt->pageSize;                              /* aSpace1 */
61613
61614  /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
61615  ** that is more than 6 times the database page size. */
61616  assert( szScratch<=6*(int)pBt->pageSize );
61617  b.apCell = sqlite3ScratchMalloc( szScratch );
61618  if( b.apCell==0 ){
61619    rc = SQLITE_NOMEM;
61620    goto balance_cleanup;
61621  }
61622  b.szCell = (u16*)&b.apCell[nMaxCells];
61623  aSpace1 = (u8*)&b.szCell[nMaxCells];
61624  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
61625
61626  /*
61627  ** Load pointers to all cells on sibling pages and the divider cells
61628  ** into the local b.apCell[] array.  Make copies of the divider cells
61629  ** into space obtained from aSpace1[]. The divider cells have already
61630  ** been removed from pParent.
61631  **
61632  ** If the siblings are on leaf pages, then the child pointers of the
61633  ** divider cells are stripped from the cells before they are copied
61634  ** into aSpace1[].  In this way, all cells in b.apCell[] are without
61635  ** child pointers.  If siblings are not leaves, then all cell in
61636  ** b.apCell[] include child pointers.  Either way, all cells in b.apCell[]
61637  ** are alike.
61638  **
61639  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
61640  **       leafData:  1 if pPage holds key+data and pParent holds only keys.
61641  */
61642  b.pRef = apOld[0];
61643  leafCorrection = b.pRef->leaf*4;
61644  leafData = b.pRef->intKeyLeaf;
61645  for(i=0; i<nOld; i++){
61646    MemPage *pOld = apOld[i];
61647    int limit = pOld->nCell;
61648    u8 *aData = pOld->aData;
61649    u16 maskPage = pOld->maskPage;
61650    u8 *piCell = aData + pOld->cellOffset;
61651    u8 *piEnd;
61652
61653    /* Verify that all sibling pages are of the same "type" (table-leaf,
61654    ** table-interior, index-leaf, or index-interior).
61655    */
61656    if( pOld->aData[0]!=apOld[0]->aData[0] ){
61657      rc = SQLITE_CORRUPT_BKPT;
61658      goto balance_cleanup;
61659    }
61660
61661    /* Load b.apCell[] with pointers to all cells in pOld.  If pOld
61662    ** constains overflow cells, include them in the b.apCell[] array
61663    ** in the correct spot.
61664    **
61665    ** Note that when there are multiple overflow cells, it is always the
61666    ** case that they are sequential and adjacent.  This invariant arises
61667    ** because multiple overflows can only occurs when inserting divider
61668    ** cells into a parent on a prior balance, and divider cells are always
61669    ** adjacent and are inserted in order.  There is an assert() tagged
61670    ** with "NOTE 1" in the overflow cell insertion loop to prove this
61671    ** invariant.
61672    **
61673    ** This must be done in advance.  Once the balance starts, the cell
61674    ** offset section of the btree page will be overwritten and we will no
61675    ** long be able to find the cells if a pointer to each cell is not saved
61676    ** first.
61677    */
61678    memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*limit);
61679    if( pOld->nOverflow>0 ){
61680      memset(&b.szCell[b.nCell+limit], 0, sizeof(b.szCell[0])*pOld->nOverflow);
61681      limit = pOld->aiOvfl[0];
61682      for(j=0; j<limit; j++){
61683        b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
61684        piCell += 2;
61685        b.nCell++;
61686      }
61687      for(k=0; k<pOld->nOverflow; k++){
61688        assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
61689        b.apCell[b.nCell] = pOld->apOvfl[k];
61690        b.nCell++;
61691      }
61692    }
61693    piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
61694    while( piCell<piEnd ){
61695      assert( b.nCell<nMaxCells );
61696      b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
61697      piCell += 2;
61698      b.nCell++;
61699    }
61700
61701    cntOld[i] = b.nCell;
61702    if( i<nOld-1 && !leafData){
61703      u16 sz = (u16)szNew[i];
61704      u8 *pTemp;
61705      assert( b.nCell<nMaxCells );
61706      b.szCell[b.nCell] = sz;
61707      pTemp = &aSpace1[iSpace1];
61708      iSpace1 += sz;
61709      assert( sz<=pBt->maxLocal+23 );
61710      assert( iSpace1 <= (int)pBt->pageSize );
61711      memcpy(pTemp, apDiv[i], sz);
61712      b.apCell[b.nCell] = pTemp+leafCorrection;
61713      assert( leafCorrection==0 || leafCorrection==4 );
61714      b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
61715      if( !pOld->leaf ){
61716        assert( leafCorrection==0 );
61717        assert( pOld->hdrOffset==0 );
61718        /* The right pointer of the child page pOld becomes the left
61719        ** pointer of the divider cell */
61720        memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
61721      }else{
61722        assert( leafCorrection==4 );
61723        while( b.szCell[b.nCell]<4 ){
61724          /* Do not allow any cells smaller than 4 bytes. If a smaller cell
61725          ** does exist, pad it with 0x00 bytes. */
61726          assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
61727          assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
61728          aSpace1[iSpace1++] = 0x00;
61729          b.szCell[b.nCell]++;
61730        }
61731      }
61732      b.nCell++;
61733    }
61734  }
61735
61736  /*
61737  ** Figure out the number of pages needed to hold all b.nCell cells.
61738  ** Store this number in "k".  Also compute szNew[] which is the total
61739  ** size of all cells on the i-th page and cntNew[] which is the index
61740  ** in b.apCell[] of the cell that divides page i from page i+1.
61741  ** cntNew[k] should equal b.nCell.
61742  **
61743  ** Values computed by this block:
61744  **
61745  **           k: The total number of sibling pages
61746  **    szNew[i]: Spaced used on the i-th sibling page.
61747  **   cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
61748  **              the right of the i-th sibling page.
61749  ** usableSpace: Number of bytes of space available on each sibling.
61750  **
61751  */
61752  usableSpace = pBt->usableSize - 12 + leafCorrection;
61753  for(i=0; i<nOld; i++){
61754    MemPage *p = apOld[i];
61755    szNew[i] = usableSpace - p->nFree;
61756    if( szNew[i]<0 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
61757    for(j=0; j<p->nOverflow; j++){
61758      szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
61759    }
61760    cntNew[i] = cntOld[i];
61761  }
61762  k = nOld;
61763  for(i=0; i<k; i++){
61764    int sz;
61765    while( szNew[i]>usableSpace ){
61766      if( i+1>=k ){
61767        k = i+2;
61768        if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
61769        szNew[k-1] = 0;
61770        cntNew[k-1] = b.nCell;
61771      }
61772      sz = 2 + cachedCellSize(&b, cntNew[i]-1);
61773      szNew[i] -= sz;
61774      if( !leafData ){
61775        if( cntNew[i]<b.nCell ){
61776          sz = 2 + cachedCellSize(&b, cntNew[i]);
61777        }else{
61778          sz = 0;
61779        }
61780      }
61781      szNew[i+1] += sz;
61782      cntNew[i]--;
61783    }
61784    while( cntNew[i]<b.nCell ){
61785      sz = 2 + cachedCellSize(&b, cntNew[i]);
61786      if( szNew[i]+sz>usableSpace ) break;
61787      szNew[i] += sz;
61788      cntNew[i]++;
61789      if( !leafData ){
61790        if( cntNew[i]<b.nCell ){
61791          sz = 2 + cachedCellSize(&b, cntNew[i]);
61792        }else{
61793          sz = 0;
61794        }
61795      }
61796      szNew[i+1] -= sz;
61797    }
61798    if( cntNew[i]>=b.nCell ){
61799      k = i+1;
61800    }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
61801      rc = SQLITE_CORRUPT_BKPT;
61802      goto balance_cleanup;
61803    }
61804  }
61805
61806  /*
61807  ** The packing computed by the previous block is biased toward the siblings
61808  ** on the left side (siblings with smaller keys). The left siblings are
61809  ** always nearly full, while the right-most sibling might be nearly empty.
61810  ** The next block of code attempts to adjust the packing of siblings to
61811  ** get a better balance.
61812  **
61813  ** This adjustment is more than an optimization.  The packing above might
61814  ** be so out of balance as to be illegal.  For example, the right-most
61815  ** sibling might be completely empty.  This adjustment is not optional.
61816  */
61817  for(i=k-1; i>0; i--){
61818    int szRight = szNew[i];  /* Size of sibling on the right */
61819    int szLeft = szNew[i-1]; /* Size of sibling on the left */
61820    int r;              /* Index of right-most cell in left sibling */
61821    int d;              /* Index of first cell to the left of right sibling */
61822
61823    r = cntNew[i-1] - 1;
61824    d = r + 1 - leafData;
61825    (void)cachedCellSize(&b, d);
61826    do{
61827      assert( d<nMaxCells );
61828      assert( r<nMaxCells );
61829      (void)cachedCellSize(&b, r);
61830      if( szRight!=0
61831       && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+2)) ){
61832        break;
61833      }
61834      szRight += b.szCell[d] + 2;
61835      szLeft -= b.szCell[r] + 2;
61836      cntNew[i-1] = r;
61837      r--;
61838      d--;
61839    }while( r>=0 );
61840    szNew[i] = szRight;
61841    szNew[i-1] = szLeft;
61842    if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
61843      rc = SQLITE_CORRUPT_BKPT;
61844      goto balance_cleanup;
61845    }
61846  }
61847
61848  /* Sanity check:  For a non-corrupt database file one of the follwing
61849  ** must be true:
61850  **    (1) We found one or more cells (cntNew[0])>0), or
61851  **    (2) pPage is a virtual root page.  A virtual root page is when
61852  **        the real root page is page 1 and we are the only child of
61853  **        that page.
61854  */
61855  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
61856  TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
61857    apOld[0]->pgno, apOld[0]->nCell,
61858    nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
61859    nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
61860  ));
61861
61862  /*
61863  ** Allocate k new pages.  Reuse old pages where possible.
61864  */
61865  pageFlags = apOld[0]->aData[0];
61866  for(i=0; i<k; i++){
61867    MemPage *pNew;
61868    if( i<nOld ){
61869      pNew = apNew[i] = apOld[i];
61870      apOld[i] = 0;
61871      rc = sqlite3PagerWrite(pNew->pDbPage);
61872      nNew++;
61873      if( rc ) goto balance_cleanup;
61874    }else{
61875      assert( i>0 );
61876      rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
61877      if( rc ) goto balance_cleanup;
61878      zeroPage(pNew, pageFlags);
61879      apNew[i] = pNew;
61880      nNew++;
61881      cntOld[i] = b.nCell;
61882
61883      /* Set the pointer-map entry for the new sibling page. */
61884      if( ISAUTOVACUUM ){
61885        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
61886        if( rc!=SQLITE_OK ){
61887          goto balance_cleanup;
61888        }
61889      }
61890    }
61891  }
61892
61893  /*
61894  ** Reassign page numbers so that the new pages are in ascending order.
61895  ** This helps to keep entries in the disk file in order so that a scan
61896  ** of the table is closer to a linear scan through the file. That in turn
61897  ** helps the operating system to deliver pages from the disk more rapidly.
61898  **
61899  ** An O(n^2) insertion sort algorithm is used, but since n is never more
61900  ** than (NB+2) (a small constant), that should not be a problem.
61901  **
61902  ** When NB==3, this one optimization makes the database about 25% faster
61903  ** for large insertions and deletions.
61904  */
61905  for(i=0; i<nNew; i++){
61906    aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
61907    aPgFlags[i] = apNew[i]->pDbPage->flags;
61908    for(j=0; j<i; j++){
61909      if( aPgno[j]==aPgno[i] ){
61910        /* This branch is taken if the set of sibling pages somehow contains
61911        ** duplicate entries. This can happen if the database is corrupt.
61912        ** It would be simpler to detect this as part of the loop below, but
61913        ** we do the detection here in order to avoid populating the pager
61914        ** cache with two separate objects associated with the same
61915        ** page number.  */
61916        assert( CORRUPT_DB );
61917        rc = SQLITE_CORRUPT_BKPT;
61918        goto balance_cleanup;
61919      }
61920    }
61921  }
61922  for(i=0; i<nNew; i++){
61923    int iBest = 0;                /* aPgno[] index of page number to use */
61924    for(j=1; j<nNew; j++){
61925      if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
61926    }
61927    pgno = aPgOrder[iBest];
61928    aPgOrder[iBest] = 0xffffffff;
61929    if( iBest!=i ){
61930      if( iBest>i ){
61931        sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
61932      }
61933      sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
61934      apNew[i]->pgno = pgno;
61935    }
61936  }
61937
61938  TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
61939         "%d(%d nc=%d) %d(%d nc=%d)\n",
61940    apNew[0]->pgno, szNew[0], cntNew[0],
61941    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
61942    nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
61943    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
61944    nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
61945    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
61946    nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
61947    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
61948    nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
61949  ));
61950
61951  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
61952  put4byte(pRight, apNew[nNew-1]->pgno);
61953
61954  /* If the sibling pages are not leaves, ensure that the right-child pointer
61955  ** of the right-most new sibling page is set to the value that was
61956  ** originally in the same field of the right-most old sibling page. */
61957  if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
61958    MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
61959    memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
61960  }
61961
61962  /* Make any required updates to pointer map entries associated with
61963  ** cells stored on sibling pages following the balance operation. Pointer
61964  ** map entries associated with divider cells are set by the insertCell()
61965  ** routine. The associated pointer map entries are:
61966  **
61967  **   a) if the cell contains a reference to an overflow chain, the
61968  **      entry associated with the first page in the overflow chain, and
61969  **
61970  **   b) if the sibling pages are not leaves, the child page associated
61971  **      with the cell.
61972  **
61973  ** If the sibling pages are not leaves, then the pointer map entry
61974  ** associated with the right-child of each sibling may also need to be
61975  ** updated. This happens below, after the sibling pages have been
61976  ** populated, not here.
61977  */
61978  if( ISAUTOVACUUM ){
61979    MemPage *pNew = apNew[0];
61980    u8 *aOld = pNew->aData;
61981    int cntOldNext = pNew->nCell + pNew->nOverflow;
61982    int usableSize = pBt->usableSize;
61983    int iNew = 0;
61984    int iOld = 0;
61985
61986    for(i=0; i<b.nCell; i++){
61987      u8 *pCell = b.apCell[i];
61988      if( i==cntOldNext ){
61989        MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
61990        cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
61991        aOld = pOld->aData;
61992      }
61993      if( i==cntNew[iNew] ){
61994        pNew = apNew[++iNew];
61995        if( !leafData ) continue;
61996      }
61997
61998      /* Cell pCell is destined for new sibling page pNew. Originally, it
61999      ** was either part of sibling page iOld (possibly an overflow cell),
62000      ** or else the divider cell to the left of sibling page iOld. So,
62001      ** if sibling page iOld had the same page number as pNew, and if
62002      ** pCell really was a part of sibling page iOld (not a divider or
62003      ** overflow cell), we can skip updating the pointer map entries.  */
62004      if( iOld>=nNew
62005       || pNew->pgno!=aPgno[iOld]
62006       || pCell<aOld
62007       || pCell>=&aOld[usableSize]
62008      ){
62009        if( !leafCorrection ){
62010          ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
62011        }
62012        if( cachedCellSize(&b,i)>pNew->minLocal ){
62013          ptrmapPutOvflPtr(pNew, pCell, &rc);
62014        }
62015        if( rc ) goto balance_cleanup;
62016      }
62017    }
62018  }
62019
62020  /* Insert new divider cells into pParent. */
62021  for(i=0; i<nNew-1; i++){
62022    u8 *pCell;
62023    u8 *pTemp;
62024    int sz;
62025    MemPage *pNew = apNew[i];
62026    j = cntNew[i];
62027
62028    assert( j<nMaxCells );
62029    assert( b.apCell[j]!=0 );
62030    pCell = b.apCell[j];
62031    sz = b.szCell[j] + leafCorrection;
62032    pTemp = &aOvflSpace[iOvflSpace];
62033    if( !pNew->leaf ){
62034      memcpy(&pNew->aData[8], pCell, 4);
62035    }else if( leafData ){
62036      /* If the tree is a leaf-data tree, and the siblings are leaves,
62037      ** then there is no divider cell in b.apCell[]. Instead, the divider
62038      ** cell consists of the integer key for the right-most cell of
62039      ** the sibling-page assembled above only.
62040      */
62041      CellInfo info;
62042      j--;
62043      pNew->xParseCell(pNew, b.apCell[j], &info);
62044      pCell = pTemp;
62045      sz = 4 + putVarint(&pCell[4], info.nKey);
62046      pTemp = 0;
62047    }else{
62048      pCell -= 4;
62049      /* Obscure case for non-leaf-data trees: If the cell at pCell was
62050      ** previously stored on a leaf node, and its reported size was 4
62051      ** bytes, then it may actually be smaller than this
62052      ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
62053      ** any cell). But it is important to pass the correct size to
62054      ** insertCell(), so reparse the cell now.
62055      **
62056      ** Note that this can never happen in an SQLite data file, as all
62057      ** cells are at least 4 bytes. It only happens in b-trees used
62058      ** to evaluate "IN (SELECT ...)" and similar clauses.
62059      */
62060      if( b.szCell[j]==4 ){
62061        assert(leafCorrection==4);
62062        sz = pParent->xCellSize(pParent, pCell);
62063      }
62064    }
62065    iOvflSpace += sz;
62066    assert( sz<=pBt->maxLocal+23 );
62067    assert( iOvflSpace <= (int)pBt->pageSize );
62068    insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
62069    if( rc!=SQLITE_OK ) goto balance_cleanup;
62070    assert( sqlite3PagerIswriteable(pParent->pDbPage) );
62071  }
62072
62073  /* Now update the actual sibling pages. The order in which they are updated
62074  ** is important, as this code needs to avoid disrupting any page from which
62075  ** cells may still to be read. In practice, this means:
62076  **
62077  **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
62078  **      then it is not safe to update page apNew[iPg] until after
62079  **      the left-hand sibling apNew[iPg-1] has been updated.
62080  **
62081  **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
62082  **      then it is not safe to update page apNew[iPg] until after
62083  **      the right-hand sibling apNew[iPg+1] has been updated.
62084  **
62085  ** If neither of the above apply, the page is safe to update.
62086  **
62087  ** The iPg value in the following loop starts at nNew-1 goes down
62088  ** to 0, then back up to nNew-1 again, thus making two passes over
62089  ** the pages.  On the initial downward pass, only condition (1) above
62090  ** needs to be tested because (2) will always be true from the previous
62091  ** step.  On the upward pass, both conditions are always true, so the
62092  ** upwards pass simply processes pages that were missed on the downward
62093  ** pass.
62094  */
62095  for(i=1-nNew; i<nNew; i++){
62096    int iPg = i<0 ? -i : i;
62097    assert( iPg>=0 && iPg<nNew );
62098    if( abDone[iPg] ) continue;         /* Skip pages already processed */
62099    if( i>=0                            /* On the upwards pass, or... */
62100     || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */
62101    ){
62102      int iNew;
62103      int iOld;
62104      int nNewCell;
62105
62106      /* Verify condition (1):  If cells are moving left, update iPg
62107      ** only after iPg-1 has already been updated. */
62108      assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
62109
62110      /* Verify condition (2):  If cells are moving right, update iPg
62111      ** only after iPg+1 has already been updated. */
62112      assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
62113
62114      if( iPg==0 ){
62115        iNew = iOld = 0;
62116        nNewCell = cntNew[0];
62117      }else{
62118        iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
62119        iNew = cntNew[iPg-1] + !leafData;
62120        nNewCell = cntNew[iPg] - iNew;
62121      }
62122
62123      rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
62124      if( rc ) goto balance_cleanup;
62125      abDone[iPg]++;
62126      apNew[iPg]->nFree = usableSpace-szNew[iPg];
62127      assert( apNew[iPg]->nOverflow==0 );
62128      assert( apNew[iPg]->nCell==nNewCell );
62129    }
62130  }
62131
62132  /* All pages have been processed exactly once */
62133  assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
62134
62135  assert( nOld>0 );
62136  assert( nNew>0 );
62137
62138  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
62139    /* The root page of the b-tree now contains no cells. The only sibling
62140    ** page is the right-child of the parent. Copy the contents of the
62141    ** child page into the parent, decreasing the overall height of the
62142    ** b-tree structure by one. This is described as the "balance-shallower"
62143    ** sub-algorithm in some documentation.
62144    **
62145    ** If this is an auto-vacuum database, the call to copyNodeContent()
62146    ** sets all pointer-map entries corresponding to database image pages
62147    ** for which the pointer is stored within the content being copied.
62148    **
62149    ** It is critical that the child page be defragmented before being
62150    ** copied into the parent, because if the parent is page 1 then it will
62151    ** by smaller than the child due to the database header, and so all the
62152    ** free space needs to be up front.
62153    */
62154    assert( nNew==1 || CORRUPT_DB );
62155    rc = defragmentPage(apNew[0]);
62156    testcase( rc!=SQLITE_OK );
62157    assert( apNew[0]->nFree ==
62158        (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
62159      || rc!=SQLITE_OK
62160    );
62161    copyNodeContent(apNew[0], pParent, &rc);
62162    freePage(apNew[0], &rc);
62163  }else if( ISAUTOVACUUM && !leafCorrection ){
62164    /* Fix the pointer map entries associated with the right-child of each
62165    ** sibling page. All other pointer map entries have already been taken
62166    ** care of.  */
62167    for(i=0; i<nNew; i++){
62168      u32 key = get4byte(&apNew[i]->aData[8]);
62169      ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
62170    }
62171  }
62172
62173  assert( pParent->isInit );
62174  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
62175          nOld, nNew, b.nCell));
62176
62177  /* Free any old pages that were not reused as new pages.
62178  */
62179  for(i=nNew; i<nOld; i++){
62180    freePage(apOld[i], &rc);
62181  }
62182
62183#if 0
62184  if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
62185    /* The ptrmapCheckPages() contains assert() statements that verify that
62186    ** all pointer map pages are set correctly. This is helpful while
62187    ** debugging. This is usually disabled because a corrupt database may
62188    ** cause an assert() statement to fail.  */
62189    ptrmapCheckPages(apNew, nNew);
62190    ptrmapCheckPages(&pParent, 1);
62191  }
62192#endif
62193
62194  /*
62195  ** Cleanup before returning.
62196  */
62197balance_cleanup:
62198  sqlite3ScratchFree(b.apCell);
62199  for(i=0; i<nOld; i++){
62200    releasePage(apOld[i]);
62201  }
62202  for(i=0; i<nNew; i++){
62203    releasePage(apNew[i]);
62204  }
62205
62206  return rc;
62207}
62208#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
62209#pragma optimize("", on)
62210#endif
62211
62212
62213/*
62214** This function is called when the root page of a b-tree structure is
62215** overfull (has one or more overflow pages).
62216**
62217** A new child page is allocated and the contents of the current root
62218** page, including overflow cells, are copied into the child. The root
62219** page is then overwritten to make it an empty page with the right-child
62220** pointer pointing to the new page.
62221**
62222** Before returning, all pointer-map entries corresponding to pages
62223** that the new child-page now contains pointers to are updated. The
62224** entry corresponding to the new right-child pointer of the root
62225** page is also updated.
62226**
62227** If successful, *ppChild is set to contain a reference to the child
62228** page and SQLITE_OK is returned. In this case the caller is required
62229** to call releasePage() on *ppChild exactly once. If an error occurs,
62230** an error code is returned and *ppChild is set to 0.
62231*/
62232static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
62233  int rc;                        /* Return value from subprocedures */
62234  MemPage *pChild = 0;           /* Pointer to a new child page */
62235  Pgno pgnoChild = 0;            /* Page number of the new child page */
62236  BtShared *pBt = pRoot->pBt;    /* The BTree */
62237
62238  assert( pRoot->nOverflow>0 );
62239  assert( sqlite3_mutex_held(pBt->mutex) );
62240
62241  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
62242  ** page that will become the new right-child of pPage. Copy the contents
62243  ** of the node stored on pRoot into the new child page.
62244  */
62245  rc = sqlite3PagerWrite(pRoot->pDbPage);
62246  if( rc==SQLITE_OK ){
62247    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
62248    copyNodeContent(pRoot, pChild, &rc);
62249    if( ISAUTOVACUUM ){
62250      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
62251    }
62252  }
62253  if( rc ){
62254    *ppChild = 0;
62255    releasePage(pChild);
62256    return rc;
62257  }
62258  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
62259  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
62260  assert( pChild->nCell==pRoot->nCell );
62261
62262  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
62263
62264  /* Copy the overflow cells from pRoot to pChild */
62265  memcpy(pChild->aiOvfl, pRoot->aiOvfl,
62266         pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
62267  memcpy(pChild->apOvfl, pRoot->apOvfl,
62268         pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
62269  pChild->nOverflow = pRoot->nOverflow;
62270
62271  /* Zero the contents of pRoot. Then install pChild as the right-child. */
62272  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
62273  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
62274
62275  *ppChild = pChild;
62276  return SQLITE_OK;
62277}
62278
62279/*
62280** The page that pCur currently points to has just been modified in
62281** some way. This function figures out if this modification means the
62282** tree needs to be balanced, and if so calls the appropriate balancing
62283** routine. Balancing routines are:
62284**
62285**   balance_quick()
62286**   balance_deeper()
62287**   balance_nonroot()
62288*/
62289static int balance(BtCursor *pCur){
62290  int rc = SQLITE_OK;
62291  const int nMin = pCur->pBt->usableSize * 2 / 3;
62292  u8 aBalanceQuickSpace[13];
62293  u8 *pFree = 0;
62294
62295  TESTONLY( int balance_quick_called = 0 );
62296  TESTONLY( int balance_deeper_called = 0 );
62297
62298  do {
62299    int iPage = pCur->iPage;
62300    MemPage *pPage = pCur->apPage[iPage];
62301
62302    if( iPage==0 ){
62303      if( pPage->nOverflow ){
62304        /* The root page of the b-tree is overfull. In this case call the
62305        ** balance_deeper() function to create a new child for the root-page
62306        ** and copy the current contents of the root-page to it. The
62307        ** next iteration of the do-loop will balance the child page.
62308        */
62309        assert( (balance_deeper_called++)==0 );
62310        rc = balance_deeper(pPage, &pCur->apPage[1]);
62311        if( rc==SQLITE_OK ){
62312          pCur->iPage = 1;
62313          pCur->aiIdx[0] = 0;
62314          pCur->aiIdx[1] = 0;
62315          assert( pCur->apPage[1]->nOverflow );
62316        }
62317      }else{
62318        break;
62319      }
62320    }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
62321      break;
62322    }else{
62323      MemPage * const pParent = pCur->apPage[iPage-1];
62324      int const iIdx = pCur->aiIdx[iPage-1];
62325
62326      rc = sqlite3PagerWrite(pParent->pDbPage);
62327      if( rc==SQLITE_OK ){
62328#ifndef SQLITE_OMIT_QUICKBALANCE
62329        if( pPage->intKeyLeaf
62330         && pPage->nOverflow==1
62331         && pPage->aiOvfl[0]==pPage->nCell
62332         && pParent->pgno!=1
62333         && pParent->nCell==iIdx
62334        ){
62335          /* Call balance_quick() to create a new sibling of pPage on which
62336          ** to store the overflow cell. balance_quick() inserts a new cell
62337          ** into pParent, which may cause pParent overflow. If this
62338          ** happens, the next iteration of the do-loop will balance pParent
62339          ** use either balance_nonroot() or balance_deeper(). Until this
62340          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
62341          ** buffer.
62342          **
62343          ** The purpose of the following assert() is to check that only a
62344          ** single call to balance_quick() is made for each call to this
62345          ** function. If this were not verified, a subtle bug involving reuse
62346          ** of the aBalanceQuickSpace[] might sneak in.
62347          */
62348          assert( (balance_quick_called++)==0 );
62349          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
62350        }else
62351#endif
62352        {
62353          /* In this case, call balance_nonroot() to redistribute cells
62354          ** between pPage and up to 2 of its sibling pages. This involves
62355          ** modifying the contents of pParent, which may cause pParent to
62356          ** become overfull or underfull. The next iteration of the do-loop
62357          ** will balance the parent page to correct this.
62358          **
62359          ** If the parent page becomes overfull, the overflow cell or cells
62360          ** are stored in the pSpace buffer allocated immediately below.
62361          ** A subsequent iteration of the do-loop will deal with this by
62362          ** calling balance_nonroot() (balance_deeper() may be called first,
62363          ** but it doesn't deal with overflow cells - just moves them to a
62364          ** different page). Once this subsequent call to balance_nonroot()
62365          ** has completed, it is safe to release the pSpace buffer used by
62366          ** the previous call, as the overflow cell data will have been
62367          ** copied either into the body of a database page or into the new
62368          ** pSpace buffer passed to the latter call to balance_nonroot().
62369          */
62370          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
62371          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
62372                               pCur->hints&BTREE_BULKLOAD);
62373          if( pFree ){
62374            /* If pFree is not NULL, it points to the pSpace buffer used
62375            ** by a previous call to balance_nonroot(). Its contents are
62376            ** now stored either on real database pages or within the
62377            ** new pSpace buffer, so it may be safely freed here. */
62378            sqlite3PageFree(pFree);
62379          }
62380
62381          /* The pSpace buffer will be freed after the next call to
62382          ** balance_nonroot(), or just before this function returns, whichever
62383          ** comes first. */
62384          pFree = pSpace;
62385        }
62386      }
62387
62388      pPage->nOverflow = 0;
62389
62390      /* The next iteration of the do-loop balances the parent page. */
62391      releasePage(pPage);
62392      pCur->iPage--;
62393      assert( pCur->iPage>=0 );
62394    }
62395  }while( rc==SQLITE_OK );
62396
62397  if( pFree ){
62398    sqlite3PageFree(pFree);
62399  }
62400  return rc;
62401}
62402
62403
62404/*
62405** Insert a new record into the BTree.  The key is given by (pKey,nKey)
62406** and the data is given by (pData,nData).  The cursor is used only to
62407** define what table the record should be inserted into.  The cursor
62408** is left pointing at a random location.
62409**
62410** For an INTKEY table, only the nKey value of the key is used.  pKey is
62411** ignored.  For a ZERODATA table, the pData and nData are both ignored.
62412**
62413** If the seekResult parameter is non-zero, then a successful call to
62414** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
62415** been performed. seekResult is the search result returned (a negative
62416** number if pCur points at an entry that is smaller than (pKey, nKey), or
62417** a positive value if pCur points at an entry that is larger than
62418** (pKey, nKey)).
62419**
62420** If the seekResult parameter is non-zero, then the caller guarantees that
62421** cursor pCur is pointing at the existing copy of a row that is to be
62422** overwritten.  If the seekResult parameter is 0, then cursor pCur may
62423** point to any entry or to no entry at all and so this function has to seek
62424** the cursor before the new key can be inserted.
62425*/
62426SQLITE_PRIVATE int sqlite3BtreeInsert(
62427  BtCursor *pCur,                /* Insert data into the table of this cursor */
62428  const void *pKey, i64 nKey,    /* The key of the new record */
62429  const void *pData, int nData,  /* The data of the new record */
62430  int nZero,                     /* Number of extra 0 bytes to append to data */
62431  int appendBias,                /* True if this is likely an append */
62432  int seekResult                 /* Result of prior MovetoUnpacked() call */
62433){
62434  int rc;
62435  int loc = seekResult;          /* -1: before desired location  +1: after */
62436  int szNew = 0;
62437  int idx;
62438  MemPage *pPage;
62439  Btree *p = pCur->pBtree;
62440  BtShared *pBt = p->pBt;
62441  unsigned char *oldCell;
62442  unsigned char *newCell = 0;
62443
62444  if( pCur->eState==CURSOR_FAULT ){
62445    assert( pCur->skipNext!=SQLITE_OK );
62446    return pCur->skipNext;
62447  }
62448
62449  assert( cursorHoldsMutex(pCur) );
62450  assert( (pCur->curFlags & BTCF_WriteFlag)!=0
62451              && pBt->inTransaction==TRANS_WRITE
62452              && (pBt->btsFlags & BTS_READ_ONLY)==0 );
62453  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
62454
62455  /* Assert that the caller has been consistent. If this cursor was opened
62456  ** expecting an index b-tree, then the caller should be inserting blob
62457  ** keys with no associated data. If the cursor was opened expecting an
62458  ** intkey table, the caller should be inserting integer keys with a
62459  ** blob of associated data.  */
62460  assert( (pKey==0)==(pCur->pKeyInfo==0) );
62461
62462  /* Save the positions of any other cursors open on this table.
62463  **
62464  ** In some cases, the call to btreeMoveto() below is a no-op. For
62465  ** example, when inserting data into a table with auto-generated integer
62466  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
62467  ** integer key to use. It then calls this function to actually insert the
62468  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
62469  ** that the cursor is already where it needs to be and returns without
62470  ** doing any work. To avoid thwarting these optimizations, it is important
62471  ** not to clear the cursor here.
62472  */
62473  if( pCur->curFlags & BTCF_Multiple ){
62474    rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
62475    if( rc ) return rc;
62476  }
62477
62478  if( pCur->pKeyInfo==0 ){
62479    assert( pKey==0 );
62480    /* If this is an insert into a table b-tree, invalidate any incrblob
62481    ** cursors open on the row being replaced */
62482    invalidateIncrblobCursors(p, nKey, 0);
62483
62484    /* If the cursor is currently on the last row and we are appending a
62485    ** new row onto the end, set the "loc" to avoid an unnecessary
62486    ** btreeMoveto() call */
62487    if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0
62488      && pCur->info.nKey==nKey-1 ){
62489       loc = -1;
62490    }else if( loc==0 ){
62491      rc = sqlite3BtreeMovetoUnpacked(pCur, 0, nKey, appendBias, &loc);
62492      if( rc ) return rc;
62493    }
62494  }else if( loc==0 ){
62495    rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
62496    if( rc ) return rc;
62497  }
62498  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
62499
62500  pPage = pCur->apPage[pCur->iPage];
62501  assert( pPage->intKey || nKey>=0 );
62502  assert( pPage->leaf || !pPage->intKey );
62503
62504  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
62505          pCur->pgnoRoot, nKey, nData, pPage->pgno,
62506          loc==0 ? "overwrite" : "new entry"));
62507  assert( pPage->isInit );
62508  newCell = pBt->pTmpSpace;
62509  assert( newCell!=0 );
62510  rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
62511  if( rc ) goto end_insert;
62512  assert( szNew==pPage->xCellSize(pPage, newCell) );
62513  assert( szNew <= MX_CELL_SIZE(pBt) );
62514  idx = pCur->aiIdx[pCur->iPage];
62515  if( loc==0 ){
62516    u16 szOld;
62517    assert( idx<pPage->nCell );
62518    rc = sqlite3PagerWrite(pPage->pDbPage);
62519    if( rc ){
62520      goto end_insert;
62521    }
62522    oldCell = findCell(pPage, idx);
62523    if( !pPage->leaf ){
62524      memcpy(newCell, oldCell, 4);
62525    }
62526    rc = clearCell(pPage, oldCell, &szOld);
62527    dropCell(pPage, idx, szOld, &rc);
62528    if( rc ) goto end_insert;
62529  }else if( loc<0 && pPage->nCell>0 ){
62530    assert( pPage->leaf );
62531    idx = ++pCur->aiIdx[pCur->iPage];
62532  }else{
62533    assert( pPage->leaf );
62534  }
62535  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
62536  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
62537
62538  /* If no error has occurred and pPage has an overflow cell, call balance()
62539  ** to redistribute the cells within the tree. Since balance() may move
62540  ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
62541  ** variables.
62542  **
62543  ** Previous versions of SQLite called moveToRoot() to move the cursor
62544  ** back to the root page as balance() used to invalidate the contents
62545  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
62546  ** set the cursor state to "invalid". This makes common insert operations
62547  ** slightly faster.
62548  **
62549  ** There is a subtle but important optimization here too. When inserting
62550  ** multiple records into an intkey b-tree using a single cursor (as can
62551  ** happen while processing an "INSERT INTO ... SELECT" statement), it
62552  ** is advantageous to leave the cursor pointing to the last entry in
62553  ** the b-tree if possible. If the cursor is left pointing to the last
62554  ** entry in the table, and the next row inserted has an integer key
62555  ** larger than the largest existing key, it is possible to insert the
62556  ** row without seeking the cursor. This can be a big performance boost.
62557  */
62558  pCur->info.nSize = 0;
62559  if( rc==SQLITE_OK && pPage->nOverflow ){
62560    pCur->curFlags &= ~(BTCF_ValidNKey);
62561    rc = balance(pCur);
62562
62563    /* Must make sure nOverflow is reset to zero even if the balance()
62564    ** fails. Internal data structure corruption will result otherwise.
62565    ** Also, set the cursor state to invalid. This stops saveCursorPosition()
62566    ** from trying to save the current position of the cursor.  */
62567    pCur->apPage[pCur->iPage]->nOverflow = 0;
62568    pCur->eState = CURSOR_INVALID;
62569  }
62570  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
62571
62572end_insert:
62573  return rc;
62574}
62575
62576/*
62577** Delete the entry that the cursor is pointing to.
62578**
62579** If the second parameter is zero, then the cursor is left pointing at an
62580** arbitrary location after the delete. If it is non-zero, then the cursor
62581** is left in a state such that the next call to BtreeNext() or BtreePrev()
62582** moves it to the same row as it would if the call to BtreeDelete() had
62583** been omitted.
62584*/
62585SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, int bPreserve){
62586  Btree *p = pCur->pBtree;
62587  BtShared *pBt = p->pBt;
62588  int rc;                              /* Return code */
62589  MemPage *pPage;                      /* Page to delete cell from */
62590  unsigned char *pCell;                /* Pointer to cell to delete */
62591  int iCellIdx;                        /* Index of cell to delete */
62592  int iCellDepth;                      /* Depth of node containing pCell */
62593  u16 szCell;                          /* Size of the cell being deleted */
62594  int bSkipnext = 0;                   /* Leaf cursor in SKIPNEXT state */
62595
62596  assert( cursorHoldsMutex(pCur) );
62597  assert( pBt->inTransaction==TRANS_WRITE );
62598  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
62599  assert( pCur->curFlags & BTCF_WriteFlag );
62600  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
62601  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
62602  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
62603  assert( pCur->eState==CURSOR_VALID );
62604
62605  iCellDepth = pCur->iPage;
62606  iCellIdx = pCur->aiIdx[iCellDepth];
62607  pPage = pCur->apPage[iCellDepth];
62608  pCell = findCell(pPage, iCellIdx);
62609
62610  /* If the page containing the entry to delete is not a leaf page, move
62611  ** the cursor to the largest entry in the tree that is smaller than
62612  ** the entry being deleted. This cell will replace the cell being deleted
62613  ** from the internal node. The 'previous' entry is used for this instead
62614  ** of the 'next' entry, as the previous entry is always a part of the
62615  ** sub-tree headed by the child page of the cell being deleted. This makes
62616  ** balancing the tree following the delete operation easier.  */
62617  if( !pPage->leaf ){
62618    int notUsed = 0;
62619    rc = sqlite3BtreePrevious(pCur, &notUsed);
62620    if( rc ) return rc;
62621  }
62622
62623  /* Save the positions of any other cursors open on this table before
62624  ** making any modifications.  */
62625  if( pCur->curFlags & BTCF_Multiple ){
62626    rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
62627    if( rc ) return rc;
62628  }
62629
62630  /* If this is a delete operation to remove a row from a table b-tree,
62631  ** invalidate any incrblob cursors open on the row being deleted.  */
62632  if( pCur->pKeyInfo==0 ){
62633    invalidateIncrblobCursors(p, pCur->info.nKey, 0);
62634  }
62635
62636  /* If the bPreserve flag is set to true, then the cursor position must
62637  ** be preserved following this delete operation. If the current delete
62638  ** will cause a b-tree rebalance, then this is done by saving the cursor
62639  ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
62640  ** returning.
62641  **
62642  ** Or, if the current delete will not cause a rebalance, then the cursor
62643  ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
62644  ** before or after the deleted entry. In this case set bSkipnext to true.  */
62645  if( bPreserve ){
62646    if( !pPage->leaf
62647     || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
62648    ){
62649      /* A b-tree rebalance will be required after deleting this entry.
62650      ** Save the cursor key.  */
62651      rc = saveCursorKey(pCur);
62652      if( rc ) return rc;
62653    }else{
62654      bSkipnext = 1;
62655    }
62656  }
62657
62658  /* Make the page containing the entry to be deleted writable. Then free any
62659  ** overflow pages associated with the entry and finally remove the cell
62660  ** itself from within the page.  */
62661  rc = sqlite3PagerWrite(pPage->pDbPage);
62662  if( rc ) return rc;
62663  rc = clearCell(pPage, pCell, &szCell);
62664  dropCell(pPage, iCellIdx, szCell, &rc);
62665  if( rc ) return rc;
62666
62667  /* If the cell deleted was not located on a leaf page, then the cursor
62668  ** is currently pointing to the largest entry in the sub-tree headed
62669  ** by the child-page of the cell that was just deleted from an internal
62670  ** node. The cell from the leaf node needs to be moved to the internal
62671  ** node to replace the deleted cell.  */
62672  if( !pPage->leaf ){
62673    MemPage *pLeaf = pCur->apPage[pCur->iPage];
62674    int nCell;
62675    Pgno n = pCur->apPage[iCellDepth+1]->pgno;
62676    unsigned char *pTmp;
62677
62678    pCell = findCell(pLeaf, pLeaf->nCell-1);
62679    if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
62680    nCell = pLeaf->xCellSize(pLeaf, pCell);
62681    assert( MX_CELL_SIZE(pBt) >= nCell );
62682    pTmp = pBt->pTmpSpace;
62683    assert( pTmp!=0 );
62684    rc = sqlite3PagerWrite(pLeaf->pDbPage);
62685    insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
62686    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
62687    if( rc ) return rc;
62688  }
62689
62690  /* Balance the tree. If the entry deleted was located on a leaf page,
62691  ** then the cursor still points to that page. In this case the first
62692  ** call to balance() repairs the tree, and the if(...) condition is
62693  ** never true.
62694  **
62695  ** Otherwise, if the entry deleted was on an internal node page, then
62696  ** pCur is pointing to the leaf page from which a cell was removed to
62697  ** replace the cell deleted from the internal node. This is slightly
62698  ** tricky as the leaf node may be underfull, and the internal node may
62699  ** be either under or overfull. In this case run the balancing algorithm
62700  ** on the leaf node first. If the balance proceeds far enough up the
62701  ** tree that we can be sure that any problem in the internal node has
62702  ** been corrected, so be it. Otherwise, after balancing the leaf node,
62703  ** walk the cursor up the tree to the internal node and balance it as
62704  ** well.  */
62705  rc = balance(pCur);
62706  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
62707    while( pCur->iPage>iCellDepth ){
62708      releasePage(pCur->apPage[pCur->iPage--]);
62709    }
62710    rc = balance(pCur);
62711  }
62712
62713  if( rc==SQLITE_OK ){
62714    if( bSkipnext ){
62715      assert( bPreserve && pCur->iPage==iCellDepth );
62716      assert( pPage==pCur->apPage[pCur->iPage] );
62717      assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
62718      pCur->eState = CURSOR_SKIPNEXT;
62719      if( iCellIdx>=pPage->nCell ){
62720        pCur->skipNext = -1;
62721        pCur->aiIdx[iCellDepth] = pPage->nCell-1;
62722      }else{
62723        pCur->skipNext = 1;
62724      }
62725    }else{
62726      rc = moveToRoot(pCur);
62727      if( bPreserve ){
62728        pCur->eState = CURSOR_REQUIRESEEK;
62729      }
62730    }
62731  }
62732  return rc;
62733}
62734
62735/*
62736** Create a new BTree table.  Write into *piTable the page
62737** number for the root page of the new table.
62738**
62739** The type of type is determined by the flags parameter.  Only the
62740** following values of flags are currently in use.  Other values for
62741** flags might not work:
62742**
62743**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
62744**     BTREE_ZERODATA                  Used for SQL indices
62745*/
62746static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
62747  BtShared *pBt = p->pBt;
62748  MemPage *pRoot;
62749  Pgno pgnoRoot;
62750  int rc;
62751  int ptfFlags;          /* Page-type flage for the root page of new table */
62752
62753  assert( sqlite3BtreeHoldsMutex(p) );
62754  assert( pBt->inTransaction==TRANS_WRITE );
62755  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
62756
62757#ifdef SQLITE_OMIT_AUTOVACUUM
62758  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
62759  if( rc ){
62760    return rc;
62761  }
62762#else
62763  if( pBt->autoVacuum ){
62764    Pgno pgnoMove;      /* Move a page here to make room for the root-page */
62765    MemPage *pPageMove; /* The page to move to. */
62766
62767    /* Creating a new table may probably require moving an existing database
62768    ** to make room for the new tables root page. In case this page turns
62769    ** out to be an overflow page, delete all overflow page-map caches
62770    ** held by open cursors.
62771    */
62772    invalidateAllOverflowCache(pBt);
62773
62774    /* Read the value of meta[3] from the database to determine where the
62775    ** root page of the new table should go. meta[3] is the largest root-page
62776    ** created so far, so the new root-page is (meta[3]+1).
62777    */
62778    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
62779    pgnoRoot++;
62780
62781    /* The new root-page may not be allocated on a pointer-map page, or the
62782    ** PENDING_BYTE page.
62783    */
62784    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
62785        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
62786      pgnoRoot++;
62787    }
62788    assert( pgnoRoot>=3 || CORRUPT_DB );
62789    testcase( pgnoRoot<3 );
62790
62791    /* Allocate a page. The page that currently resides at pgnoRoot will
62792    ** be moved to the allocated page (unless the allocated page happens
62793    ** to reside at pgnoRoot).
62794    */
62795    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
62796    if( rc!=SQLITE_OK ){
62797      return rc;
62798    }
62799
62800    if( pgnoMove!=pgnoRoot ){
62801      /* pgnoRoot is the page that will be used for the root-page of
62802      ** the new table (assuming an error did not occur). But we were
62803      ** allocated pgnoMove. If required (i.e. if it was not allocated
62804      ** by extending the file), the current page at position pgnoMove
62805      ** is already journaled.
62806      */
62807      u8 eType = 0;
62808      Pgno iPtrPage = 0;
62809
62810      /* Save the positions of any open cursors. This is required in
62811      ** case they are holding a reference to an xFetch reference
62812      ** corresponding to page pgnoRoot.  */
62813      rc = saveAllCursors(pBt, 0, 0);
62814      releasePage(pPageMove);
62815      if( rc!=SQLITE_OK ){
62816        return rc;
62817      }
62818
62819      /* Move the page currently at pgnoRoot to pgnoMove. */
62820      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
62821      if( rc!=SQLITE_OK ){
62822        return rc;
62823      }
62824      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
62825      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
62826        rc = SQLITE_CORRUPT_BKPT;
62827      }
62828      if( rc!=SQLITE_OK ){
62829        releasePage(pRoot);
62830        return rc;
62831      }
62832      assert( eType!=PTRMAP_ROOTPAGE );
62833      assert( eType!=PTRMAP_FREEPAGE );
62834      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
62835      releasePage(pRoot);
62836
62837      /* Obtain the page at pgnoRoot */
62838      if( rc!=SQLITE_OK ){
62839        return rc;
62840      }
62841      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
62842      if( rc!=SQLITE_OK ){
62843        return rc;
62844      }
62845      rc = sqlite3PagerWrite(pRoot->pDbPage);
62846      if( rc!=SQLITE_OK ){
62847        releasePage(pRoot);
62848        return rc;
62849      }
62850    }else{
62851      pRoot = pPageMove;
62852    }
62853
62854    /* Update the pointer-map and meta-data with the new root-page number. */
62855    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
62856    if( rc ){
62857      releasePage(pRoot);
62858      return rc;
62859    }
62860
62861    /* When the new root page was allocated, page 1 was made writable in
62862    ** order either to increase the database filesize, or to decrement the
62863    ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
62864    */
62865    assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
62866    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
62867    if( NEVER(rc) ){
62868      releasePage(pRoot);
62869      return rc;
62870    }
62871
62872  }else{
62873    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
62874    if( rc ) return rc;
62875  }
62876#endif
62877  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
62878  if( createTabFlags & BTREE_INTKEY ){
62879    ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
62880  }else{
62881    ptfFlags = PTF_ZERODATA | PTF_LEAF;
62882  }
62883  zeroPage(pRoot, ptfFlags);
62884  sqlite3PagerUnref(pRoot->pDbPage);
62885  assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
62886  *piTable = (int)pgnoRoot;
62887  return SQLITE_OK;
62888}
62889SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
62890  int rc;
62891  sqlite3BtreeEnter(p);
62892  rc = btreeCreateTable(p, piTable, flags);
62893  sqlite3BtreeLeave(p);
62894  return rc;
62895}
62896
62897/*
62898** Erase the given database page and all its children.  Return
62899** the page to the freelist.
62900*/
62901static int clearDatabasePage(
62902  BtShared *pBt,           /* The BTree that contains the table */
62903  Pgno pgno,               /* Page number to clear */
62904  int freePageFlag,        /* Deallocate page if true */
62905  int *pnChange            /* Add number of Cells freed to this counter */
62906){
62907  MemPage *pPage;
62908  int rc;
62909  unsigned char *pCell;
62910  int i;
62911  int hdr;
62912  u16 szCell;
62913
62914  assert( sqlite3_mutex_held(pBt->mutex) );
62915  if( pgno>btreePagecount(pBt) ){
62916    return SQLITE_CORRUPT_BKPT;
62917  }
62918  rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
62919  if( rc ) return rc;
62920  if( pPage->bBusy ){
62921    rc = SQLITE_CORRUPT_BKPT;
62922    goto cleardatabasepage_out;
62923  }
62924  pPage->bBusy = 1;
62925  hdr = pPage->hdrOffset;
62926  for(i=0; i<pPage->nCell; i++){
62927    pCell = findCell(pPage, i);
62928    if( !pPage->leaf ){
62929      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
62930      if( rc ) goto cleardatabasepage_out;
62931    }
62932    rc = clearCell(pPage, pCell, &szCell);
62933    if( rc ) goto cleardatabasepage_out;
62934  }
62935  if( !pPage->leaf ){
62936    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
62937    if( rc ) goto cleardatabasepage_out;
62938  }else if( pnChange ){
62939    assert( pPage->intKey || CORRUPT_DB );
62940    testcase( !pPage->intKey );
62941    *pnChange += pPage->nCell;
62942  }
62943  if( freePageFlag ){
62944    freePage(pPage, &rc);
62945  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
62946    zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
62947  }
62948
62949cleardatabasepage_out:
62950  pPage->bBusy = 0;
62951  releasePage(pPage);
62952  return rc;
62953}
62954
62955/*
62956** Delete all information from a single table in the database.  iTable is
62957** the page number of the root of the table.  After this routine returns,
62958** the root page is empty, but still exists.
62959**
62960** This routine will fail with SQLITE_LOCKED if there are any open
62961** read cursors on the table.  Open write cursors are moved to the
62962** root of the table.
62963**
62964** If pnChange is not NULL, then table iTable must be an intkey table. The
62965** integer value pointed to by pnChange is incremented by the number of
62966** entries in the table.
62967*/
62968SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
62969  int rc;
62970  BtShared *pBt = p->pBt;
62971  sqlite3BtreeEnter(p);
62972  assert( p->inTrans==TRANS_WRITE );
62973
62974  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
62975
62976  if( SQLITE_OK==rc ){
62977    /* Invalidate all incrblob cursors open on table iTable (assuming iTable
62978    ** is the root of a table b-tree - if it is not, the following call is
62979    ** a no-op).  */
62980    invalidateIncrblobCursors(p, 0, 1);
62981    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
62982  }
62983  sqlite3BtreeLeave(p);
62984  return rc;
62985}
62986
62987/*
62988** Delete all information from the single table that pCur is open on.
62989**
62990** This routine only work for pCur on an ephemeral table.
62991*/
62992SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
62993  return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
62994}
62995
62996/*
62997** Erase all information in a table and add the root of the table to
62998** the freelist.  Except, the root of the principle table (the one on
62999** page 1) is never added to the freelist.
63000**
63001** This routine will fail with SQLITE_LOCKED if there are any open
63002** cursors on the table.
63003**
63004** If AUTOVACUUM is enabled and the page at iTable is not the last
63005** root page in the database file, then the last root page
63006** in the database file is moved into the slot formerly occupied by
63007** iTable and that last slot formerly occupied by the last root page
63008** is added to the freelist instead of iTable.  In this say, all
63009** root pages are kept at the beginning of the database file, which
63010** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
63011** page number that used to be the last root page in the file before
63012** the move.  If no page gets moved, *piMoved is set to 0.
63013** The last root page is recorded in meta[3] and the value of
63014** meta[3] is updated by this procedure.
63015*/
63016static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
63017  int rc;
63018  MemPage *pPage = 0;
63019  BtShared *pBt = p->pBt;
63020
63021  assert( sqlite3BtreeHoldsMutex(p) );
63022  assert( p->inTrans==TRANS_WRITE );
63023
63024  /* It is illegal to drop a table if any cursors are open on the
63025  ** database. This is because in auto-vacuum mode the backend may
63026  ** need to move another root-page to fill a gap left by the deleted
63027  ** root page. If an open cursor was using this page a problem would
63028  ** occur.
63029  **
63030  ** This error is caught long before control reaches this point.
63031  */
63032  if( NEVER(pBt->pCursor) ){
63033    sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
63034    return SQLITE_LOCKED_SHAREDCACHE;
63035  }
63036
63037  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
63038  if( rc ) return rc;
63039  rc = sqlite3BtreeClearTable(p, iTable, 0);
63040  if( rc ){
63041    releasePage(pPage);
63042    return rc;
63043  }
63044
63045  *piMoved = 0;
63046
63047  if( iTable>1 ){
63048#ifdef SQLITE_OMIT_AUTOVACUUM
63049    freePage(pPage, &rc);
63050    releasePage(pPage);
63051#else
63052    if( pBt->autoVacuum ){
63053      Pgno maxRootPgno;
63054      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
63055
63056      if( iTable==maxRootPgno ){
63057        /* If the table being dropped is the table with the largest root-page
63058        ** number in the database, put the root page on the free list.
63059        */
63060        freePage(pPage, &rc);
63061        releasePage(pPage);
63062        if( rc!=SQLITE_OK ){
63063          return rc;
63064        }
63065      }else{
63066        /* The table being dropped does not have the largest root-page
63067        ** number in the database. So move the page that does into the
63068        ** gap left by the deleted root-page.
63069        */
63070        MemPage *pMove;
63071        releasePage(pPage);
63072        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
63073        if( rc!=SQLITE_OK ){
63074          return rc;
63075        }
63076        rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
63077        releasePage(pMove);
63078        if( rc!=SQLITE_OK ){
63079          return rc;
63080        }
63081        pMove = 0;
63082        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
63083        freePage(pMove, &rc);
63084        releasePage(pMove);
63085        if( rc!=SQLITE_OK ){
63086          return rc;
63087        }
63088        *piMoved = maxRootPgno;
63089      }
63090
63091      /* Set the new 'max-root-page' value in the database header. This
63092      ** is the old value less one, less one more if that happens to
63093      ** be a root-page number, less one again if that is the
63094      ** PENDING_BYTE_PAGE.
63095      */
63096      maxRootPgno--;
63097      while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
63098             || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
63099        maxRootPgno--;
63100      }
63101      assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
63102
63103      rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
63104    }else{
63105      freePage(pPage, &rc);
63106      releasePage(pPage);
63107    }
63108#endif
63109  }else{
63110    /* If sqlite3BtreeDropTable was called on page 1.
63111    ** This really never should happen except in a corrupt
63112    ** database.
63113    */
63114    zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
63115    releasePage(pPage);
63116  }
63117  return rc;
63118}
63119SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
63120  int rc;
63121  sqlite3BtreeEnter(p);
63122  rc = btreeDropTable(p, iTable, piMoved);
63123  sqlite3BtreeLeave(p);
63124  return rc;
63125}
63126
63127
63128/*
63129** This function may only be called if the b-tree connection already
63130** has a read or write transaction open on the database.
63131**
63132** Read the meta-information out of a database file.  Meta[0]
63133** is the number of free pages currently in the database.  Meta[1]
63134** through meta[15] are available for use by higher layers.  Meta[0]
63135** is read-only, the others are read/write.
63136**
63137** The schema layer numbers meta values differently.  At the schema
63138** layer (and the SetCookie and ReadCookie opcodes) the number of
63139** free pages is not visible.  So Cookie[0] is the same as Meta[1].
63140**
63141** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead
63142** of reading the value out of the header, it instead loads the "DataVersion"
63143** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the
63144** database file.  It is a number computed by the pager.  But its access
63145** pattern is the same as header meta values, and so it is convenient to
63146** read it from this routine.
63147*/
63148SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
63149  BtShared *pBt = p->pBt;
63150
63151  sqlite3BtreeEnter(p);
63152  assert( p->inTrans>TRANS_NONE );
63153  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
63154  assert( pBt->pPage1 );
63155  assert( idx>=0 && idx<=15 );
63156
63157  if( idx==BTREE_DATA_VERSION ){
63158    *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
63159  }else{
63160    *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
63161  }
63162
63163  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
63164  ** database, mark the database as read-only.  */
63165#ifdef SQLITE_OMIT_AUTOVACUUM
63166  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
63167    pBt->btsFlags |= BTS_READ_ONLY;
63168  }
63169#endif
63170
63171  sqlite3BtreeLeave(p);
63172}
63173
63174/*
63175** Write meta-information back into the database.  Meta[0] is
63176** read-only and may not be written.
63177*/
63178SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
63179  BtShared *pBt = p->pBt;
63180  unsigned char *pP1;
63181  int rc;
63182  assert( idx>=1 && idx<=15 );
63183  sqlite3BtreeEnter(p);
63184  assert( p->inTrans==TRANS_WRITE );
63185  assert( pBt->pPage1!=0 );
63186  pP1 = pBt->pPage1->aData;
63187  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
63188  if( rc==SQLITE_OK ){
63189    put4byte(&pP1[36 + idx*4], iMeta);
63190#ifndef SQLITE_OMIT_AUTOVACUUM
63191    if( idx==BTREE_INCR_VACUUM ){
63192      assert( pBt->autoVacuum || iMeta==0 );
63193      assert( iMeta==0 || iMeta==1 );
63194      pBt->incrVacuum = (u8)iMeta;
63195    }
63196#endif
63197  }
63198  sqlite3BtreeLeave(p);
63199  return rc;
63200}
63201
63202#ifndef SQLITE_OMIT_BTREECOUNT
63203/*
63204** The first argument, pCur, is a cursor opened on some b-tree. Count the
63205** number of entries in the b-tree and write the result to *pnEntry.
63206**
63207** SQLITE_OK is returned if the operation is successfully executed.
63208** Otherwise, if an error is encountered (i.e. an IO error or database
63209** corruption) an SQLite error code is returned.
63210*/
63211SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
63212  i64 nEntry = 0;                      /* Value to return in *pnEntry */
63213  int rc;                              /* Return code */
63214
63215  if( pCur->pgnoRoot==0 ){
63216    *pnEntry = 0;
63217    return SQLITE_OK;
63218  }
63219  rc = moveToRoot(pCur);
63220
63221  /* Unless an error occurs, the following loop runs one iteration for each
63222  ** page in the B-Tree structure (not including overflow pages).
63223  */
63224  while( rc==SQLITE_OK ){
63225    int iIdx;                          /* Index of child node in parent */
63226    MemPage *pPage;                    /* Current page of the b-tree */
63227
63228    /* If this is a leaf page or the tree is not an int-key tree, then
63229    ** this page contains countable entries. Increment the entry counter
63230    ** accordingly.
63231    */
63232    pPage = pCur->apPage[pCur->iPage];
63233    if( pPage->leaf || !pPage->intKey ){
63234      nEntry += pPage->nCell;
63235    }
63236
63237    /* pPage is a leaf node. This loop navigates the cursor so that it
63238    ** points to the first interior cell that it points to the parent of
63239    ** the next page in the tree that has not yet been visited. The
63240    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
63241    ** of the page, or to the number of cells in the page if the next page
63242    ** to visit is the right-child of its parent.
63243    **
63244    ** If all pages in the tree have been visited, return SQLITE_OK to the
63245    ** caller.
63246    */
63247    if( pPage->leaf ){
63248      do {
63249        if( pCur->iPage==0 ){
63250          /* All pages of the b-tree have been visited. Return successfully. */
63251          *pnEntry = nEntry;
63252          return moveToRoot(pCur);
63253        }
63254        moveToParent(pCur);
63255      }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
63256
63257      pCur->aiIdx[pCur->iPage]++;
63258      pPage = pCur->apPage[pCur->iPage];
63259    }
63260
63261    /* Descend to the child node of the cell that the cursor currently
63262    ** points at. This is the right-child if (iIdx==pPage->nCell).
63263    */
63264    iIdx = pCur->aiIdx[pCur->iPage];
63265    if( iIdx==pPage->nCell ){
63266      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
63267    }else{
63268      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
63269    }
63270  }
63271
63272  /* An error has occurred. Return an error code. */
63273  return rc;
63274}
63275#endif
63276
63277/*
63278** Return the pager associated with a BTree.  This routine is used for
63279** testing and debugging only.
63280*/
63281SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
63282  return p->pBt->pPager;
63283}
63284
63285#ifndef SQLITE_OMIT_INTEGRITY_CHECK
63286/*
63287** Append a message to the error message string.
63288*/
63289static void checkAppendMsg(
63290  IntegrityCk *pCheck,
63291  const char *zFormat,
63292  ...
63293){
63294  va_list ap;
63295  if( !pCheck->mxErr ) return;
63296  pCheck->mxErr--;
63297  pCheck->nErr++;
63298  va_start(ap, zFormat);
63299  if( pCheck->errMsg.nChar ){
63300    sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
63301  }
63302  if( pCheck->zPfx ){
63303    sqlite3XPrintf(&pCheck->errMsg, 0, pCheck->zPfx, pCheck->v1, pCheck->v2);
63304  }
63305  sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
63306  va_end(ap);
63307  if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
63308    pCheck->mallocFailed = 1;
63309  }
63310}
63311#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
63312
63313#ifndef SQLITE_OMIT_INTEGRITY_CHECK
63314
63315/*
63316** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
63317** corresponds to page iPg is already set.
63318*/
63319static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
63320  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
63321  return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
63322}
63323
63324/*
63325** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
63326*/
63327static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
63328  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
63329  pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
63330}
63331
63332
63333/*
63334** Add 1 to the reference count for page iPage.  If this is the second
63335** reference to the page, add an error message to pCheck->zErrMsg.
63336** Return 1 if there are 2 or more references to the page and 0 if
63337** if this is the first reference to the page.
63338**
63339** Also check that the page number is in bounds.
63340*/
63341static int checkRef(IntegrityCk *pCheck, Pgno iPage){
63342  if( iPage==0 ) return 1;
63343  if( iPage>pCheck->nPage ){
63344    checkAppendMsg(pCheck, "invalid page number %d", iPage);
63345    return 1;
63346  }
63347  if( getPageReferenced(pCheck, iPage) ){
63348    checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
63349    return 1;
63350  }
63351  setPageReferenced(pCheck, iPage);
63352  return 0;
63353}
63354
63355#ifndef SQLITE_OMIT_AUTOVACUUM
63356/*
63357** Check that the entry in the pointer-map for page iChild maps to
63358** page iParent, pointer type ptrType. If not, append an error message
63359** to pCheck.
63360*/
63361static void checkPtrmap(
63362  IntegrityCk *pCheck,   /* Integrity check context */
63363  Pgno iChild,           /* Child page number */
63364  u8 eType,              /* Expected pointer map type */
63365  Pgno iParent           /* Expected pointer map parent page number */
63366){
63367  int rc;
63368  u8 ePtrmapType;
63369  Pgno iPtrmapParent;
63370
63371  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
63372  if( rc!=SQLITE_OK ){
63373    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
63374    checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
63375    return;
63376  }
63377
63378  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
63379    checkAppendMsg(pCheck,
63380      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
63381      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
63382  }
63383}
63384#endif
63385
63386/*
63387** Check the integrity of the freelist or of an overflow page list.
63388** Verify that the number of pages on the list is N.
63389*/
63390static void checkList(
63391  IntegrityCk *pCheck,  /* Integrity checking context */
63392  int isFreeList,       /* True for a freelist.  False for overflow page list */
63393  int iPage,            /* Page number for first page in the list */
63394  int N                 /* Expected number of pages in the list */
63395){
63396  int i;
63397  int expected = N;
63398  int iFirst = iPage;
63399  while( N-- > 0 && pCheck->mxErr ){
63400    DbPage *pOvflPage;
63401    unsigned char *pOvflData;
63402    if( iPage<1 ){
63403      checkAppendMsg(pCheck,
63404         "%d of %d pages missing from overflow list starting at %d",
63405          N+1, expected, iFirst);
63406      break;
63407    }
63408    if( checkRef(pCheck, iPage) ) break;
63409    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
63410      checkAppendMsg(pCheck, "failed to get page %d", iPage);
63411      break;
63412    }
63413    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
63414    if( isFreeList ){
63415      int n = get4byte(&pOvflData[4]);
63416#ifndef SQLITE_OMIT_AUTOVACUUM
63417      if( pCheck->pBt->autoVacuum ){
63418        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
63419      }
63420#endif
63421      if( n>(int)pCheck->pBt->usableSize/4-2 ){
63422        checkAppendMsg(pCheck,
63423           "freelist leaf count too big on page %d", iPage);
63424        N--;
63425      }else{
63426        for(i=0; i<n; i++){
63427          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
63428#ifndef SQLITE_OMIT_AUTOVACUUM
63429          if( pCheck->pBt->autoVacuum ){
63430            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
63431          }
63432#endif
63433          checkRef(pCheck, iFreePage);
63434        }
63435        N -= n;
63436      }
63437    }
63438#ifndef SQLITE_OMIT_AUTOVACUUM
63439    else{
63440      /* If this database supports auto-vacuum and iPage is not the last
63441      ** page in this overflow list, check that the pointer-map entry for
63442      ** the following page matches iPage.
63443      */
63444      if( pCheck->pBt->autoVacuum && N>0 ){
63445        i = get4byte(pOvflData);
63446        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
63447      }
63448    }
63449#endif
63450    iPage = get4byte(pOvflData);
63451    sqlite3PagerUnref(pOvflPage);
63452
63453    if( isFreeList && N<(iPage!=0) ){
63454      checkAppendMsg(pCheck, "free-page count in header is too small");
63455    }
63456  }
63457}
63458#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
63459
63460/*
63461** An implementation of a min-heap.
63462**
63463** aHeap[0] is the number of elements on the heap.  aHeap[1] is the
63464** root element.  The daughter nodes of aHeap[N] are aHeap[N*2]
63465** and aHeap[N*2+1].
63466**
63467** The heap property is this:  Every node is less than or equal to both
63468** of its daughter nodes.  A consequence of the heap property is that the
63469** root node aHeap[1] is always the minimum value currently in the heap.
63470**
63471** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
63472** the heap, preserving the heap property.  The btreeHeapPull() routine
63473** removes the root element from the heap (the minimum value in the heap)
63474** and then moves other nodes around as necessary to preserve the heap
63475** property.
63476**
63477** This heap is used for cell overlap and coverage testing.  Each u32
63478** entry represents the span of a cell or freeblock on a btree page.
63479** The upper 16 bits are the index of the first byte of a range and the
63480** lower 16 bits are the index of the last byte of that range.
63481*/
63482static void btreeHeapInsert(u32 *aHeap, u32 x){
63483  u32 j, i = ++aHeap[0];
63484  aHeap[i] = x;
63485  while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
63486    x = aHeap[j];
63487    aHeap[j] = aHeap[i];
63488    aHeap[i] = x;
63489    i = j;
63490  }
63491}
63492static int btreeHeapPull(u32 *aHeap, u32 *pOut){
63493  u32 j, i, x;
63494  if( (x = aHeap[0])==0 ) return 0;
63495  *pOut = aHeap[1];
63496  aHeap[1] = aHeap[x];
63497  aHeap[x] = 0xffffffff;
63498  aHeap[0]--;
63499  i = 1;
63500  while( (j = i*2)<=aHeap[0] ){
63501    if( aHeap[j]>aHeap[j+1] ) j++;
63502    if( aHeap[i]<aHeap[j] ) break;
63503    x = aHeap[i];
63504    aHeap[i] = aHeap[j];
63505    aHeap[j] = x;
63506    i = j;
63507  }
63508  return 1;
63509}
63510
63511#ifndef SQLITE_OMIT_INTEGRITY_CHECK
63512/*
63513** Do various sanity checks on a single page of a tree.  Return
63514** the tree depth.  Root pages return 0.  Parents of root pages
63515** return 1, and so forth.
63516**
63517** These checks are done:
63518**
63519**      1.  Make sure that cells and freeblocks do not overlap
63520**          but combine to completely cover the page.
63521**      2.  Make sure integer cell keys are in order.
63522**      3.  Check the integrity of overflow pages.
63523**      4.  Recursively call checkTreePage on all children.
63524**      5.  Verify that the depth of all children is the same.
63525*/
63526static int checkTreePage(
63527  IntegrityCk *pCheck,  /* Context for the sanity check */
63528  int iPage,            /* Page number of the page to check */
63529  i64 *piMinKey,        /* Write minimum integer primary key here */
63530  i64 maxKey            /* Error if integer primary key greater than this */
63531){
63532  MemPage *pPage = 0;      /* The page being analyzed */
63533  int i;                   /* Loop counter */
63534  int rc;                  /* Result code from subroutine call */
63535  int depth = -1, d2;      /* Depth of a subtree */
63536  int pgno;                /* Page number */
63537  int nFrag;               /* Number of fragmented bytes on the page */
63538  int hdr;                 /* Offset to the page header */
63539  int cellStart;           /* Offset to the start of the cell pointer array */
63540  int nCell;               /* Number of cells */
63541  int doCoverageCheck = 1; /* True if cell coverage checking should be done */
63542  int keyCanBeEqual = 1;   /* True if IPK can be equal to maxKey
63543                           ** False if IPK must be strictly less than maxKey */
63544  u8 *data;                /* Page content */
63545  u8 *pCell;               /* Cell content */
63546  u8 *pCellIdx;            /* Next element of the cell pointer array */
63547  BtShared *pBt;           /* The BtShared object that owns pPage */
63548  u32 pc;                  /* Address of a cell */
63549  u32 usableSize;          /* Usable size of the page */
63550  u32 contentOffset;       /* Offset to the start of the cell content area */
63551  u32 *heap = 0;           /* Min-heap used for checking cell coverage */
63552  u32 x, prev = 0;         /* Next and previous entry on the min-heap */
63553  const char *saved_zPfx = pCheck->zPfx;
63554  int saved_v1 = pCheck->v1;
63555  int saved_v2 = pCheck->v2;
63556  u8 savedIsInit = 0;
63557
63558  /* Check that the page exists
63559  */
63560  pBt = pCheck->pBt;
63561  usableSize = pBt->usableSize;
63562  if( iPage==0 ) return 0;
63563  if( checkRef(pCheck, iPage) ) return 0;
63564  pCheck->zPfx = "Page %d: ";
63565  pCheck->v1 = iPage;
63566  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
63567    checkAppendMsg(pCheck,
63568       "unable to get the page. error code=%d", rc);
63569    goto end_of_check;
63570  }
63571
63572  /* Clear MemPage.isInit to make sure the corruption detection code in
63573  ** btreeInitPage() is executed.  */
63574  savedIsInit = pPage->isInit;
63575  pPage->isInit = 0;
63576  if( (rc = btreeInitPage(pPage))!=0 ){
63577    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
63578    checkAppendMsg(pCheck,
63579                   "btreeInitPage() returns error code %d", rc);
63580    goto end_of_check;
63581  }
63582  data = pPage->aData;
63583  hdr = pPage->hdrOffset;
63584
63585  /* Set up for cell analysis */
63586  pCheck->zPfx = "On tree page %d cell %d: ";
63587  contentOffset = get2byteNotZero(&data[hdr+5]);
63588  assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
63589
63590  /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
63591  ** number of cells on the page. */
63592  nCell = get2byte(&data[hdr+3]);
63593  assert( pPage->nCell==nCell );
63594
63595  /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
63596  ** immediately follows the b-tree page header. */
63597  cellStart = hdr + 12 - 4*pPage->leaf;
63598  assert( pPage->aCellIdx==&data[cellStart] );
63599  pCellIdx = &data[cellStart + 2*(nCell-1)];
63600
63601  if( !pPage->leaf ){
63602    /* Analyze the right-child page of internal pages */
63603    pgno = get4byte(&data[hdr+8]);
63604#ifndef SQLITE_OMIT_AUTOVACUUM
63605    if( pBt->autoVacuum ){
63606      pCheck->zPfx = "On page %d at right child: ";
63607      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
63608    }
63609#endif
63610    depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
63611    keyCanBeEqual = 0;
63612  }else{
63613    /* For leaf pages, the coverage check will occur in the same loop
63614    ** as the other cell checks, so initialize the heap.  */
63615    heap = pCheck->heap;
63616    heap[0] = 0;
63617  }
63618
63619  /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
63620  ** integer offsets to the cell contents. */
63621  for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
63622    CellInfo info;
63623
63624    /* Check cell size */
63625    pCheck->v2 = i;
63626    assert( pCellIdx==&data[cellStart + i*2] );
63627    pc = get2byteAligned(pCellIdx);
63628    pCellIdx -= 2;
63629    if( pc<contentOffset || pc>usableSize-4 ){
63630      checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
63631                             pc, contentOffset, usableSize-4);
63632      doCoverageCheck = 0;
63633      continue;
63634    }
63635    pCell = &data[pc];
63636    pPage->xParseCell(pPage, pCell, &info);
63637    if( pc+info.nSize>usableSize ){
63638      checkAppendMsg(pCheck, "Extends off end of page");
63639      doCoverageCheck = 0;
63640      continue;
63641    }
63642
63643    /* Check for integer primary key out of range */
63644    if( pPage->intKey ){
63645      if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
63646        checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
63647      }
63648      maxKey = info.nKey;
63649    }
63650
63651    /* Check the content overflow list */
63652    if( info.nPayload>info.nLocal ){
63653      int nPage;       /* Number of pages on the overflow chain */
63654      Pgno pgnoOvfl;   /* First page of the overflow chain */
63655      assert( pc + info.iOverflow <= usableSize );
63656      nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
63657      pgnoOvfl = get4byte(&pCell[info.iOverflow]);
63658#ifndef SQLITE_OMIT_AUTOVACUUM
63659      if( pBt->autoVacuum ){
63660        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
63661      }
63662#endif
63663      checkList(pCheck, 0, pgnoOvfl, nPage);
63664    }
63665
63666    if( !pPage->leaf ){
63667      /* Check sanity of left child page for internal pages */
63668      pgno = get4byte(pCell);
63669#ifndef SQLITE_OMIT_AUTOVACUUM
63670      if( pBt->autoVacuum ){
63671        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
63672      }
63673#endif
63674      d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
63675      keyCanBeEqual = 0;
63676      if( d2!=depth ){
63677        checkAppendMsg(pCheck, "Child page depth differs");
63678        depth = d2;
63679      }
63680    }else{
63681      /* Populate the coverage-checking heap for leaf pages */
63682      btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
63683    }
63684  }
63685  *piMinKey = maxKey;
63686
63687  /* Check for complete coverage of the page
63688  */
63689  pCheck->zPfx = 0;
63690  if( doCoverageCheck && pCheck->mxErr>0 ){
63691    /* For leaf pages, the min-heap has already been initialized and the
63692    ** cells have already been inserted.  But for internal pages, that has
63693    ** not yet been done, so do it now */
63694    if( !pPage->leaf ){
63695      heap = pCheck->heap;
63696      heap[0] = 0;
63697      for(i=nCell-1; i>=0; i--){
63698        u32 size;
63699        pc = get2byteAligned(&data[cellStart+i*2]);
63700        size = pPage->xCellSize(pPage, &data[pc]);
63701        btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
63702      }
63703    }
63704    /* Add the freeblocks to the min-heap
63705    **
63706    ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
63707    ** is the offset of the first freeblock, or zero if there are no
63708    ** freeblocks on the page.
63709    */
63710    i = get2byte(&data[hdr+1]);
63711    while( i>0 ){
63712      int size, j;
63713      assert( (u32)i<=usableSize-4 );     /* Enforced by btreeInitPage() */
63714      size = get2byte(&data[i+2]);
63715      assert( (u32)(i+size)<=usableSize );  /* Enforced by btreeInitPage() */
63716      btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
63717      /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
63718      ** big-endian integer which is the offset in the b-tree page of the next
63719      ** freeblock in the chain, or zero if the freeblock is the last on the
63720      ** chain. */
63721      j = get2byte(&data[i]);
63722      /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
63723      ** increasing offset. */
63724      assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
63725      assert( (u32)j<=usableSize-4 );   /* Enforced by btreeInitPage() */
63726      i = j;
63727    }
63728    /* Analyze the min-heap looking for overlap between cells and/or
63729    ** freeblocks, and counting the number of untracked bytes in nFrag.
63730    **
63731    ** Each min-heap entry is of the form:    (start_address<<16)|end_address.
63732    ** There is an implied first entry the covers the page header, the cell
63733    ** pointer index, and the gap between the cell pointer index and the start
63734    ** of cell content.
63735    **
63736    ** The loop below pulls entries from the min-heap in order and compares
63737    ** the start_address against the previous end_address.  If there is an
63738    ** overlap, that means bytes are used multiple times.  If there is a gap,
63739    ** that gap is added to the fragmentation count.
63740    */
63741    nFrag = 0;
63742    prev = contentOffset - 1;   /* Implied first min-heap entry */
63743    while( btreeHeapPull(heap,&x) ){
63744      if( (prev&0xffff)>=(x>>16) ){
63745        checkAppendMsg(pCheck,
63746          "Multiple uses for byte %u of page %d", x>>16, iPage);
63747        break;
63748      }else{
63749        nFrag += (x>>16) - (prev&0xffff) - 1;
63750        prev = x;
63751      }
63752    }
63753    nFrag += usableSize - (prev&0xffff) - 1;
63754    /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
63755    ** is stored in the fifth field of the b-tree page header.
63756    ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
63757    ** number of fragmented free bytes within the cell content area.
63758    */
63759    if( heap[0]==0 && nFrag!=data[hdr+7] ){
63760      checkAppendMsg(pCheck,
63761          "Fragmentation of %d bytes reported as %d on page %d",
63762          nFrag, data[hdr+7], iPage);
63763    }
63764  }
63765
63766end_of_check:
63767  if( !doCoverageCheck ) pPage->isInit = savedIsInit;
63768  releasePage(pPage);
63769  pCheck->zPfx = saved_zPfx;
63770  pCheck->v1 = saved_v1;
63771  pCheck->v2 = saved_v2;
63772  return depth+1;
63773}
63774#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
63775
63776#ifndef SQLITE_OMIT_INTEGRITY_CHECK
63777/*
63778** This routine does a complete check of the given BTree file.  aRoot[] is
63779** an array of pages numbers were each page number is the root page of
63780** a table.  nRoot is the number of entries in aRoot.
63781**
63782** A read-only or read-write transaction must be opened before calling
63783** this function.
63784**
63785** Write the number of error seen in *pnErr.  Except for some memory
63786** allocation errors,  an error message held in memory obtained from
63787** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
63788** returned.  If a memory allocation error occurs, NULL is returned.
63789*/
63790SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
63791  Btree *p,     /* The btree to be checked */
63792  int *aRoot,   /* An array of root pages numbers for individual trees */
63793  int nRoot,    /* Number of entries in aRoot[] */
63794  int mxErr,    /* Stop reporting errors after this many */
63795  int *pnErr    /* Write number of errors seen to this variable */
63796){
63797  Pgno i;
63798  IntegrityCk sCheck;
63799  BtShared *pBt = p->pBt;
63800  int savedDbFlags = pBt->db->flags;
63801  char zErr[100];
63802  VVA_ONLY( int nRef );
63803
63804  sqlite3BtreeEnter(p);
63805  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
63806  assert( (nRef = sqlite3PagerRefcount(pBt->pPager))>=0 );
63807  sCheck.pBt = pBt;
63808  sCheck.pPager = pBt->pPager;
63809  sCheck.nPage = btreePagecount(sCheck.pBt);
63810  sCheck.mxErr = mxErr;
63811  sCheck.nErr = 0;
63812  sCheck.mallocFailed = 0;
63813  sCheck.zPfx = 0;
63814  sCheck.v1 = 0;
63815  sCheck.v2 = 0;
63816  sCheck.aPgRef = 0;
63817  sCheck.heap = 0;
63818  sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
63819  if( sCheck.nPage==0 ){
63820    goto integrity_ck_cleanup;
63821  }
63822
63823  sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
63824  if( !sCheck.aPgRef ){
63825    sCheck.mallocFailed = 1;
63826    goto integrity_ck_cleanup;
63827  }
63828  sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
63829  if( sCheck.heap==0 ){
63830    sCheck.mallocFailed = 1;
63831    goto integrity_ck_cleanup;
63832  }
63833
63834  i = PENDING_BYTE_PAGE(pBt);
63835  if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
63836
63837  /* Check the integrity of the freelist
63838  */
63839  sCheck.zPfx = "Main freelist: ";
63840  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
63841            get4byte(&pBt->pPage1->aData[36]));
63842  sCheck.zPfx = 0;
63843
63844  /* Check all the tables.
63845  */
63846  testcase( pBt->db->flags & SQLITE_CellSizeCk );
63847  pBt->db->flags &= ~SQLITE_CellSizeCk;
63848  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
63849    i64 notUsed;
63850    if( aRoot[i]==0 ) continue;
63851#ifndef SQLITE_OMIT_AUTOVACUUM
63852    if( pBt->autoVacuum && aRoot[i]>1 ){
63853      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
63854    }
63855#endif
63856    checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
63857  }
63858  pBt->db->flags = savedDbFlags;
63859
63860  /* Make sure every page in the file is referenced
63861  */
63862  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
63863#ifdef SQLITE_OMIT_AUTOVACUUM
63864    if( getPageReferenced(&sCheck, i)==0 ){
63865      checkAppendMsg(&sCheck, "Page %d is never used", i);
63866    }
63867#else
63868    /* If the database supports auto-vacuum, make sure no tables contain
63869    ** references to pointer-map pages.
63870    */
63871    if( getPageReferenced(&sCheck, i)==0 &&
63872       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
63873      checkAppendMsg(&sCheck, "Page %d is never used", i);
63874    }
63875    if( getPageReferenced(&sCheck, i)!=0 &&
63876       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
63877      checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
63878    }
63879#endif
63880  }
63881
63882  /* Clean  up and report errors.
63883  */
63884integrity_ck_cleanup:
63885  sqlite3PageFree(sCheck.heap);
63886  sqlite3_free(sCheck.aPgRef);
63887  if( sCheck.mallocFailed ){
63888    sqlite3StrAccumReset(&sCheck.errMsg);
63889    sCheck.nErr++;
63890  }
63891  *pnErr = sCheck.nErr;
63892  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
63893  /* Make sure this analysis did not leave any unref() pages. */
63894  assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
63895  sqlite3BtreeLeave(p);
63896  return sqlite3StrAccumFinish(&sCheck.errMsg);
63897}
63898#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
63899
63900/*
63901** Return the full pathname of the underlying database file.  Return
63902** an empty string if the database is in-memory or a TEMP database.
63903**
63904** The pager filename is invariant as long as the pager is
63905** open so it is safe to access without the BtShared mutex.
63906*/
63907SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
63908  assert( p->pBt->pPager!=0 );
63909  return sqlite3PagerFilename(p->pBt->pPager, 1);
63910}
63911
63912/*
63913** Return the pathname of the journal file for this database. The return
63914** value of this routine is the same regardless of whether the journal file
63915** has been created or not.
63916**
63917** The pager journal filename is invariant as long as the pager is
63918** open so it is safe to access without the BtShared mutex.
63919*/
63920SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
63921  assert( p->pBt->pPager!=0 );
63922  return sqlite3PagerJournalname(p->pBt->pPager);
63923}
63924
63925/*
63926** Return non-zero if a transaction is active.
63927*/
63928SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
63929  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
63930  return (p && (p->inTrans==TRANS_WRITE));
63931}
63932
63933#ifndef SQLITE_OMIT_WAL
63934/*
63935** Run a checkpoint on the Btree passed as the first argument.
63936**
63937** Return SQLITE_LOCKED if this or any other connection has an open
63938** transaction on the shared-cache the argument Btree is connected to.
63939**
63940** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
63941*/
63942SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
63943  int rc = SQLITE_OK;
63944  if( p ){
63945    BtShared *pBt = p->pBt;
63946    sqlite3BtreeEnter(p);
63947    if( pBt->inTransaction!=TRANS_NONE ){
63948      rc = SQLITE_LOCKED;
63949    }else{
63950      rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
63951    }
63952    sqlite3BtreeLeave(p);
63953  }
63954  return rc;
63955}
63956#endif
63957
63958/*
63959** Return non-zero if a read (or write) transaction is active.
63960*/
63961SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
63962  assert( p );
63963  assert( sqlite3_mutex_held(p->db->mutex) );
63964  return p->inTrans!=TRANS_NONE;
63965}
63966
63967SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
63968  assert( p );
63969  assert( sqlite3_mutex_held(p->db->mutex) );
63970  return p->nBackup!=0;
63971}
63972
63973/*
63974** This function returns a pointer to a blob of memory associated with
63975** a single shared-btree. The memory is used by client code for its own
63976** purposes (for example, to store a high-level schema associated with
63977** the shared-btree). The btree layer manages reference counting issues.
63978**
63979** The first time this is called on a shared-btree, nBytes bytes of memory
63980** are allocated, zeroed, and returned to the caller. For each subsequent
63981** call the nBytes parameter is ignored and a pointer to the same blob
63982** of memory returned.
63983**
63984** If the nBytes parameter is 0 and the blob of memory has not yet been
63985** allocated, a null pointer is returned. If the blob has already been
63986** allocated, it is returned as normal.
63987**
63988** Just before the shared-btree is closed, the function passed as the
63989** xFree argument when the memory allocation was made is invoked on the
63990** blob of allocated memory. The xFree function should not call sqlite3_free()
63991** on the memory, the btree layer does that.
63992*/
63993SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
63994  BtShared *pBt = p->pBt;
63995  sqlite3BtreeEnter(p);
63996  if( !pBt->pSchema && nBytes ){
63997    pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
63998    pBt->xFreeSchema = xFree;
63999  }
64000  sqlite3BtreeLeave(p);
64001  return pBt->pSchema;
64002}
64003
64004/*
64005** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
64006** btree as the argument handle holds an exclusive lock on the
64007** sqlite_master table. Otherwise SQLITE_OK.
64008*/
64009SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
64010  int rc;
64011  assert( sqlite3_mutex_held(p->db->mutex) );
64012  sqlite3BtreeEnter(p);
64013  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
64014  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
64015  sqlite3BtreeLeave(p);
64016  return rc;
64017}
64018
64019
64020#ifndef SQLITE_OMIT_SHARED_CACHE
64021/*
64022** Obtain a lock on the table whose root page is iTab.  The
64023** lock is a write lock if isWritelock is true or a read lock
64024** if it is false.
64025*/
64026SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
64027  int rc = SQLITE_OK;
64028  assert( p->inTrans!=TRANS_NONE );
64029  if( p->sharable ){
64030    u8 lockType = READ_LOCK + isWriteLock;
64031    assert( READ_LOCK+1==WRITE_LOCK );
64032    assert( isWriteLock==0 || isWriteLock==1 );
64033
64034    sqlite3BtreeEnter(p);
64035    rc = querySharedCacheTableLock(p, iTab, lockType);
64036    if( rc==SQLITE_OK ){
64037      rc = setSharedCacheTableLock(p, iTab, lockType);
64038    }
64039    sqlite3BtreeLeave(p);
64040  }
64041  return rc;
64042}
64043#endif
64044
64045#ifndef SQLITE_OMIT_INCRBLOB
64046/*
64047** Argument pCsr must be a cursor opened for writing on an
64048** INTKEY table currently pointing at a valid table entry.
64049** This function modifies the data stored as part of that entry.
64050**
64051** Only the data content may only be modified, it is not possible to
64052** change the length of the data stored. If this function is called with
64053** parameters that attempt to write past the end of the existing data,
64054** no modifications are made and SQLITE_CORRUPT is returned.
64055*/
64056SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
64057  int rc;
64058  assert( cursorHoldsMutex(pCsr) );
64059  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
64060  assert( pCsr->curFlags & BTCF_Incrblob );
64061
64062  rc = restoreCursorPosition(pCsr);
64063  if( rc!=SQLITE_OK ){
64064    return rc;
64065  }
64066  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
64067  if( pCsr->eState!=CURSOR_VALID ){
64068    return SQLITE_ABORT;
64069  }
64070
64071  /* Save the positions of all other cursors open on this table. This is
64072  ** required in case any of them are holding references to an xFetch
64073  ** version of the b-tree page modified by the accessPayload call below.
64074  **
64075  ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
64076  ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
64077  ** saveAllCursors can only return SQLITE_OK.
64078  */
64079  VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
64080  assert( rc==SQLITE_OK );
64081
64082  /* Check some assumptions:
64083  **   (a) the cursor is open for writing,
64084  **   (b) there is a read/write transaction open,
64085  **   (c) the connection holds a write-lock on the table (if required),
64086  **   (d) there are no conflicting read-locks, and
64087  **   (e) the cursor points at a valid row of an intKey table.
64088  */
64089  if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
64090    return SQLITE_READONLY;
64091  }
64092  assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
64093              && pCsr->pBt->inTransaction==TRANS_WRITE );
64094  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
64095  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
64096  assert( pCsr->apPage[pCsr->iPage]->intKey );
64097
64098  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
64099}
64100
64101/*
64102** Mark this cursor as an incremental blob cursor.
64103*/
64104SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
64105  pCur->curFlags |= BTCF_Incrblob;
64106  pCur->pBtree->hasIncrblobCur = 1;
64107}
64108#endif
64109
64110/*
64111** Set both the "read version" (single byte at byte offset 18) and
64112** "write version" (single byte at byte offset 19) fields in the database
64113** header to iVersion.
64114*/
64115SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
64116  BtShared *pBt = pBtree->pBt;
64117  int rc;                         /* Return code */
64118
64119  assert( iVersion==1 || iVersion==2 );
64120
64121  /* If setting the version fields to 1, do not automatically open the
64122  ** WAL connection, even if the version fields are currently set to 2.
64123  */
64124  pBt->btsFlags &= ~BTS_NO_WAL;
64125  if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
64126
64127  rc = sqlite3BtreeBeginTrans(pBtree, 0);
64128  if( rc==SQLITE_OK ){
64129    u8 *aData = pBt->pPage1->aData;
64130    if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
64131      rc = sqlite3BtreeBeginTrans(pBtree, 2);
64132      if( rc==SQLITE_OK ){
64133        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
64134        if( rc==SQLITE_OK ){
64135          aData[18] = (u8)iVersion;
64136          aData[19] = (u8)iVersion;
64137        }
64138      }
64139    }
64140  }
64141
64142  pBt->btsFlags &= ~BTS_NO_WAL;
64143  return rc;
64144}
64145
64146/*
64147** set the mask of hint flags for cursor pCsr.
64148*/
64149SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
64150  assert( mask==BTREE_BULKLOAD || mask==BTREE_SEEK_EQ || mask==0 );
64151  pCsr->hints = mask;
64152}
64153
64154#ifdef SQLITE_DEBUG
64155/*
64156** Return true if the cursor has a hint specified.  This routine is
64157** only used from within assert() statements
64158*/
64159SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
64160  return (pCsr->hints & mask)!=0;
64161}
64162#endif
64163
64164/*
64165** Return true if the given Btree is read-only.
64166*/
64167SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
64168  return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
64169}
64170
64171/*
64172** Return the size of the header added to each page by this module.
64173*/
64174SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
64175
64176/************** End of btree.c ***********************************************/
64177/************** Begin file backup.c ******************************************/
64178/*
64179** 2009 January 28
64180**
64181** The author disclaims copyright to this source code.  In place of
64182** a legal notice, here is a blessing:
64183**
64184**    May you do good and not evil.
64185**    May you find forgiveness for yourself and forgive others.
64186**    May you share freely, never taking more than you give.
64187**
64188*************************************************************************
64189** This file contains the implementation of the sqlite3_backup_XXX()
64190** API functions and the related features.
64191*/
64192/* #include "sqliteInt.h" */
64193/* #include "btreeInt.h" */
64194
64195/*
64196** Structure allocated for each backup operation.
64197*/
64198struct sqlite3_backup {
64199  sqlite3* pDestDb;        /* Destination database handle */
64200  Btree *pDest;            /* Destination b-tree file */
64201  u32 iDestSchema;         /* Original schema cookie in destination */
64202  int bDestLocked;         /* True once a write-transaction is open on pDest */
64203
64204  Pgno iNext;              /* Page number of the next source page to copy */
64205  sqlite3* pSrcDb;         /* Source database handle */
64206  Btree *pSrc;             /* Source b-tree file */
64207
64208  int rc;                  /* Backup process error code */
64209
64210  /* These two variables are set by every call to backup_step(). They are
64211  ** read by calls to backup_remaining() and backup_pagecount().
64212  */
64213  Pgno nRemaining;         /* Number of pages left to copy */
64214  Pgno nPagecount;         /* Total number of pages to copy */
64215
64216  int isAttached;          /* True once backup has been registered with pager */
64217  sqlite3_backup *pNext;   /* Next backup associated with source pager */
64218};
64219
64220/*
64221** THREAD SAFETY NOTES:
64222**
64223**   Once it has been created using backup_init(), a single sqlite3_backup
64224**   structure may be accessed via two groups of thread-safe entry points:
64225**
64226**     * Via the sqlite3_backup_XXX() API function backup_step() and
64227**       backup_finish(). Both these functions obtain the source database
64228**       handle mutex and the mutex associated with the source BtShared
64229**       structure, in that order.
64230**
64231**     * Via the BackupUpdate() and BackupRestart() functions, which are
64232**       invoked by the pager layer to report various state changes in
64233**       the page cache associated with the source database. The mutex
64234**       associated with the source database BtShared structure will always
64235**       be held when either of these functions are invoked.
64236**
64237**   The other sqlite3_backup_XXX() API functions, backup_remaining() and
64238**   backup_pagecount() are not thread-safe functions. If they are called
64239**   while some other thread is calling backup_step() or backup_finish(),
64240**   the values returned may be invalid. There is no way for a call to
64241**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
64242**   or backup_pagecount().
64243**
64244**   Depending on the SQLite configuration, the database handles and/or
64245**   the Btree objects may have their own mutexes that require locking.
64246**   Non-sharable Btrees (in-memory databases for example), do not have
64247**   associated mutexes.
64248*/
64249
64250/*
64251** Return a pointer corresponding to database zDb (i.e. "main", "temp")
64252** in connection handle pDb. If such a database cannot be found, return
64253** a NULL pointer and write an error message to pErrorDb.
64254**
64255** If the "temp" database is requested, it may need to be opened by this
64256** function. If an error occurs while doing so, return 0 and write an
64257** error message to pErrorDb.
64258*/
64259static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
64260  int i = sqlite3FindDbName(pDb, zDb);
64261
64262  if( i==1 ){
64263    Parse *pParse;
64264    int rc = 0;
64265    pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
64266    if( pParse==0 ){
64267      sqlite3ErrorWithMsg(pErrorDb, SQLITE_NOMEM, "out of memory");
64268      rc = SQLITE_NOMEM;
64269    }else{
64270      pParse->db = pDb;
64271      if( sqlite3OpenTempDatabase(pParse) ){
64272        sqlite3ErrorWithMsg(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
64273        rc = SQLITE_ERROR;
64274      }
64275      sqlite3DbFree(pErrorDb, pParse->zErrMsg);
64276      sqlite3ParserReset(pParse);
64277      sqlite3StackFree(pErrorDb, pParse);
64278    }
64279    if( rc ){
64280      return 0;
64281    }
64282  }
64283
64284  if( i<0 ){
64285    sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
64286    return 0;
64287  }
64288
64289  return pDb->aDb[i].pBt;
64290}
64291
64292/*
64293** Attempt to set the page size of the destination to match the page size
64294** of the source.
64295*/
64296static int setDestPgsz(sqlite3_backup *p){
64297  int rc;
64298  rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
64299  return rc;
64300}
64301
64302/*
64303** Check that there is no open read-transaction on the b-tree passed as the
64304** second argument. If there is not, return SQLITE_OK. Otherwise, if there
64305** is an open read-transaction, return SQLITE_ERROR and leave an error
64306** message in database handle db.
64307*/
64308static int checkReadTransaction(sqlite3 *db, Btree *p){
64309  if( sqlite3BtreeIsInReadTrans(p) ){
64310    sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
64311    return SQLITE_ERROR;
64312  }
64313  return SQLITE_OK;
64314}
64315
64316/*
64317** Create an sqlite3_backup process to copy the contents of zSrcDb from
64318** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
64319** a pointer to the new sqlite3_backup object.
64320**
64321** If an error occurs, NULL is returned and an error code and error message
64322** stored in database handle pDestDb.
64323*/
64324SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
64325  sqlite3* pDestDb,                     /* Database to write to */
64326  const char *zDestDb,                  /* Name of database within pDestDb */
64327  sqlite3* pSrcDb,                      /* Database connection to read from */
64328  const char *zSrcDb                    /* Name of database within pSrcDb */
64329){
64330  sqlite3_backup *p;                    /* Value to return */
64331
64332#ifdef SQLITE_ENABLE_API_ARMOR
64333  if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
64334    (void)SQLITE_MISUSE_BKPT;
64335    return 0;
64336  }
64337#endif
64338
64339  /* Lock the source database handle. The destination database
64340  ** handle is not locked in this routine, but it is locked in
64341  ** sqlite3_backup_step(). The user is required to ensure that no
64342  ** other thread accesses the destination handle for the duration
64343  ** of the backup operation.  Any attempt to use the destination
64344  ** database connection while a backup is in progress may cause
64345  ** a malfunction or a deadlock.
64346  */
64347  sqlite3_mutex_enter(pSrcDb->mutex);
64348  sqlite3_mutex_enter(pDestDb->mutex);
64349
64350  if( pSrcDb==pDestDb ){
64351    sqlite3ErrorWithMsg(
64352        pDestDb, SQLITE_ERROR, "source and destination must be distinct"
64353    );
64354    p = 0;
64355  }else {
64356    /* Allocate space for a new sqlite3_backup object...
64357    ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
64358    ** call to sqlite3_backup_init() and is destroyed by a call to
64359    ** sqlite3_backup_finish(). */
64360    p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
64361    if( !p ){
64362      sqlite3Error(pDestDb, SQLITE_NOMEM);
64363    }
64364  }
64365
64366  /* If the allocation succeeded, populate the new object. */
64367  if( p ){
64368    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
64369    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
64370    p->pDestDb = pDestDb;
64371    p->pSrcDb = pSrcDb;
64372    p->iNext = 1;
64373    p->isAttached = 0;
64374
64375    if( 0==p->pSrc || 0==p->pDest
64376     || setDestPgsz(p)==SQLITE_NOMEM
64377     || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
64378     ){
64379      /* One (or both) of the named databases did not exist or an OOM
64380      ** error was hit. Or there is a transaction open on the destination
64381      ** database. The error has already been written into the pDestDb
64382      ** handle. All that is left to do here is free the sqlite3_backup
64383      ** structure.  */
64384      sqlite3_free(p);
64385      p = 0;
64386    }
64387  }
64388  if( p ){
64389    p->pSrc->nBackup++;
64390  }
64391
64392  sqlite3_mutex_leave(pDestDb->mutex);
64393  sqlite3_mutex_leave(pSrcDb->mutex);
64394  return p;
64395}
64396
64397/*
64398** Argument rc is an SQLite error code. Return true if this error is
64399** considered fatal if encountered during a backup operation. All errors
64400** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
64401*/
64402static int isFatalError(int rc){
64403  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
64404}
64405
64406/*
64407** Parameter zSrcData points to a buffer containing the data for
64408** page iSrcPg from the source database. Copy this data into the
64409** destination database.
64410*/
64411static int backupOnePage(
64412  sqlite3_backup *p,              /* Backup handle */
64413  Pgno iSrcPg,                    /* Source database page to backup */
64414  const u8 *zSrcData,             /* Source database page data */
64415  int bUpdate                     /* True for an update, false otherwise */
64416){
64417  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
64418  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
64419  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
64420  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
64421  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
64422#ifdef SQLITE_HAS_CODEC
64423  /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
64424  ** guaranteed that the shared-mutex is held by this thread, handle
64425  ** p->pSrc may not actually be the owner.  */
64426  int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
64427  int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
64428#endif
64429  int rc = SQLITE_OK;
64430  i64 iOff;
64431
64432  assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
64433  assert( p->bDestLocked );
64434  assert( !isFatalError(p->rc) );
64435  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
64436  assert( zSrcData );
64437
64438  /* Catch the case where the destination is an in-memory database and the
64439  ** page sizes of the source and destination differ.
64440  */
64441  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
64442    rc = SQLITE_READONLY;
64443  }
64444
64445#ifdef SQLITE_HAS_CODEC
64446  /* Backup is not possible if the page size of the destination is changing
64447  ** and a codec is in use.
64448  */
64449  if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
64450    rc = SQLITE_READONLY;
64451  }
64452
64453  /* Backup is not possible if the number of bytes of reserve space differ
64454  ** between source and destination.  If there is a difference, try to
64455  ** fix the destination to agree with the source.  If that is not possible,
64456  ** then the backup cannot proceed.
64457  */
64458  if( nSrcReserve!=nDestReserve ){
64459    u32 newPgsz = nSrcPgsz;
64460    rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
64461    if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
64462  }
64463#endif
64464
64465  /* This loop runs once for each destination page spanned by the source
64466  ** page. For each iteration, variable iOff is set to the byte offset
64467  ** of the destination page.
64468  */
64469  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
64470    DbPage *pDestPg = 0;
64471    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
64472    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
64473    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
64474     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
64475    ){
64476      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
64477      u8 *zDestData = sqlite3PagerGetData(pDestPg);
64478      u8 *zOut = &zDestData[iOff%nDestPgsz];
64479
64480      /* Copy the data from the source page into the destination page.
64481      ** Then clear the Btree layer MemPage.isInit flag. Both this module
64482      ** and the pager code use this trick (clearing the first byte
64483      ** of the page 'extra' space to invalidate the Btree layers
64484      ** cached parse of the page). MemPage.isInit is marked
64485      ** "MUST BE FIRST" for this purpose.
64486      */
64487      memcpy(zOut, zIn, nCopy);
64488      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
64489      if( iOff==0 && bUpdate==0 ){
64490        sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
64491      }
64492    }
64493    sqlite3PagerUnref(pDestPg);
64494  }
64495
64496  return rc;
64497}
64498
64499/*
64500** If pFile is currently larger than iSize bytes, then truncate it to
64501** exactly iSize bytes. If pFile is not larger than iSize bytes, then
64502** this function is a no-op.
64503**
64504** Return SQLITE_OK if everything is successful, or an SQLite error
64505** code if an error occurs.
64506*/
64507static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
64508  i64 iCurrent;
64509  int rc = sqlite3OsFileSize(pFile, &iCurrent);
64510  if( rc==SQLITE_OK && iCurrent>iSize ){
64511    rc = sqlite3OsTruncate(pFile, iSize);
64512  }
64513  return rc;
64514}
64515
64516/*
64517** Register this backup object with the associated source pager for
64518** callbacks when pages are changed or the cache invalidated.
64519*/
64520static void attachBackupObject(sqlite3_backup *p){
64521  sqlite3_backup **pp;
64522  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
64523  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
64524  p->pNext = *pp;
64525  *pp = p;
64526  p->isAttached = 1;
64527}
64528
64529/*
64530** Copy nPage pages from the source b-tree to the destination.
64531*/
64532SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage){
64533  int rc;
64534  int destMode;       /* Destination journal mode */
64535  int pgszSrc = 0;    /* Source page size */
64536  int pgszDest = 0;   /* Destination page size */
64537
64538#ifdef SQLITE_ENABLE_API_ARMOR
64539  if( p==0 ) return SQLITE_MISUSE_BKPT;
64540#endif
64541  sqlite3_mutex_enter(p->pSrcDb->mutex);
64542  sqlite3BtreeEnter(p->pSrc);
64543  if( p->pDestDb ){
64544    sqlite3_mutex_enter(p->pDestDb->mutex);
64545  }
64546
64547  rc = p->rc;
64548  if( !isFatalError(rc) ){
64549    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
64550    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
64551    int ii;                            /* Iterator variable */
64552    int nSrcPage = -1;                 /* Size of source db in pages */
64553    int bCloseTrans = 0;               /* True if src db requires unlocking */
64554
64555    /* If the source pager is currently in a write-transaction, return
64556    ** SQLITE_BUSY immediately.
64557    */
64558    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
64559      rc = SQLITE_BUSY;
64560    }else{
64561      rc = SQLITE_OK;
64562    }
64563
64564    /* Lock the destination database, if it is not locked already. */
64565    if( SQLITE_OK==rc && p->bDestLocked==0
64566     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
64567    ){
64568      p->bDestLocked = 1;
64569      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
64570    }
64571
64572    /* If there is no open read-transaction on the source database, open
64573    ** one now. If a transaction is opened here, then it will be closed
64574    ** before this function exits.
64575    */
64576    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
64577      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
64578      bCloseTrans = 1;
64579    }
64580
64581    /* Do not allow backup if the destination database is in WAL mode
64582    ** and the page sizes are different between source and destination */
64583    pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
64584    pgszDest = sqlite3BtreeGetPageSize(p->pDest);
64585    destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
64586    if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
64587      rc = SQLITE_READONLY;
64588    }
64589
64590    /* Now that there is a read-lock on the source database, query the
64591    ** source pager for the number of pages in the database.
64592    */
64593    nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
64594    assert( nSrcPage>=0 );
64595    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
64596      const Pgno iSrcPg = p->iNext;                 /* Source page number */
64597      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
64598        DbPage *pSrcPg;                             /* Source page object */
64599        rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
64600                                 PAGER_GET_READONLY);
64601        if( rc==SQLITE_OK ){
64602          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
64603          sqlite3PagerUnref(pSrcPg);
64604        }
64605      }
64606      p->iNext++;
64607    }
64608    if( rc==SQLITE_OK ){
64609      p->nPagecount = nSrcPage;
64610      p->nRemaining = nSrcPage+1-p->iNext;
64611      if( p->iNext>(Pgno)nSrcPage ){
64612        rc = SQLITE_DONE;
64613      }else if( !p->isAttached ){
64614        attachBackupObject(p);
64615      }
64616    }
64617
64618    /* Update the schema version field in the destination database. This
64619    ** is to make sure that the schema-version really does change in
64620    ** the case where the source and destination databases have the
64621    ** same schema version.
64622    */
64623    if( rc==SQLITE_DONE ){
64624      if( nSrcPage==0 ){
64625        rc = sqlite3BtreeNewDb(p->pDest);
64626        nSrcPage = 1;
64627      }
64628      if( rc==SQLITE_OK || rc==SQLITE_DONE ){
64629        rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
64630      }
64631      if( rc==SQLITE_OK ){
64632        if( p->pDestDb ){
64633          sqlite3ResetAllSchemasOfConnection(p->pDestDb);
64634        }
64635        if( destMode==PAGER_JOURNALMODE_WAL ){
64636          rc = sqlite3BtreeSetVersion(p->pDest, 2);
64637        }
64638      }
64639      if( rc==SQLITE_OK ){
64640        int nDestTruncate;
64641        /* Set nDestTruncate to the final number of pages in the destination
64642        ** database. The complication here is that the destination page
64643        ** size may be different to the source page size.
64644        **
64645        ** If the source page size is smaller than the destination page size,
64646        ** round up. In this case the call to sqlite3OsTruncate() below will
64647        ** fix the size of the file. However it is important to call
64648        ** sqlite3PagerTruncateImage() here so that any pages in the
64649        ** destination file that lie beyond the nDestTruncate page mark are
64650        ** journalled by PagerCommitPhaseOne() before they are destroyed
64651        ** by the file truncation.
64652        */
64653        assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
64654        assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
64655        if( pgszSrc<pgszDest ){
64656          int ratio = pgszDest/pgszSrc;
64657          nDestTruncate = (nSrcPage+ratio-1)/ratio;
64658          if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
64659            nDestTruncate--;
64660          }
64661        }else{
64662          nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
64663        }
64664        assert( nDestTruncate>0 );
64665
64666        if( pgszSrc<pgszDest ){
64667          /* If the source page-size is smaller than the destination page-size,
64668          ** two extra things may need to happen:
64669          **
64670          **   * The destination may need to be truncated, and
64671          **
64672          **   * Data stored on the pages immediately following the
64673          **     pending-byte page in the source database may need to be
64674          **     copied into the destination database.
64675          */
64676          const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
64677          sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
64678          Pgno iPg;
64679          int nDstPage;
64680          i64 iOff;
64681          i64 iEnd;
64682
64683          assert( pFile );
64684          assert( nDestTruncate==0
64685              || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
64686                nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
64687             && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
64688          ));
64689
64690          /* This block ensures that all data required to recreate the original
64691          ** database has been stored in the journal for pDestPager and the
64692          ** journal synced to disk. So at this point we may safely modify
64693          ** the database file in any way, knowing that if a power failure
64694          ** occurs, the original database will be reconstructed from the
64695          ** journal file.  */
64696          sqlite3PagerPagecount(pDestPager, &nDstPage);
64697          for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
64698            if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
64699              DbPage *pPg;
64700              rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
64701              if( rc==SQLITE_OK ){
64702                rc = sqlite3PagerWrite(pPg);
64703                sqlite3PagerUnref(pPg);
64704              }
64705            }
64706          }
64707          if( rc==SQLITE_OK ){
64708            rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
64709          }
64710
64711          /* Write the extra pages and truncate the database file as required */
64712          iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
64713          for(
64714            iOff=PENDING_BYTE+pgszSrc;
64715            rc==SQLITE_OK && iOff<iEnd;
64716            iOff+=pgszSrc
64717          ){
64718            PgHdr *pSrcPg = 0;
64719            const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
64720            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
64721            if( rc==SQLITE_OK ){
64722              u8 *zData = sqlite3PagerGetData(pSrcPg);
64723              rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
64724            }
64725            sqlite3PagerUnref(pSrcPg);
64726          }
64727          if( rc==SQLITE_OK ){
64728            rc = backupTruncateFile(pFile, iSize);
64729          }
64730
64731          /* Sync the database file to disk. */
64732          if( rc==SQLITE_OK ){
64733            rc = sqlite3PagerSync(pDestPager, 0);
64734          }
64735        }else{
64736          sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
64737          rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
64738        }
64739
64740        /* Finish committing the transaction to the destination database. */
64741        if( SQLITE_OK==rc
64742         && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
64743        ){
64744          rc = SQLITE_DONE;
64745        }
64746      }
64747    }
64748
64749    /* If bCloseTrans is true, then this function opened a read transaction
64750    ** on the source database. Close the read transaction here. There is
64751    ** no need to check the return values of the btree methods here, as
64752    ** "committing" a read-only transaction cannot fail.
64753    */
64754    if( bCloseTrans ){
64755      TESTONLY( int rc2 );
64756      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
64757      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
64758      assert( rc2==SQLITE_OK );
64759    }
64760
64761    if( rc==SQLITE_IOERR_NOMEM ){
64762      rc = SQLITE_NOMEM;
64763    }
64764    p->rc = rc;
64765  }
64766  if( p->pDestDb ){
64767    sqlite3_mutex_leave(p->pDestDb->mutex);
64768  }
64769  sqlite3BtreeLeave(p->pSrc);
64770  sqlite3_mutex_leave(p->pSrcDb->mutex);
64771  return rc;
64772}
64773
64774/*
64775** Release all resources associated with an sqlite3_backup* handle.
64776*/
64777SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p){
64778  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
64779  sqlite3 *pSrcDb;                     /* Source database connection */
64780  int rc;                              /* Value to return */
64781
64782  /* Enter the mutexes */
64783  if( p==0 ) return SQLITE_OK;
64784  pSrcDb = p->pSrcDb;
64785  sqlite3_mutex_enter(pSrcDb->mutex);
64786  sqlite3BtreeEnter(p->pSrc);
64787  if( p->pDestDb ){
64788    sqlite3_mutex_enter(p->pDestDb->mutex);
64789  }
64790
64791  /* Detach this backup from the source pager. */
64792  if( p->pDestDb ){
64793    p->pSrc->nBackup--;
64794  }
64795  if( p->isAttached ){
64796    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
64797    while( *pp!=p ){
64798      pp = &(*pp)->pNext;
64799    }
64800    *pp = p->pNext;
64801  }
64802
64803  /* If a transaction is still open on the Btree, roll it back. */
64804  sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
64805
64806  /* Set the error code of the destination database handle. */
64807  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
64808  if( p->pDestDb ){
64809    sqlite3Error(p->pDestDb, rc);
64810
64811    /* Exit the mutexes and free the backup context structure. */
64812    sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
64813  }
64814  sqlite3BtreeLeave(p->pSrc);
64815  if( p->pDestDb ){
64816    /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
64817    ** call to sqlite3_backup_init() and is destroyed by a call to
64818    ** sqlite3_backup_finish(). */
64819    sqlite3_free(p);
64820  }
64821  sqlite3LeaveMutexAndCloseZombie(pSrcDb);
64822  return rc;
64823}
64824
64825/*
64826** Return the number of pages still to be backed up as of the most recent
64827** call to sqlite3_backup_step().
64828*/
64829SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p){
64830#ifdef SQLITE_ENABLE_API_ARMOR
64831  if( p==0 ){
64832    (void)SQLITE_MISUSE_BKPT;
64833    return 0;
64834  }
64835#endif
64836  return p->nRemaining;
64837}
64838
64839/*
64840** Return the total number of pages in the source database as of the most
64841** recent call to sqlite3_backup_step().
64842*/
64843SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p){
64844#ifdef SQLITE_ENABLE_API_ARMOR
64845  if( p==0 ){
64846    (void)SQLITE_MISUSE_BKPT;
64847    return 0;
64848  }
64849#endif
64850  return p->nPagecount;
64851}
64852
64853/*
64854** This function is called after the contents of page iPage of the
64855** source database have been modified. If page iPage has already been
64856** copied into the destination database, then the data written to the
64857** destination is now invalidated. The destination copy of iPage needs
64858** to be updated with the new data before the backup operation is
64859** complete.
64860**
64861** It is assumed that the mutex associated with the BtShared object
64862** corresponding to the source database is held when this function is
64863** called.
64864*/
64865static SQLITE_NOINLINE void backupUpdate(
64866  sqlite3_backup *p,
64867  Pgno iPage,
64868  const u8 *aData
64869){
64870  assert( p!=0 );
64871  do{
64872    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
64873    if( !isFatalError(p->rc) && iPage<p->iNext ){
64874      /* The backup process p has already copied page iPage. But now it
64875      ** has been modified by a transaction on the source pager. Copy
64876      ** the new data into the backup.
64877      */
64878      int rc;
64879      assert( p->pDestDb );
64880      sqlite3_mutex_enter(p->pDestDb->mutex);
64881      rc = backupOnePage(p, iPage, aData, 1);
64882      sqlite3_mutex_leave(p->pDestDb->mutex);
64883      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
64884      if( rc!=SQLITE_OK ){
64885        p->rc = rc;
64886      }
64887    }
64888  }while( (p = p->pNext)!=0 );
64889}
64890SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
64891  if( pBackup ) backupUpdate(pBackup, iPage, aData);
64892}
64893
64894/*
64895** Restart the backup process. This is called when the pager layer
64896** detects that the database has been modified by an external database
64897** connection. In this case there is no way of knowing which of the
64898** pages that have been copied into the destination database are still
64899** valid and which are not, so the entire process needs to be restarted.
64900**
64901** It is assumed that the mutex associated with the BtShared object
64902** corresponding to the source database is held when this function is
64903** called.
64904*/
64905SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
64906  sqlite3_backup *p;                   /* Iterator variable */
64907  for(p=pBackup; p; p=p->pNext){
64908    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
64909    p->iNext = 1;
64910  }
64911}
64912
64913#ifndef SQLITE_OMIT_VACUUM
64914/*
64915** Copy the complete content of pBtFrom into pBtTo.  A transaction
64916** must be active for both files.
64917**
64918** The size of file pTo may be reduced by this operation. If anything
64919** goes wrong, the transaction on pTo is rolled back. If successful, the
64920** transaction is committed before returning.
64921*/
64922SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
64923  int rc;
64924  sqlite3_file *pFd;              /* File descriptor for database pTo */
64925  sqlite3_backup b;
64926  sqlite3BtreeEnter(pTo);
64927  sqlite3BtreeEnter(pFrom);
64928
64929  assert( sqlite3BtreeIsInTrans(pTo) );
64930  pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
64931  if( pFd->pMethods ){
64932    i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
64933    rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
64934    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
64935    if( rc ) goto copy_finished;
64936  }
64937
64938  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
64939  ** to 0. This is used by the implementations of sqlite3_backup_step()
64940  ** and sqlite3_backup_finish() to detect that they are being called
64941  ** from this function, not directly by the user.
64942  */
64943  memset(&b, 0, sizeof(b));
64944  b.pSrcDb = pFrom->db;
64945  b.pSrc = pFrom;
64946  b.pDest = pTo;
64947  b.iNext = 1;
64948
64949#ifdef SQLITE_HAS_CODEC
64950  sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
64951#endif
64952
64953  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
64954  ** file. By passing this as the number of pages to copy to
64955  ** sqlite3_backup_step(), we can guarantee that the copy finishes
64956  ** within a single call (unless an error occurs). The assert() statement
64957  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
64958  ** or an error code.
64959  */
64960  sqlite3_backup_step(&b, 0x7FFFFFFF);
64961  assert( b.rc!=SQLITE_OK );
64962  rc = sqlite3_backup_finish(&b);
64963  if( rc==SQLITE_OK ){
64964    pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
64965  }else{
64966    sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
64967  }
64968
64969  assert( sqlite3BtreeIsInTrans(pTo)==0 );
64970copy_finished:
64971  sqlite3BtreeLeave(pFrom);
64972  sqlite3BtreeLeave(pTo);
64973  return rc;
64974}
64975#endif /* SQLITE_OMIT_VACUUM */
64976
64977/************** End of backup.c **********************************************/
64978/************** Begin file vdbemem.c *****************************************/
64979/*
64980** 2004 May 26
64981**
64982** The author disclaims copyright to this source code.  In place of
64983** a legal notice, here is a blessing:
64984**
64985**    May you do good and not evil.
64986**    May you find forgiveness for yourself and forgive others.
64987**    May you share freely, never taking more than you give.
64988**
64989*************************************************************************
64990**
64991** This file contains code use to manipulate "Mem" structure.  A "Mem"
64992** stores a single value in the VDBE.  Mem is an opaque structure visible
64993** only within the VDBE.  Interface routines refer to a Mem using the
64994** name sqlite_value
64995*/
64996/* #include "sqliteInt.h" */
64997/* #include "vdbeInt.h" */
64998
64999#ifdef SQLITE_DEBUG
65000/*
65001** Check invariants on a Mem object.
65002**
65003** This routine is intended for use inside of assert() statements, like
65004** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
65005*/
65006SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
65007  /* If MEM_Dyn is set then Mem.xDel!=0.
65008  ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
65009  */
65010  assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
65011
65012  /* MEM_Dyn may only be set if Mem.szMalloc==0.  In this way we
65013  ** ensure that if Mem.szMalloc>0 then it is safe to do
65014  ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
65015  ** That saves a few cycles in inner loops. */
65016  assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
65017
65018  /* Cannot be both MEM_Int and MEM_Real at the same time */
65019  assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
65020
65021  /* The szMalloc field holds the correct memory allocation size */
65022  assert( p->szMalloc==0
65023       || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
65024
65025  /* If p holds a string or blob, the Mem.z must point to exactly
65026  ** one of the following:
65027  **
65028  **   (1) Memory in Mem.zMalloc and managed by the Mem object
65029  **   (2) Memory to be freed using Mem.xDel
65030  **   (3) An ephemeral string or blob
65031  **   (4) A static string or blob
65032  */
65033  if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
65034    assert(
65035      ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
65036      ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
65037      ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
65038      ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
65039    );
65040  }
65041  return 1;
65042}
65043#endif
65044
65045
65046/*
65047** If pMem is an object with a valid string representation, this routine
65048** ensures the internal encoding for the string representation is
65049** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
65050**
65051** If pMem is not a string object, or the encoding of the string
65052** representation is already stored using the requested encoding, then this
65053** routine is a no-op.
65054**
65055** SQLITE_OK is returned if the conversion is successful (or not required).
65056** SQLITE_NOMEM may be returned if a malloc() fails during conversion
65057** between formats.
65058*/
65059SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
65060#ifndef SQLITE_OMIT_UTF16
65061  int rc;
65062#endif
65063  assert( (pMem->flags&MEM_RowSet)==0 );
65064  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
65065           || desiredEnc==SQLITE_UTF16BE );
65066  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
65067    return SQLITE_OK;
65068  }
65069  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65070#ifdef SQLITE_OMIT_UTF16
65071  return SQLITE_ERROR;
65072#else
65073
65074  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
65075  ** then the encoding of the value may not have changed.
65076  */
65077  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
65078  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
65079  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
65080  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
65081  return rc;
65082#endif
65083}
65084
65085/*
65086** Make sure pMem->z points to a writable allocation of at least
65087** min(n,32) bytes.
65088**
65089** If the bPreserve argument is true, then copy of the content of
65090** pMem->z into the new allocation.  pMem must be either a string or
65091** blob if bPreserve is true.  If bPreserve is false, any prior content
65092** in pMem->z is discarded.
65093*/
65094SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
65095  assert( sqlite3VdbeCheckMemInvariants(pMem) );
65096  assert( (pMem->flags&MEM_RowSet)==0 );
65097
65098  /* If the bPreserve flag is set to true, then the memory cell must already
65099  ** contain a valid string or blob value.  */
65100  assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
65101  testcase( bPreserve && pMem->z==0 );
65102
65103  assert( pMem->szMalloc==0
65104       || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
65105  if( pMem->szMalloc<n ){
65106    if( n<32 ) n = 32;
65107    if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
65108      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
65109      bPreserve = 0;
65110    }else{
65111      if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
65112      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
65113    }
65114    if( pMem->zMalloc==0 ){
65115      sqlite3VdbeMemSetNull(pMem);
65116      pMem->z = 0;
65117      pMem->szMalloc = 0;
65118      return SQLITE_NOMEM;
65119    }else{
65120      pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
65121    }
65122  }
65123
65124  if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
65125    memcpy(pMem->zMalloc, pMem->z, pMem->n);
65126  }
65127  if( (pMem->flags&MEM_Dyn)!=0 ){
65128    assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
65129    pMem->xDel((void *)(pMem->z));
65130  }
65131
65132  pMem->z = pMem->zMalloc;
65133  pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
65134  return SQLITE_OK;
65135}
65136
65137/*
65138** Change the pMem->zMalloc allocation to be at least szNew bytes.
65139** If pMem->zMalloc already meets or exceeds the requested size, this
65140** routine is a no-op.
65141**
65142** Any prior string or blob content in the pMem object may be discarded.
65143** The pMem->xDel destructor is called, if it exists.  Though MEM_Str
65144** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
65145** values are preserved.
65146**
65147** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
65148** if unable to complete the resizing.
65149*/
65150SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
65151  assert( szNew>0 );
65152  assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
65153  if( pMem->szMalloc<szNew ){
65154    return sqlite3VdbeMemGrow(pMem, szNew, 0);
65155  }
65156  assert( (pMem->flags & MEM_Dyn)==0 );
65157  pMem->z = pMem->zMalloc;
65158  pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
65159  return SQLITE_OK;
65160}
65161
65162/*
65163** Change pMem so that its MEM_Str or MEM_Blob value is stored in
65164** MEM.zMalloc, where it can be safely written.
65165**
65166** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
65167*/
65168SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
65169  int f;
65170  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65171  assert( (pMem->flags&MEM_RowSet)==0 );
65172  ExpandBlob(pMem);
65173  f = pMem->flags;
65174  if( (f&(MEM_Str|MEM_Blob)) && (pMem->szMalloc==0 || pMem->z!=pMem->zMalloc) ){
65175    if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
65176      return SQLITE_NOMEM;
65177    }
65178    pMem->z[pMem->n] = 0;
65179    pMem->z[pMem->n+1] = 0;
65180    pMem->flags |= MEM_Term;
65181  }
65182  pMem->flags &= ~MEM_Ephem;
65183#ifdef SQLITE_DEBUG
65184  pMem->pScopyFrom = 0;
65185#endif
65186
65187  return SQLITE_OK;
65188}
65189
65190/*
65191** If the given Mem* has a zero-filled tail, turn it into an ordinary
65192** blob stored in dynamically allocated space.
65193*/
65194#ifndef SQLITE_OMIT_INCRBLOB
65195SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
65196  if( pMem->flags & MEM_Zero ){
65197    int nByte;
65198    assert( pMem->flags&MEM_Blob );
65199    assert( (pMem->flags&MEM_RowSet)==0 );
65200    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65201
65202    /* Set nByte to the number of bytes required to store the expanded blob. */
65203    nByte = pMem->n + pMem->u.nZero;
65204    if( nByte<=0 ){
65205      nByte = 1;
65206    }
65207    if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
65208      return SQLITE_NOMEM;
65209    }
65210
65211    memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
65212    pMem->n += pMem->u.nZero;
65213    pMem->flags &= ~(MEM_Zero|MEM_Term);
65214  }
65215  return SQLITE_OK;
65216}
65217#endif
65218
65219/*
65220** It is already known that pMem contains an unterminated string.
65221** Add the zero terminator.
65222*/
65223static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
65224  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
65225    return SQLITE_NOMEM;
65226  }
65227  pMem->z[pMem->n] = 0;
65228  pMem->z[pMem->n+1] = 0;
65229  pMem->flags |= MEM_Term;
65230  return SQLITE_OK;
65231}
65232
65233/*
65234** Make sure the given Mem is \u0000 terminated.
65235*/
65236SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
65237  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65238  testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
65239  testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
65240  if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
65241    return SQLITE_OK;   /* Nothing to do */
65242  }else{
65243    return vdbeMemAddTerminator(pMem);
65244  }
65245}
65246
65247/*
65248** Add MEM_Str to the set of representations for the given Mem.  Numbers
65249** are converted using sqlite3_snprintf().  Converting a BLOB to a string
65250** is a no-op.
65251**
65252** Existing representations MEM_Int and MEM_Real are invalidated if
65253** bForce is true but are retained if bForce is false.
65254**
65255** A MEM_Null value will never be passed to this function. This function is
65256** used for converting values to text for returning to the user (i.e. via
65257** sqlite3_value_text()), or for ensuring that values to be used as btree
65258** keys are strings. In the former case a NULL pointer is returned the
65259** user and the latter is an internal programming error.
65260*/
65261SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
65262  int fg = pMem->flags;
65263  const int nByte = 32;
65264
65265  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65266  assert( !(fg&MEM_Zero) );
65267  assert( !(fg&(MEM_Str|MEM_Blob)) );
65268  assert( fg&(MEM_Int|MEM_Real) );
65269  assert( (pMem->flags&MEM_RowSet)==0 );
65270  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
65271
65272
65273  if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
65274    return SQLITE_NOMEM;
65275  }
65276
65277  /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
65278  ** string representation of the value. Then, if the required encoding
65279  ** is UTF-16le or UTF-16be do a translation.
65280  **
65281  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
65282  */
65283  if( fg & MEM_Int ){
65284    sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
65285  }else{
65286    assert( fg & MEM_Real );
65287    sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
65288  }
65289  pMem->n = sqlite3Strlen30(pMem->z);
65290  pMem->enc = SQLITE_UTF8;
65291  pMem->flags |= MEM_Str|MEM_Term;
65292  if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
65293  sqlite3VdbeChangeEncoding(pMem, enc);
65294  return SQLITE_OK;
65295}
65296
65297/*
65298** Memory cell pMem contains the context of an aggregate function.
65299** This routine calls the finalize method for that function.  The
65300** result of the aggregate is stored back into pMem.
65301**
65302** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
65303** otherwise.
65304*/
65305SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
65306  int rc = SQLITE_OK;
65307  if( ALWAYS(pFunc && pFunc->xFinalize) ){
65308    sqlite3_context ctx;
65309    Mem t;
65310    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
65311    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65312    memset(&ctx, 0, sizeof(ctx));
65313    memset(&t, 0, sizeof(t));
65314    t.flags = MEM_Null;
65315    t.db = pMem->db;
65316    ctx.pOut = &t;
65317    ctx.pMem = pMem;
65318    ctx.pFunc = pFunc;
65319    pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
65320    assert( (pMem->flags & MEM_Dyn)==0 );
65321    if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
65322    memcpy(pMem, &t, sizeof(t));
65323    rc = ctx.isError;
65324  }
65325  return rc;
65326}
65327
65328/*
65329** If the memory cell contains a value that must be freed by
65330** invoking the external callback in Mem.xDel, then this routine
65331** will free that value.  It also sets Mem.flags to MEM_Null.
65332**
65333** This is a helper routine for sqlite3VdbeMemSetNull() and
65334** for sqlite3VdbeMemRelease().  Use those other routines as the
65335** entry point for releasing Mem resources.
65336*/
65337static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
65338  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
65339  assert( VdbeMemDynamic(p) );
65340  if( p->flags&MEM_Agg ){
65341    sqlite3VdbeMemFinalize(p, p->u.pDef);
65342    assert( (p->flags & MEM_Agg)==0 );
65343    testcase( p->flags & MEM_Dyn );
65344  }
65345  if( p->flags&MEM_Dyn ){
65346    assert( (p->flags&MEM_RowSet)==0 );
65347    assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
65348    p->xDel((void *)p->z);
65349  }else if( p->flags&MEM_RowSet ){
65350    sqlite3RowSetClear(p->u.pRowSet);
65351  }else if( p->flags&MEM_Frame ){
65352    VdbeFrame *pFrame = p->u.pFrame;
65353    pFrame->pParent = pFrame->v->pDelFrame;
65354    pFrame->v->pDelFrame = pFrame;
65355  }
65356  p->flags = MEM_Null;
65357}
65358
65359/*
65360** Release memory held by the Mem p, both external memory cleared
65361** by p->xDel and memory in p->zMalloc.
65362**
65363** This is a helper routine invoked by sqlite3VdbeMemRelease() in
65364** the unusual case where there really is memory in p that needs
65365** to be freed.
65366*/
65367static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
65368  if( VdbeMemDynamic(p) ){
65369    vdbeMemClearExternAndSetNull(p);
65370  }
65371  if( p->szMalloc ){
65372    sqlite3DbFree(p->db, p->zMalloc);
65373    p->szMalloc = 0;
65374  }
65375  p->z = 0;
65376}
65377
65378/*
65379** Release any memory resources held by the Mem.  Both the memory that is
65380** free by Mem.xDel and the Mem.zMalloc allocation are freed.
65381**
65382** Use this routine prior to clean up prior to abandoning a Mem, or to
65383** reset a Mem back to its minimum memory utilization.
65384**
65385** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
65386** prior to inserting new content into the Mem.
65387*/
65388SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
65389  assert( sqlite3VdbeCheckMemInvariants(p) );
65390  if( VdbeMemDynamic(p) || p->szMalloc ){
65391    vdbeMemClear(p);
65392  }
65393}
65394
65395/*
65396** Convert a 64-bit IEEE double into a 64-bit signed integer.
65397** If the double is out of range of a 64-bit signed integer then
65398** return the closest available 64-bit signed integer.
65399*/
65400static i64 doubleToInt64(double r){
65401#ifdef SQLITE_OMIT_FLOATING_POINT
65402  /* When floating-point is omitted, double and int64 are the same thing */
65403  return r;
65404#else
65405  /*
65406  ** Many compilers we encounter do not define constants for the
65407  ** minimum and maximum 64-bit integers, or they define them
65408  ** inconsistently.  And many do not understand the "LL" notation.
65409  ** So we define our own static constants here using nothing
65410  ** larger than a 32-bit integer constant.
65411  */
65412  static const i64 maxInt = LARGEST_INT64;
65413  static const i64 minInt = SMALLEST_INT64;
65414
65415  if( r<=(double)minInt ){
65416    return minInt;
65417  }else if( r>=(double)maxInt ){
65418    return maxInt;
65419  }else{
65420    return (i64)r;
65421  }
65422#endif
65423}
65424
65425/*
65426** Return some kind of integer value which is the best we can do
65427** at representing the value that *pMem describes as an integer.
65428** If pMem is an integer, then the value is exact.  If pMem is
65429** a floating-point then the value returned is the integer part.
65430** If pMem is a string or blob, then we make an attempt to convert
65431** it into an integer and return that.  If pMem represents an
65432** an SQL-NULL value, return 0.
65433**
65434** If pMem represents a string value, its encoding might be changed.
65435*/
65436SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
65437  int flags;
65438  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65439  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
65440  flags = pMem->flags;
65441  if( flags & MEM_Int ){
65442    return pMem->u.i;
65443  }else if( flags & MEM_Real ){
65444    return doubleToInt64(pMem->u.r);
65445  }else if( flags & (MEM_Str|MEM_Blob) ){
65446    i64 value = 0;
65447    assert( pMem->z || pMem->n==0 );
65448    sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
65449    return value;
65450  }else{
65451    return 0;
65452  }
65453}
65454
65455/*
65456** Return the best representation of pMem that we can get into a
65457** double.  If pMem is already a double or an integer, return its
65458** value.  If it is a string or blob, try to convert it to a double.
65459** If it is a NULL, return 0.0.
65460*/
65461SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
65462  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65463  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
65464  if( pMem->flags & MEM_Real ){
65465    return pMem->u.r;
65466  }else if( pMem->flags & MEM_Int ){
65467    return (double)pMem->u.i;
65468  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
65469    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
65470    double val = (double)0;
65471    sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
65472    return val;
65473  }else{
65474    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
65475    return (double)0;
65476  }
65477}
65478
65479/*
65480** The MEM structure is already a MEM_Real.  Try to also make it a
65481** MEM_Int if we can.
65482*/
65483SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
65484  i64 ix;
65485  assert( pMem->flags & MEM_Real );
65486  assert( (pMem->flags & MEM_RowSet)==0 );
65487  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65488  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
65489
65490  ix = doubleToInt64(pMem->u.r);
65491
65492  /* Only mark the value as an integer if
65493  **
65494  **    (1) the round-trip conversion real->int->real is a no-op, and
65495  **    (2) The integer is neither the largest nor the smallest
65496  **        possible integer (ticket #3922)
65497  **
65498  ** The second and third terms in the following conditional enforces
65499  ** the second condition under the assumption that addition overflow causes
65500  ** values to wrap around.
65501  */
65502  if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
65503    pMem->u.i = ix;
65504    MemSetTypeFlag(pMem, MEM_Int);
65505  }
65506}
65507
65508/*
65509** Convert pMem to type integer.  Invalidate any prior representations.
65510*/
65511SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
65512  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65513  assert( (pMem->flags & MEM_RowSet)==0 );
65514  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
65515
65516  pMem->u.i = sqlite3VdbeIntValue(pMem);
65517  MemSetTypeFlag(pMem, MEM_Int);
65518  return SQLITE_OK;
65519}
65520
65521/*
65522** Convert pMem so that it is of type MEM_Real.
65523** Invalidate any prior representations.
65524*/
65525SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
65526  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65527  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
65528
65529  pMem->u.r = sqlite3VdbeRealValue(pMem);
65530  MemSetTypeFlag(pMem, MEM_Real);
65531  return SQLITE_OK;
65532}
65533
65534/*
65535** Convert pMem so that it has types MEM_Real or MEM_Int or both.
65536** Invalidate any prior representations.
65537**
65538** Every effort is made to force the conversion, even if the input
65539** is a string that does not look completely like a number.  Convert
65540** as much of the string as we can and ignore the rest.
65541*/
65542SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
65543  if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
65544    assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
65545    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65546    if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
65547      MemSetTypeFlag(pMem, MEM_Int);
65548    }else{
65549      pMem->u.r = sqlite3VdbeRealValue(pMem);
65550      MemSetTypeFlag(pMem, MEM_Real);
65551      sqlite3VdbeIntegerAffinity(pMem);
65552    }
65553  }
65554  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
65555  pMem->flags &= ~(MEM_Str|MEM_Blob);
65556  return SQLITE_OK;
65557}
65558
65559/*
65560** Cast the datatype of the value in pMem according to the affinity
65561** "aff".  Casting is different from applying affinity in that a cast
65562** is forced.  In other words, the value is converted into the desired
65563** affinity even if that results in loss of data.  This routine is
65564** used (for example) to implement the SQL "cast()" operator.
65565*/
65566SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
65567  if( pMem->flags & MEM_Null ) return;
65568  switch( aff ){
65569    case SQLITE_AFF_BLOB: {   /* Really a cast to BLOB */
65570      if( (pMem->flags & MEM_Blob)==0 ){
65571        sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
65572        assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
65573        MemSetTypeFlag(pMem, MEM_Blob);
65574      }else{
65575        pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
65576      }
65577      break;
65578    }
65579    case SQLITE_AFF_NUMERIC: {
65580      sqlite3VdbeMemNumerify(pMem);
65581      break;
65582    }
65583    case SQLITE_AFF_INTEGER: {
65584      sqlite3VdbeMemIntegerify(pMem);
65585      break;
65586    }
65587    case SQLITE_AFF_REAL: {
65588      sqlite3VdbeMemRealify(pMem);
65589      break;
65590    }
65591    default: {
65592      assert( aff==SQLITE_AFF_TEXT );
65593      assert( MEM_Str==(MEM_Blob>>3) );
65594      pMem->flags |= (pMem->flags&MEM_Blob)>>3;
65595      sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
65596      assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
65597      pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
65598      break;
65599    }
65600  }
65601}
65602
65603/*
65604** Initialize bulk memory to be a consistent Mem object.
65605**
65606** The minimum amount of initialization feasible is performed.
65607*/
65608SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
65609  assert( (flags & ~MEM_TypeMask)==0 );
65610  pMem->flags = flags;
65611  pMem->db = db;
65612  pMem->szMalloc = 0;
65613}
65614
65615
65616/*
65617** Delete any previous value and set the value stored in *pMem to NULL.
65618**
65619** This routine calls the Mem.xDel destructor to dispose of values that
65620** require the destructor.  But it preserves the Mem.zMalloc memory allocation.
65621** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
65622** routine to invoke the destructor and deallocates Mem.zMalloc.
65623**
65624** Use this routine to reset the Mem prior to insert a new value.
65625**
65626** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
65627*/
65628SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
65629  if( VdbeMemDynamic(pMem) ){
65630    vdbeMemClearExternAndSetNull(pMem);
65631  }else{
65632    pMem->flags = MEM_Null;
65633  }
65634}
65635SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
65636  sqlite3VdbeMemSetNull((Mem*)p);
65637}
65638
65639/*
65640** Delete any previous value and set the value to be a BLOB of length
65641** n containing all zeros.
65642*/
65643SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
65644  sqlite3VdbeMemRelease(pMem);
65645  pMem->flags = MEM_Blob|MEM_Zero;
65646  pMem->n = 0;
65647  if( n<0 ) n = 0;
65648  pMem->u.nZero = n;
65649  pMem->enc = SQLITE_UTF8;
65650  pMem->z = 0;
65651}
65652
65653/*
65654** The pMem is known to contain content that needs to be destroyed prior
65655** to a value change.  So invoke the destructor, then set the value to
65656** a 64-bit integer.
65657*/
65658static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
65659  sqlite3VdbeMemSetNull(pMem);
65660  pMem->u.i = val;
65661  pMem->flags = MEM_Int;
65662}
65663
65664/*
65665** Delete any previous value and set the value stored in *pMem to val,
65666** manifest type INTEGER.
65667*/
65668SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
65669  if( VdbeMemDynamic(pMem) ){
65670    vdbeReleaseAndSetInt64(pMem, val);
65671  }else{
65672    pMem->u.i = val;
65673    pMem->flags = MEM_Int;
65674  }
65675}
65676
65677#ifndef SQLITE_OMIT_FLOATING_POINT
65678/*
65679** Delete any previous value and set the value stored in *pMem to val,
65680** manifest type REAL.
65681*/
65682SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
65683  sqlite3VdbeMemSetNull(pMem);
65684  if( !sqlite3IsNaN(val) ){
65685    pMem->u.r = val;
65686    pMem->flags = MEM_Real;
65687  }
65688}
65689#endif
65690
65691/*
65692** Delete any previous value and set the value of pMem to be an
65693** empty boolean index.
65694*/
65695SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
65696  sqlite3 *db = pMem->db;
65697  assert( db!=0 );
65698  assert( (pMem->flags & MEM_RowSet)==0 );
65699  sqlite3VdbeMemRelease(pMem);
65700  pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
65701  if( db->mallocFailed ){
65702    pMem->flags = MEM_Null;
65703    pMem->szMalloc = 0;
65704  }else{
65705    assert( pMem->zMalloc );
65706    pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
65707    pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
65708    assert( pMem->u.pRowSet!=0 );
65709    pMem->flags = MEM_RowSet;
65710  }
65711}
65712
65713/*
65714** Return true if the Mem object contains a TEXT or BLOB that is
65715** too large - whose size exceeds SQLITE_MAX_LENGTH.
65716*/
65717SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
65718  assert( p->db!=0 );
65719  if( p->flags & (MEM_Str|MEM_Blob) ){
65720    int n = p->n;
65721    if( p->flags & MEM_Zero ){
65722      n += p->u.nZero;
65723    }
65724    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
65725  }
65726  return 0;
65727}
65728
65729#ifdef SQLITE_DEBUG
65730/*
65731** This routine prepares a memory cell for modification by breaking
65732** its link to a shallow copy and by marking any current shallow
65733** copies of this cell as invalid.
65734**
65735** This is used for testing and debugging only - to make sure shallow
65736** copies are not misused.
65737*/
65738SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
65739  int i;
65740  Mem *pX;
65741  for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
65742    if( pX->pScopyFrom==pMem ){
65743      pX->flags |= MEM_Undefined;
65744      pX->pScopyFrom = 0;
65745    }
65746  }
65747  pMem->pScopyFrom = 0;
65748}
65749#endif /* SQLITE_DEBUG */
65750
65751
65752/*
65753** Make an shallow copy of pFrom into pTo.  Prior contents of
65754** pTo are freed.  The pFrom->z field is not duplicated.  If
65755** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
65756** and flags gets srcType (either MEM_Ephem or MEM_Static).
65757*/
65758static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
65759  vdbeMemClearExternAndSetNull(pTo);
65760  assert( !VdbeMemDynamic(pTo) );
65761  sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
65762}
65763SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
65764  assert( (pFrom->flags & MEM_RowSet)==0 );
65765  assert( pTo->db==pFrom->db );
65766  if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
65767  memcpy(pTo, pFrom, MEMCELLSIZE);
65768  if( (pFrom->flags&MEM_Static)==0 ){
65769    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
65770    assert( srcType==MEM_Ephem || srcType==MEM_Static );
65771    pTo->flags |= srcType;
65772  }
65773}
65774
65775/*
65776** Make a full copy of pFrom into pTo.  Prior contents of pTo are
65777** freed before the copy is made.
65778*/
65779SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
65780  int rc = SQLITE_OK;
65781
65782  /* The pFrom==0 case in the following assert() is when an sqlite3_value
65783  ** from sqlite3_value_dup() is used as the argument
65784  ** to sqlite3_result_value(). */
65785  assert( pTo->db==pFrom->db || pFrom->db==0 );
65786  assert( (pFrom->flags & MEM_RowSet)==0 );
65787  if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
65788  memcpy(pTo, pFrom, MEMCELLSIZE);
65789  pTo->flags &= ~MEM_Dyn;
65790  if( pTo->flags&(MEM_Str|MEM_Blob) ){
65791    if( 0==(pFrom->flags&MEM_Static) ){
65792      pTo->flags |= MEM_Ephem;
65793      rc = sqlite3VdbeMemMakeWriteable(pTo);
65794    }
65795  }
65796
65797  return rc;
65798}
65799
65800/*
65801** Transfer the contents of pFrom to pTo. Any existing value in pTo is
65802** freed. If pFrom contains ephemeral data, a copy is made.
65803**
65804** pFrom contains an SQL NULL when this routine returns.
65805*/
65806SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
65807  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
65808  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
65809  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
65810
65811  sqlite3VdbeMemRelease(pTo);
65812  memcpy(pTo, pFrom, sizeof(Mem));
65813  pFrom->flags = MEM_Null;
65814  pFrom->szMalloc = 0;
65815}
65816
65817/*
65818** Change the value of a Mem to be a string or a BLOB.
65819**
65820** The memory management strategy depends on the value of the xDel
65821** parameter. If the value passed is SQLITE_TRANSIENT, then the
65822** string is copied into a (possibly existing) buffer managed by the
65823** Mem structure. Otherwise, any existing buffer is freed and the
65824** pointer copied.
65825**
65826** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
65827** size limit) then no memory allocation occurs.  If the string can be
65828** stored without allocating memory, then it is.  If a memory allocation
65829** is required to store the string, then value of pMem is unchanged.  In
65830** either case, SQLITE_TOOBIG is returned.
65831*/
65832SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
65833  Mem *pMem,          /* Memory cell to set to string value */
65834  const char *z,      /* String pointer */
65835  int n,              /* Bytes in string, or negative */
65836  u8 enc,             /* Encoding of z.  0 for BLOBs */
65837  void (*xDel)(void*) /* Destructor function */
65838){
65839  int nByte = n;      /* New value for pMem->n */
65840  int iLimit;         /* Maximum allowed string or blob size */
65841  u16 flags = 0;      /* New value for pMem->flags */
65842
65843  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
65844  assert( (pMem->flags & MEM_RowSet)==0 );
65845
65846  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
65847  if( !z ){
65848    sqlite3VdbeMemSetNull(pMem);
65849    return SQLITE_OK;
65850  }
65851
65852  if( pMem->db ){
65853    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
65854  }else{
65855    iLimit = SQLITE_MAX_LENGTH;
65856  }
65857  flags = (enc==0?MEM_Blob:MEM_Str);
65858  if( nByte<0 ){
65859    assert( enc!=0 );
65860    if( enc==SQLITE_UTF8 ){
65861      nByte = sqlite3Strlen30(z);
65862      if( nByte>iLimit ) nByte = iLimit+1;
65863    }else{
65864      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
65865    }
65866    flags |= MEM_Term;
65867  }
65868
65869  /* The following block sets the new values of Mem.z and Mem.xDel. It
65870  ** also sets a flag in local variable "flags" to indicate the memory
65871  ** management (one of MEM_Dyn or MEM_Static).
65872  */
65873  if( xDel==SQLITE_TRANSIENT ){
65874    int nAlloc = nByte;
65875    if( flags&MEM_Term ){
65876      nAlloc += (enc==SQLITE_UTF8?1:2);
65877    }
65878    if( nByte>iLimit ){
65879      return SQLITE_TOOBIG;
65880    }
65881    testcase( nAlloc==0 );
65882    testcase( nAlloc==31 );
65883    testcase( nAlloc==32 );
65884    if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
65885      return SQLITE_NOMEM;
65886    }
65887    memcpy(pMem->z, z, nAlloc);
65888  }else if( xDel==SQLITE_DYNAMIC ){
65889    sqlite3VdbeMemRelease(pMem);
65890    pMem->zMalloc = pMem->z = (char *)z;
65891    pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
65892  }else{
65893    sqlite3VdbeMemRelease(pMem);
65894    pMem->z = (char *)z;
65895    pMem->xDel = xDel;
65896    flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
65897  }
65898
65899  pMem->n = nByte;
65900  pMem->flags = flags;
65901  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
65902
65903#ifndef SQLITE_OMIT_UTF16
65904  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
65905    return SQLITE_NOMEM;
65906  }
65907#endif
65908
65909  if( nByte>iLimit ){
65910    return SQLITE_TOOBIG;
65911  }
65912
65913  return SQLITE_OK;
65914}
65915
65916/*
65917** Move data out of a btree key or data field and into a Mem structure.
65918** The data or key is taken from the entry that pCur is currently pointing
65919** to.  offset and amt determine what portion of the data or key to retrieve.
65920** key is true to get the key or false to get data.  The result is written
65921** into the pMem element.
65922**
65923** The pMem object must have been initialized.  This routine will use
65924** pMem->zMalloc to hold the content from the btree, if possible.  New
65925** pMem->zMalloc space will be allocated if necessary.  The calling routine
65926** is responsible for making sure that the pMem object is eventually
65927** destroyed.
65928**
65929** If this routine fails for any reason (malloc returns NULL or unable
65930** to read from the disk) then the pMem is left in an inconsistent state.
65931*/
65932static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
65933  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
65934  u32 offset,       /* Offset from the start of data to return bytes from. */
65935  u32 amt,          /* Number of bytes to return. */
65936  int key,          /* If true, retrieve from the btree key, not data. */
65937  Mem *pMem         /* OUT: Return data in this Mem structure. */
65938){
65939  int rc;
65940  pMem->flags = MEM_Null;
65941  if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
65942    if( key ){
65943      rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
65944    }else{
65945      rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
65946    }
65947    if( rc==SQLITE_OK ){
65948      pMem->z[amt] = 0;
65949      pMem->z[amt+1] = 0;
65950      pMem->flags = MEM_Blob|MEM_Term;
65951      pMem->n = (int)amt;
65952    }else{
65953      sqlite3VdbeMemRelease(pMem);
65954    }
65955  }
65956  return rc;
65957}
65958SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
65959  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
65960  u32 offset,       /* Offset from the start of data to return bytes from. */
65961  u32 amt,          /* Number of bytes to return. */
65962  int key,          /* If true, retrieve from the btree key, not data. */
65963  Mem *pMem         /* OUT: Return data in this Mem structure. */
65964){
65965  char *zData;        /* Data from the btree layer */
65966  u32 available = 0;  /* Number of bytes available on the local btree page */
65967  int rc = SQLITE_OK; /* Return code */
65968
65969  assert( sqlite3BtreeCursorIsValid(pCur) );
65970  assert( !VdbeMemDynamic(pMem) );
65971
65972  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
65973  ** that both the BtShared and database handle mutexes are held. */
65974  assert( (pMem->flags & MEM_RowSet)==0 );
65975  if( key ){
65976    zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
65977  }else{
65978    zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
65979  }
65980  assert( zData!=0 );
65981
65982  if( offset+amt<=available ){
65983    pMem->z = &zData[offset];
65984    pMem->flags = MEM_Blob|MEM_Ephem;
65985    pMem->n = (int)amt;
65986  }else{
65987    rc = vdbeMemFromBtreeResize(pCur, offset, amt, key, pMem);
65988  }
65989
65990  return rc;
65991}
65992
65993/*
65994** The pVal argument is known to be a value other than NULL.
65995** Convert it into a string with encoding enc and return a pointer
65996** to a zero-terminated version of that string.
65997*/
65998static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
65999  assert( pVal!=0 );
66000  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
66001  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
66002  assert( (pVal->flags & MEM_RowSet)==0 );
66003  assert( (pVal->flags & (MEM_Null))==0 );
66004  if( pVal->flags & (MEM_Blob|MEM_Str) ){
66005    pVal->flags |= MEM_Str;
66006    if( pVal->flags & MEM_Zero ){
66007      sqlite3VdbeMemExpandBlob(pVal);
66008    }
66009    if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
66010      sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
66011    }
66012    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
66013      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
66014      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
66015        return 0;
66016      }
66017    }
66018    sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
66019  }else{
66020    sqlite3VdbeMemStringify(pVal, enc, 0);
66021    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
66022  }
66023  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
66024              || pVal->db->mallocFailed );
66025  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
66026    return pVal->z;
66027  }else{
66028    return 0;
66029  }
66030}
66031
66032/* This function is only available internally, it is not part of the
66033** external API. It works in a similar way to sqlite3_value_text(),
66034** except the data returned is in the encoding specified by the second
66035** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
66036** SQLITE_UTF8.
66037**
66038** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
66039** If that is the case, then the result must be aligned on an even byte
66040** boundary.
66041*/
66042SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
66043  if( !pVal ) return 0;
66044  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
66045  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
66046  assert( (pVal->flags & MEM_RowSet)==0 );
66047  if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
66048    return pVal->z;
66049  }
66050  if( pVal->flags&MEM_Null ){
66051    return 0;
66052  }
66053  return valueToText(pVal, enc);
66054}
66055
66056/*
66057** Create a new sqlite3_value object.
66058*/
66059SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
66060  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
66061  if( p ){
66062    p->flags = MEM_Null;
66063    p->db = db;
66064  }
66065  return p;
66066}
66067
66068/*
66069** Context object passed by sqlite3Stat4ProbeSetValue() through to
66070** valueNew(). See comments above valueNew() for details.
66071*/
66072struct ValueNewStat4Ctx {
66073  Parse *pParse;
66074  Index *pIdx;
66075  UnpackedRecord **ppRec;
66076  int iVal;
66077};
66078
66079/*
66080** Allocate and return a pointer to a new sqlite3_value object. If
66081** the second argument to this function is NULL, the object is allocated
66082** by calling sqlite3ValueNew().
66083**
66084** Otherwise, if the second argument is non-zero, then this function is
66085** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
66086** already been allocated, allocate the UnpackedRecord structure that
66087** that function will return to its caller here. Then return a pointer to
66088** an sqlite3_value within the UnpackedRecord.a[] array.
66089*/
66090static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
66091#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
66092  if( p ){
66093    UnpackedRecord *pRec = p->ppRec[0];
66094
66095    if( pRec==0 ){
66096      Index *pIdx = p->pIdx;      /* Index being probed */
66097      int nByte;                  /* Bytes of space to allocate */
66098      int i;                      /* Counter variable */
66099      int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
66100
66101      nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
66102      pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
66103      if( pRec ){
66104        pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
66105        if( pRec->pKeyInfo ){
66106          assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
66107          assert( pRec->pKeyInfo->enc==ENC(db) );
66108          pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
66109          for(i=0; i<nCol; i++){
66110            pRec->aMem[i].flags = MEM_Null;
66111            pRec->aMem[i].db = db;
66112          }
66113        }else{
66114          sqlite3DbFree(db, pRec);
66115          pRec = 0;
66116        }
66117      }
66118      if( pRec==0 ) return 0;
66119      p->ppRec[0] = pRec;
66120    }
66121
66122    pRec->nField = p->iVal+1;
66123    return &pRec->aMem[p->iVal];
66124  }
66125#else
66126  UNUSED_PARAMETER(p);
66127#endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
66128  return sqlite3ValueNew(db);
66129}
66130
66131/*
66132** The expression object indicated by the second argument is guaranteed
66133** to be a scalar SQL function. If
66134**
66135**   * all function arguments are SQL literals,
66136**   * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
66137**   * the SQLITE_FUNC_NEEDCOLL function flag is not set,
66138**
66139** then this routine attempts to invoke the SQL function. Assuming no
66140** error occurs, output parameter (*ppVal) is set to point to a value
66141** object containing the result before returning SQLITE_OK.
66142**
66143** Affinity aff is applied to the result of the function before returning.
66144** If the result is a text value, the sqlite3_value object uses encoding
66145** enc.
66146**
66147** If the conditions above are not met, this function returns SQLITE_OK
66148** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
66149** NULL and an SQLite error code returned.
66150*/
66151#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
66152static int valueFromFunction(
66153  sqlite3 *db,                    /* The database connection */
66154  Expr *p,                        /* The expression to evaluate */
66155  u8 enc,                         /* Encoding to use */
66156  u8 aff,                         /* Affinity to use */
66157  sqlite3_value **ppVal,          /* Write the new value here */
66158  struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
66159){
66160  sqlite3_context ctx;            /* Context object for function invocation */
66161  sqlite3_value **apVal = 0;      /* Function arguments */
66162  int nVal = 0;                   /* Size of apVal[] array */
66163  FuncDef *pFunc = 0;             /* Function definition */
66164  sqlite3_value *pVal = 0;        /* New value */
66165  int rc = SQLITE_OK;             /* Return code */
66166  int nName;                      /* Size of function name in bytes */
66167  ExprList *pList = 0;            /* Function arguments */
66168  int i;                          /* Iterator variable */
66169
66170  assert( pCtx!=0 );
66171  assert( (p->flags & EP_TokenOnly)==0 );
66172  pList = p->x.pList;
66173  if( pList ) nVal = pList->nExpr;
66174  nName = sqlite3Strlen30(p->u.zToken);
66175  pFunc = sqlite3FindFunction(db, p->u.zToken, nName, nVal, enc, 0);
66176  assert( pFunc );
66177  if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
66178   || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
66179  ){
66180    return SQLITE_OK;
66181  }
66182
66183  if( pList ){
66184    apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
66185    if( apVal==0 ){
66186      rc = SQLITE_NOMEM;
66187      goto value_from_function_out;
66188    }
66189    for(i=0; i<nVal; i++){
66190      rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
66191      if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
66192    }
66193  }
66194
66195  pVal = valueNew(db, pCtx);
66196  if( pVal==0 ){
66197    rc = SQLITE_NOMEM;
66198    goto value_from_function_out;
66199  }
66200
66201  assert( pCtx->pParse->rc==SQLITE_OK );
66202  memset(&ctx, 0, sizeof(ctx));
66203  ctx.pOut = pVal;
66204  ctx.pFunc = pFunc;
66205  pFunc->xFunc(&ctx, nVal, apVal);
66206  if( ctx.isError ){
66207    rc = ctx.isError;
66208    sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
66209  }else{
66210    sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
66211    assert( rc==SQLITE_OK );
66212    rc = sqlite3VdbeChangeEncoding(pVal, enc);
66213    if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
66214      rc = SQLITE_TOOBIG;
66215      pCtx->pParse->nErr++;
66216    }
66217  }
66218  pCtx->pParse->rc = rc;
66219
66220 value_from_function_out:
66221  if( rc!=SQLITE_OK ){
66222    pVal = 0;
66223  }
66224  if( apVal ){
66225    for(i=0; i<nVal; i++){
66226      sqlite3ValueFree(apVal[i]);
66227    }
66228    sqlite3DbFree(db, apVal);
66229  }
66230
66231  *ppVal = pVal;
66232  return rc;
66233}
66234#else
66235# define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
66236#endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
66237
66238/*
66239** Extract a value from the supplied expression in the manner described
66240** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
66241** using valueNew().
66242**
66243** If pCtx is NULL and an error occurs after the sqlite3_value object
66244** has been allocated, it is freed before returning. Or, if pCtx is not
66245** NULL, it is assumed that the caller will free any allocated object
66246** in all cases.
66247*/
66248static int valueFromExpr(
66249  sqlite3 *db,                    /* The database connection */
66250  Expr *pExpr,                    /* The expression to evaluate */
66251  u8 enc,                         /* Encoding to use */
66252  u8 affinity,                    /* Affinity to use */
66253  sqlite3_value **ppVal,          /* Write the new value here */
66254  struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
66255){
66256  int op;
66257  char *zVal = 0;
66258  sqlite3_value *pVal = 0;
66259  int negInt = 1;
66260  const char *zNeg = "";
66261  int rc = SQLITE_OK;
66262
66263  if( !pExpr ){
66264    *ppVal = 0;
66265    return SQLITE_OK;
66266  }
66267  while( (op = pExpr->op)==TK_UPLUS ) pExpr = pExpr->pLeft;
66268  if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
66269
66270  /* Compressed expressions only appear when parsing the DEFAULT clause
66271  ** on a table column definition, and hence only when pCtx==0.  This
66272  ** check ensures that an EP_TokenOnly expression is never passed down
66273  ** into valueFromFunction(). */
66274  assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
66275
66276  if( op==TK_CAST ){
66277    u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
66278    rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
66279    testcase( rc!=SQLITE_OK );
66280    if( *ppVal ){
66281      sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
66282      sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
66283    }
66284    return rc;
66285  }
66286
66287  /* Handle negative integers in a single step.  This is needed in the
66288  ** case when the value is -9223372036854775808.
66289  */
66290  if( op==TK_UMINUS
66291   && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
66292    pExpr = pExpr->pLeft;
66293    op = pExpr->op;
66294    negInt = -1;
66295    zNeg = "-";
66296  }
66297
66298  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
66299    pVal = valueNew(db, pCtx);
66300    if( pVal==0 ) goto no_mem;
66301    if( ExprHasProperty(pExpr, EP_IntValue) ){
66302      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
66303    }else{
66304      zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
66305      if( zVal==0 ) goto no_mem;
66306      sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
66307    }
66308    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
66309      sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
66310    }else{
66311      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
66312    }
66313    if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
66314    if( enc!=SQLITE_UTF8 ){
66315      rc = sqlite3VdbeChangeEncoding(pVal, enc);
66316    }
66317  }else if( op==TK_UMINUS ) {
66318    /* This branch happens for multiple negative signs.  Ex: -(-5) */
66319    if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
66320     && pVal!=0
66321    ){
66322      sqlite3VdbeMemNumerify(pVal);
66323      if( pVal->flags & MEM_Real ){
66324        pVal->u.r = -pVal->u.r;
66325      }else if( pVal->u.i==SMALLEST_INT64 ){
66326        pVal->u.r = -(double)SMALLEST_INT64;
66327        MemSetTypeFlag(pVal, MEM_Real);
66328      }else{
66329        pVal->u.i = -pVal->u.i;
66330      }
66331      sqlite3ValueApplyAffinity(pVal, affinity, enc);
66332    }
66333  }else if( op==TK_NULL ){
66334    pVal = valueNew(db, pCtx);
66335    if( pVal==0 ) goto no_mem;
66336  }
66337#ifndef SQLITE_OMIT_BLOB_LITERAL
66338  else if( op==TK_BLOB ){
66339    int nVal;
66340    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
66341    assert( pExpr->u.zToken[1]=='\'' );
66342    pVal = valueNew(db, pCtx);
66343    if( !pVal ) goto no_mem;
66344    zVal = &pExpr->u.zToken[2];
66345    nVal = sqlite3Strlen30(zVal)-1;
66346    assert( zVal[nVal]=='\'' );
66347    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
66348                         0, SQLITE_DYNAMIC);
66349  }
66350#endif
66351
66352#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
66353  else if( op==TK_FUNCTION && pCtx!=0 ){
66354    rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
66355  }
66356#endif
66357
66358  *ppVal = pVal;
66359  return rc;
66360
66361no_mem:
66362  db->mallocFailed = 1;
66363  sqlite3DbFree(db, zVal);
66364  assert( *ppVal==0 );
66365#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
66366  if( pCtx==0 ) sqlite3ValueFree(pVal);
66367#else
66368  assert( pCtx==0 ); sqlite3ValueFree(pVal);
66369#endif
66370  return SQLITE_NOMEM;
66371}
66372
66373/*
66374** Create a new sqlite3_value object, containing the value of pExpr.
66375**
66376** This only works for very simple expressions that consist of one constant
66377** token (i.e. "5", "5.1", "'a string'"). If the expression can
66378** be converted directly into a value, then the value is allocated and
66379** a pointer written to *ppVal. The caller is responsible for deallocating
66380** the value by passing it to sqlite3ValueFree() later on. If the expression
66381** cannot be converted to a value, then *ppVal is set to NULL.
66382*/
66383SQLITE_PRIVATE int sqlite3ValueFromExpr(
66384  sqlite3 *db,              /* The database connection */
66385  Expr *pExpr,              /* The expression to evaluate */
66386  u8 enc,                   /* Encoding to use */
66387  u8 affinity,              /* Affinity to use */
66388  sqlite3_value **ppVal     /* Write the new value here */
66389){
66390  return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
66391}
66392
66393#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
66394/*
66395** The implementation of the sqlite_record() function. This function accepts
66396** a single argument of any type. The return value is a formatted database
66397** record (a blob) containing the argument value.
66398**
66399** This is used to convert the value stored in the 'sample' column of the
66400** sqlite_stat3 table to the record format SQLite uses internally.
66401*/
66402static void recordFunc(
66403  sqlite3_context *context,
66404  int argc,
66405  sqlite3_value **argv
66406){
66407  const int file_format = 1;
66408  int iSerial;                    /* Serial type */
66409  int nSerial;                    /* Bytes of space for iSerial as varint */
66410  int nVal;                       /* Bytes of space required for argv[0] */
66411  int nRet;
66412  sqlite3 *db;
66413  u8 *aRet;
66414
66415  UNUSED_PARAMETER( argc );
66416  iSerial = sqlite3VdbeSerialType(argv[0], file_format);
66417  nSerial = sqlite3VarintLen(iSerial);
66418  nVal = sqlite3VdbeSerialTypeLen(iSerial);
66419  db = sqlite3_context_db_handle(context);
66420
66421  nRet = 1 + nSerial + nVal;
66422  aRet = sqlite3DbMallocRaw(db, nRet);
66423  if( aRet==0 ){
66424    sqlite3_result_error_nomem(context);
66425  }else{
66426    aRet[0] = nSerial+1;
66427    putVarint32(&aRet[1], iSerial);
66428    sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
66429    sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
66430    sqlite3DbFree(db, aRet);
66431  }
66432}
66433
66434/*
66435** Register built-in functions used to help read ANALYZE data.
66436*/
66437SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
66438  static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
66439    FUNCTION(sqlite_record,   1, 0, 0, recordFunc),
66440  };
66441  int i;
66442  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
66443  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
66444  for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
66445    sqlite3FuncDefInsert(pHash, &aFunc[i]);
66446  }
66447}
66448
66449/*
66450** Attempt to extract a value from pExpr and use it to construct *ppVal.
66451**
66452** If pAlloc is not NULL, then an UnpackedRecord object is created for
66453** pAlloc if one does not exist and the new value is added to the
66454** UnpackedRecord object.
66455**
66456** A value is extracted in the following cases:
66457**
66458**  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
66459**
66460**  * The expression is a bound variable, and this is a reprepare, or
66461**
66462**  * The expression is a literal value.
66463**
66464** On success, *ppVal is made to point to the extracted value.  The caller
66465** is responsible for ensuring that the value is eventually freed.
66466*/
66467static int stat4ValueFromExpr(
66468  Parse *pParse,                  /* Parse context */
66469  Expr *pExpr,                    /* The expression to extract a value from */
66470  u8 affinity,                    /* Affinity to use */
66471  struct ValueNewStat4Ctx *pAlloc,/* How to allocate space.  Or NULL */
66472  sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
66473){
66474  int rc = SQLITE_OK;
66475  sqlite3_value *pVal = 0;
66476  sqlite3 *db = pParse->db;
66477
66478  /* Skip over any TK_COLLATE nodes */
66479  pExpr = sqlite3ExprSkipCollate(pExpr);
66480
66481  if( !pExpr ){
66482    pVal = valueNew(db, pAlloc);
66483    if( pVal ){
66484      sqlite3VdbeMemSetNull((Mem*)pVal);
66485    }
66486  }else if( pExpr->op==TK_VARIABLE
66487        || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
66488  ){
66489    Vdbe *v;
66490    int iBindVar = pExpr->iColumn;
66491    sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
66492    if( (v = pParse->pReprepare)!=0 ){
66493      pVal = valueNew(db, pAlloc);
66494      if( pVal ){
66495        rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
66496        if( rc==SQLITE_OK ){
66497          sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
66498        }
66499        pVal->db = pParse->db;
66500      }
66501    }
66502  }else{
66503    rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
66504  }
66505
66506  assert( pVal==0 || pVal->db==db );
66507  *ppVal = pVal;
66508  return rc;
66509}
66510
66511/*
66512** This function is used to allocate and populate UnpackedRecord
66513** structures intended to be compared against sample index keys stored
66514** in the sqlite_stat4 table.
66515**
66516** A single call to this function attempts to populates field iVal (leftmost
66517** is 0 etc.) of the unpacked record with a value extracted from expression
66518** pExpr. Extraction of values is possible if:
66519**
66520**  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
66521**
66522**  * The expression is a bound variable, and this is a reprepare, or
66523**
66524**  * The sqlite3ValueFromExpr() function is able to extract a value
66525**    from the expression (i.e. the expression is a literal value).
66526**
66527** If a value can be extracted, the affinity passed as the 5th argument
66528** is applied to it before it is copied into the UnpackedRecord. Output
66529** parameter *pbOk is set to true if a value is extracted, or false
66530** otherwise.
66531**
66532** When this function is called, *ppRec must either point to an object
66533** allocated by an earlier call to this function, or must be NULL. If it
66534** is NULL and a value can be successfully extracted, a new UnpackedRecord
66535** is allocated (and *ppRec set to point to it) before returning.
66536**
66537** Unless an error is encountered, SQLITE_OK is returned. It is not an
66538** error if a value cannot be extracted from pExpr. If an error does
66539** occur, an SQLite error code is returned.
66540*/
66541SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
66542  Parse *pParse,                  /* Parse context */
66543  Index *pIdx,                    /* Index being probed */
66544  UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
66545  Expr *pExpr,                    /* The expression to extract a value from */
66546  u8 affinity,                    /* Affinity to use */
66547  int iVal,                       /* Array element to populate */
66548  int *pbOk                       /* OUT: True if value was extracted */
66549){
66550  int rc;
66551  sqlite3_value *pVal = 0;
66552  struct ValueNewStat4Ctx alloc;
66553
66554  alloc.pParse = pParse;
66555  alloc.pIdx = pIdx;
66556  alloc.ppRec = ppRec;
66557  alloc.iVal = iVal;
66558
66559  rc = stat4ValueFromExpr(pParse, pExpr, affinity, &alloc, &pVal);
66560  assert( pVal==0 || pVal->db==pParse->db );
66561  *pbOk = (pVal!=0);
66562  return rc;
66563}
66564
66565/*
66566** Attempt to extract a value from expression pExpr using the methods
66567** as described for sqlite3Stat4ProbeSetValue() above.
66568**
66569** If successful, set *ppVal to point to a new value object and return
66570** SQLITE_OK. If no value can be extracted, but no other error occurs
66571** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
66572** does occur, return an SQLite error code. The final value of *ppVal
66573** is undefined in this case.
66574*/
66575SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
66576  Parse *pParse,                  /* Parse context */
66577  Expr *pExpr,                    /* The expression to extract a value from */
66578  u8 affinity,                    /* Affinity to use */
66579  sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
66580){
66581  return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
66582}
66583
66584/*
66585** Extract the iCol-th column from the nRec-byte record in pRec.  Write
66586** the column value into *ppVal.  If *ppVal is initially NULL then a new
66587** sqlite3_value object is allocated.
66588**
66589** If *ppVal is initially NULL then the caller is responsible for
66590** ensuring that the value written into *ppVal is eventually freed.
66591*/
66592SQLITE_PRIVATE int sqlite3Stat4Column(
66593  sqlite3 *db,                    /* Database handle */
66594  const void *pRec,               /* Pointer to buffer containing record */
66595  int nRec,                       /* Size of buffer pRec in bytes */
66596  int iCol,                       /* Column to extract */
66597  sqlite3_value **ppVal           /* OUT: Extracted value */
66598){
66599  u32 t;                          /* a column type code */
66600  int nHdr;                       /* Size of the header in the record */
66601  int iHdr;                       /* Next unread header byte */
66602  int iField;                     /* Next unread data byte */
66603  int szField;                    /* Size of the current data field */
66604  int i;                          /* Column index */
66605  u8 *a = (u8*)pRec;              /* Typecast byte array */
66606  Mem *pMem = *ppVal;             /* Write result into this Mem object */
66607
66608  assert( iCol>0 );
66609  iHdr = getVarint32(a, nHdr);
66610  if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
66611  iField = nHdr;
66612  for(i=0; i<=iCol; i++){
66613    iHdr += getVarint32(&a[iHdr], t);
66614    testcase( iHdr==nHdr );
66615    testcase( iHdr==nHdr+1 );
66616    if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
66617    szField = sqlite3VdbeSerialTypeLen(t);
66618    iField += szField;
66619  }
66620  testcase( iField==nRec );
66621  testcase( iField==nRec+1 );
66622  if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
66623  if( pMem==0 ){
66624    pMem = *ppVal = sqlite3ValueNew(db);
66625    if( pMem==0 ) return SQLITE_NOMEM;
66626  }
66627  sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
66628  pMem->enc = ENC(db);
66629  return SQLITE_OK;
66630}
66631
66632/*
66633** Unless it is NULL, the argument must be an UnpackedRecord object returned
66634** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
66635** the object.
66636*/
66637SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
66638  if( pRec ){
66639    int i;
66640    int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
66641    Mem *aMem = pRec->aMem;
66642    sqlite3 *db = aMem[0].db;
66643    for(i=0; i<nCol; i++){
66644      sqlite3VdbeMemRelease(&aMem[i]);
66645    }
66646    sqlite3KeyInfoUnref(pRec->pKeyInfo);
66647    sqlite3DbFree(db, pRec);
66648  }
66649}
66650#endif /* ifdef SQLITE_ENABLE_STAT4 */
66651
66652/*
66653** Change the string value of an sqlite3_value object
66654*/
66655SQLITE_PRIVATE void sqlite3ValueSetStr(
66656  sqlite3_value *v,     /* Value to be set */
66657  int n,                /* Length of string z */
66658  const void *z,        /* Text of the new string */
66659  u8 enc,               /* Encoding to use */
66660  void (*xDel)(void*)   /* Destructor for the string */
66661){
66662  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
66663}
66664
66665/*
66666** Free an sqlite3_value object
66667*/
66668SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
66669  if( !v ) return;
66670  sqlite3VdbeMemRelease((Mem *)v);
66671  sqlite3DbFree(((Mem*)v)->db, v);
66672}
66673
66674/*
66675** The sqlite3ValueBytes() routine returns the number of bytes in the
66676** sqlite3_value object assuming that it uses the encoding "enc".
66677** The valueBytes() routine is a helper function.
66678*/
66679static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
66680  return valueToText(pVal, enc)!=0 ? pVal->n : 0;
66681}
66682SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
66683  Mem *p = (Mem*)pVal;
66684  assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
66685  if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
66686    return p->n;
66687  }
66688  if( (p->flags & MEM_Blob)!=0 ){
66689    if( p->flags & MEM_Zero ){
66690      return p->n + p->u.nZero;
66691    }else{
66692      return p->n;
66693    }
66694  }
66695  if( p->flags & MEM_Null ) return 0;
66696  return valueBytes(pVal, enc);
66697}
66698
66699/************** End of vdbemem.c *********************************************/
66700/************** Begin file vdbeaux.c *****************************************/
66701/*
66702** 2003 September 6
66703**
66704** The author disclaims copyright to this source code.  In place of
66705** a legal notice, here is a blessing:
66706**
66707**    May you do good and not evil.
66708**    May you find forgiveness for yourself and forgive others.
66709**    May you share freely, never taking more than you give.
66710**
66711*************************************************************************
66712** This file contains code used for creating, destroying, and populating
66713** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
66714*/
66715/* #include "sqliteInt.h" */
66716/* #include "vdbeInt.h" */
66717
66718/*
66719** Create a new virtual database engine.
66720*/
66721SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
66722  sqlite3 *db = pParse->db;
66723  Vdbe *p;
66724  p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
66725  if( p==0 ) return 0;
66726  p->db = db;
66727  if( db->pVdbe ){
66728    db->pVdbe->pPrev = p;
66729  }
66730  p->pNext = db->pVdbe;
66731  p->pPrev = 0;
66732  db->pVdbe = p;
66733  p->magic = VDBE_MAGIC_INIT;
66734  p->pParse = pParse;
66735  assert( pParse->aLabel==0 );
66736  assert( pParse->nLabel==0 );
66737  assert( pParse->nOpAlloc==0 );
66738  return p;
66739}
66740
66741/*
66742** Change the error string stored in Vdbe.zErrMsg
66743*/
66744SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
66745  va_list ap;
66746  sqlite3DbFree(p->db, p->zErrMsg);
66747  va_start(ap, zFormat);
66748  p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
66749  va_end(ap);
66750}
66751
66752/*
66753** Remember the SQL string for a prepared statement.
66754*/
66755SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
66756  assert( isPrepareV2==1 || isPrepareV2==0 );
66757  if( p==0 ) return;
66758#if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
66759  if( !isPrepareV2 ) return;
66760#endif
66761  assert( p->zSql==0 );
66762  p->zSql = sqlite3DbStrNDup(p->db, z, n);
66763  p->isPrepareV2 = (u8)isPrepareV2;
66764}
66765
66766/*
66767** Return the SQL associated with a prepared statement
66768*/
66769SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt){
66770  Vdbe *p = (Vdbe *)pStmt;
66771  return p ? p->zSql : 0;
66772}
66773
66774/*
66775** Swap all content between two VDBE structures.
66776*/
66777SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
66778  Vdbe tmp, *pTmp;
66779  char *zTmp;
66780  tmp = *pA;
66781  *pA = *pB;
66782  *pB = tmp;
66783  pTmp = pA->pNext;
66784  pA->pNext = pB->pNext;
66785  pB->pNext = pTmp;
66786  pTmp = pA->pPrev;
66787  pA->pPrev = pB->pPrev;
66788  pB->pPrev = pTmp;
66789  zTmp = pA->zSql;
66790  pA->zSql = pB->zSql;
66791  pB->zSql = zTmp;
66792  pB->isPrepareV2 = pA->isPrepareV2;
66793}
66794
66795/*
66796** Resize the Vdbe.aOp array so that it is at least nOp elements larger
66797** than its current size. nOp is guaranteed to be less than or equal
66798** to 1024/sizeof(Op).
66799**
66800** If an out-of-memory error occurs while resizing the array, return
66801** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
66802** unchanged (this is so that any opcodes already allocated can be
66803** correctly deallocated along with the rest of the Vdbe).
66804*/
66805static int growOpArray(Vdbe *v, int nOp){
66806  VdbeOp *pNew;
66807  Parse *p = v->pParse;
66808
66809  /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
66810  ** more frequent reallocs and hence provide more opportunities for
66811  ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used
66812  ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array
66813  ** by the minimum* amount required until the size reaches 512.  Normal
66814  ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
66815  ** size of the op array or add 1KB of space, whichever is smaller. */
66816#ifdef SQLITE_TEST_REALLOC_STRESS
66817  int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
66818#else
66819  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
66820  UNUSED_PARAMETER(nOp);
66821#endif
66822
66823  assert( nOp<=(1024/sizeof(Op)) );
66824  assert( nNew>=(p->nOpAlloc+nOp) );
66825  pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
66826  if( pNew ){
66827    p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
66828    v->aOp = pNew;
66829  }
66830  return (pNew ? SQLITE_OK : SQLITE_NOMEM);
66831}
66832
66833#ifdef SQLITE_DEBUG
66834/* This routine is just a convenient place to set a breakpoint that will
66835** fire after each opcode is inserted and displayed using
66836** "PRAGMA vdbe_addoptrace=on".
66837*/
66838static void test_addop_breakpoint(void){
66839  static int n = 0;
66840  n++;
66841}
66842#endif
66843
66844/*
66845** Add a new instruction to the list of instructions current in the
66846** VDBE.  Return the address of the new instruction.
66847**
66848** Parameters:
66849**
66850**    p               Pointer to the VDBE
66851**
66852**    op              The opcode for this instruction
66853**
66854**    p1, p2, p3      Operands
66855**
66856** Use the sqlite3VdbeResolveLabel() function to fix an address and
66857** the sqlite3VdbeChangeP4() function to change the value of the P4
66858** operand.
66859*/
66860SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
66861  int i;
66862  VdbeOp *pOp;
66863
66864  i = p->nOp;
66865  assert( p->magic==VDBE_MAGIC_INIT );
66866  assert( op>0 && op<0xff );
66867  if( p->pParse->nOpAlloc<=i ){
66868    if( growOpArray(p, 1) ){
66869      return 1;
66870    }
66871  }
66872  p->nOp++;
66873  pOp = &p->aOp[i];
66874  pOp->opcode = (u8)op;
66875  pOp->p5 = 0;
66876  pOp->p1 = p1;
66877  pOp->p2 = p2;
66878  pOp->p3 = p3;
66879  pOp->p4.p = 0;
66880  pOp->p4type = P4_NOTUSED;
66881#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
66882  pOp->zComment = 0;
66883#endif
66884#ifdef SQLITE_DEBUG
66885  if( p->db->flags & SQLITE_VdbeAddopTrace ){
66886    int jj, kk;
66887    Parse *pParse = p->pParse;
66888    for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
66889      struct yColCache *x = pParse->aColCache + jj;
66890      if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
66891      printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
66892      kk++;
66893    }
66894    if( kk ) printf("\n");
66895    sqlite3VdbePrintOp(0, i, &p->aOp[i]);
66896    test_addop_breakpoint();
66897  }
66898#endif
66899#ifdef VDBE_PROFILE
66900  pOp->cycles = 0;
66901  pOp->cnt = 0;
66902#endif
66903#ifdef SQLITE_VDBE_COVERAGE
66904  pOp->iSrcLine = 0;
66905#endif
66906  return i;
66907}
66908SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
66909  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
66910}
66911SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
66912  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
66913}
66914SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
66915  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
66916}
66917
66918/* Generate code for an unconditional jump to instruction iDest
66919*/
66920SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
66921  return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
66922}
66923
66924/* Generate code to cause the string zStr to be loaded into
66925** register iDest
66926*/
66927SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
66928  return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
66929}
66930
66931/*
66932** Generate code that initializes multiple registers to string or integer
66933** constants.  The registers begin with iDest and increase consecutively.
66934** One register is initialized for each characgter in zTypes[].  For each
66935** "s" character in zTypes[], the register is a string if the argument is
66936** not NULL, or OP_Null if the value is a null pointer.  For each "i" character
66937** in zTypes[], the register is initialized to an integer.
66938*/
66939SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
66940  va_list ap;
66941  int i;
66942  char c;
66943  va_start(ap, zTypes);
66944  for(i=0; (c = zTypes[i])!=0; i++){
66945    if( c=='s' ){
66946      const char *z = va_arg(ap, const char*);
66947      int addr = sqlite3VdbeAddOp2(p, z==0 ? OP_Null : OP_String8, 0, iDest++);
66948      if( z ) sqlite3VdbeChangeP4(p, addr, z, 0);
66949    }else{
66950      assert( c=='i' );
66951      sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest++);
66952    }
66953  }
66954  va_end(ap);
66955}
66956
66957/*
66958** Add an opcode that includes the p4 value as a pointer.
66959*/
66960SQLITE_PRIVATE int sqlite3VdbeAddOp4(
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 char *zP4,    /* The P4 operand */
66967  int p4type          /* P4 operand type */
66968){
66969  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
66970  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
66971  return addr;
66972}
66973
66974/*
66975** Add an opcode that includes the p4 value with a P4_INT64 or
66976** P4_REAL type.
66977*/
66978SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
66979  Vdbe *p,            /* Add the opcode to this VM */
66980  int op,             /* The new opcode */
66981  int p1,             /* The P1 operand */
66982  int p2,             /* The P2 operand */
66983  int p3,             /* The P3 operand */
66984  const u8 *zP4,      /* The P4 operand */
66985  int p4type          /* P4 operand type */
66986){
66987  char *p4copy = sqlite3DbMallocRaw(sqlite3VdbeDb(p), 8);
66988  if( p4copy ) memcpy(p4copy, zP4, 8);
66989  return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
66990}
66991
66992/*
66993** Add an OP_ParseSchema opcode.  This routine is broken out from
66994** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
66995** as having been used.
66996**
66997** The zWhere string must have been obtained from sqlite3_malloc().
66998** This routine will take ownership of the allocated memory.
66999*/
67000SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
67001  int j;
67002  int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
67003  sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
67004  for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
67005}
67006
67007/*
67008** Add an opcode that includes the p4 value as an integer.
67009*/
67010SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
67011  Vdbe *p,            /* Add the opcode to this VM */
67012  int op,             /* The new opcode */
67013  int p1,             /* The P1 operand */
67014  int p2,             /* The P2 operand */
67015  int p3,             /* The P3 operand */
67016  int p4              /* The P4 operand as an integer */
67017){
67018  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
67019  sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
67020  return addr;
67021}
67022
67023/*
67024** Create a new symbolic label for an instruction that has yet to be
67025** coded.  The symbolic label is really just a negative number.  The
67026** label can be used as the P2 value of an operation.  Later, when
67027** the label is resolved to a specific address, the VDBE will scan
67028** through its operation list and change all values of P2 which match
67029** the label into the resolved address.
67030**
67031** The VDBE knows that a P2 value is a label because labels are
67032** always negative and P2 values are suppose to be non-negative.
67033** Hence, a negative P2 value is a label that has yet to be resolved.
67034**
67035** Zero is returned if a malloc() fails.
67036*/
67037SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
67038  Parse *p = v->pParse;
67039  int i = p->nLabel++;
67040  assert( v->magic==VDBE_MAGIC_INIT );
67041  if( (i & (i-1))==0 ){
67042    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
67043                                       (i*2+1)*sizeof(p->aLabel[0]));
67044  }
67045  if( p->aLabel ){
67046    p->aLabel[i] = -1;
67047  }
67048  return -1-i;
67049}
67050
67051/*
67052** Resolve label "x" to be the address of the next instruction to
67053** be inserted.  The parameter "x" must have been obtained from
67054** a prior call to sqlite3VdbeMakeLabel().
67055*/
67056SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
67057  Parse *p = v->pParse;
67058  int j = -1-x;
67059  assert( v->magic==VDBE_MAGIC_INIT );
67060  assert( j<p->nLabel );
67061  assert( j>=0 );
67062  if( p->aLabel ){
67063    p->aLabel[j] = v->nOp;
67064  }
67065  p->iFixedOp = v->nOp - 1;
67066}
67067
67068/*
67069** Mark the VDBE as one that can only be run one time.
67070*/
67071SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
67072  p->runOnlyOnce = 1;
67073}
67074
67075#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
67076
67077/*
67078** The following type and function are used to iterate through all opcodes
67079** in a Vdbe main program and each of the sub-programs (triggers) it may
67080** invoke directly or indirectly. It should be used as follows:
67081**
67082**   Op *pOp;
67083**   VdbeOpIter sIter;
67084**
67085**   memset(&sIter, 0, sizeof(sIter));
67086**   sIter.v = v;                            // v is of type Vdbe*
67087**   while( (pOp = opIterNext(&sIter)) ){
67088**     // Do something with pOp
67089**   }
67090**   sqlite3DbFree(v->db, sIter.apSub);
67091**
67092*/
67093typedef struct VdbeOpIter VdbeOpIter;
67094struct VdbeOpIter {
67095  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
67096  SubProgram **apSub;        /* Array of subprograms */
67097  int nSub;                  /* Number of entries in apSub */
67098  int iAddr;                 /* Address of next instruction to return */
67099  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
67100};
67101static Op *opIterNext(VdbeOpIter *p){
67102  Vdbe *v = p->v;
67103  Op *pRet = 0;
67104  Op *aOp;
67105  int nOp;
67106
67107  if( p->iSub<=p->nSub ){
67108
67109    if( p->iSub==0 ){
67110      aOp = v->aOp;
67111      nOp = v->nOp;
67112    }else{
67113      aOp = p->apSub[p->iSub-1]->aOp;
67114      nOp = p->apSub[p->iSub-1]->nOp;
67115    }
67116    assert( p->iAddr<nOp );
67117
67118    pRet = &aOp[p->iAddr];
67119    p->iAddr++;
67120    if( p->iAddr==nOp ){
67121      p->iSub++;
67122      p->iAddr = 0;
67123    }
67124
67125    if( pRet->p4type==P4_SUBPROGRAM ){
67126      int nByte = (p->nSub+1)*sizeof(SubProgram*);
67127      int j;
67128      for(j=0; j<p->nSub; j++){
67129        if( p->apSub[j]==pRet->p4.pProgram ) break;
67130      }
67131      if( j==p->nSub ){
67132        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
67133        if( !p->apSub ){
67134          pRet = 0;
67135        }else{
67136          p->apSub[p->nSub++] = pRet->p4.pProgram;
67137        }
67138      }
67139    }
67140  }
67141
67142  return pRet;
67143}
67144
67145/*
67146** Check if the program stored in the VM associated with pParse may
67147** throw an ABORT exception (causing the statement, but not entire transaction
67148** to be rolled back). This condition is true if the main program or any
67149** sub-programs contains any of the following:
67150**
67151**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
67152**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
67153**   *  OP_Destroy
67154**   *  OP_VUpdate
67155**   *  OP_VRename
67156**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
67157**   *  OP_CreateTable and OP_InitCoroutine (for CREATE TABLE AS SELECT ...)
67158**
67159** Then check that the value of Parse.mayAbort is true if an
67160** ABORT may be thrown, or false otherwise. Return true if it does
67161** match, or false otherwise. This function is intended to be used as
67162** part of an assert statement in the compiler. Similar to:
67163**
67164**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
67165*/
67166SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
67167  int hasAbort = 0;
67168  int hasFkCounter = 0;
67169  int hasCreateTable = 0;
67170  int hasInitCoroutine = 0;
67171  Op *pOp;
67172  VdbeOpIter sIter;
67173  memset(&sIter, 0, sizeof(sIter));
67174  sIter.v = v;
67175
67176  while( (pOp = opIterNext(&sIter))!=0 ){
67177    int opcode = pOp->opcode;
67178    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
67179     || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
67180      && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
67181    ){
67182      hasAbort = 1;
67183      break;
67184    }
67185    if( opcode==OP_CreateTable ) hasCreateTable = 1;
67186    if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
67187#ifndef SQLITE_OMIT_FOREIGN_KEY
67188    if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
67189      hasFkCounter = 1;
67190    }
67191#endif
67192  }
67193  sqlite3DbFree(v->db, sIter.apSub);
67194
67195  /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
67196  ** If malloc failed, then the while() loop above may not have iterated
67197  ** through all opcodes and hasAbort may be set incorrectly. Return
67198  ** true for this case to prevent the assert() in the callers frame
67199  ** from failing.  */
67200  return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
67201              || (hasCreateTable && hasInitCoroutine) );
67202}
67203#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
67204
67205/*
67206** This routine is called after all opcodes have been inserted.  It loops
67207** through all the opcodes and fixes up some details.
67208**
67209** (1) For each jump instruction with a negative P2 value (a label)
67210**     resolve the P2 value to an actual address.
67211**
67212** (2) Compute the maximum number of arguments used by any SQL function
67213**     and store that value in *pMaxFuncArgs.
67214**
67215** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
67216**     indicate what the prepared statement actually does.
67217**
67218** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
67219**
67220** (5) Reclaim the memory allocated for storing labels.
67221*/
67222static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
67223  int i;
67224  int nMaxArgs = *pMaxFuncArgs;
67225  Op *pOp;
67226  Parse *pParse = p->pParse;
67227  int *aLabel = pParse->aLabel;
67228  p->readOnly = 1;
67229  p->bIsReader = 0;
67230  for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
67231    u8 opcode = pOp->opcode;
67232
67233    /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
67234    ** cases from this switch! */
67235    switch( opcode ){
67236      case OP_Transaction: {
67237        if( pOp->p2!=0 ) p->readOnly = 0;
67238        /* fall thru */
67239      }
67240      case OP_AutoCommit:
67241      case OP_Savepoint: {
67242        p->bIsReader = 1;
67243        break;
67244      }
67245#ifndef SQLITE_OMIT_WAL
67246      case OP_Checkpoint:
67247#endif
67248      case OP_Vacuum:
67249      case OP_JournalMode: {
67250        p->readOnly = 0;
67251        p->bIsReader = 1;
67252        break;
67253      }
67254#ifndef SQLITE_OMIT_VIRTUALTABLE
67255      case OP_VUpdate: {
67256        if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
67257        break;
67258      }
67259      case OP_VFilter: {
67260        int n;
67261        assert( p->nOp - i >= 3 );
67262        assert( pOp[-1].opcode==OP_Integer );
67263        n = pOp[-1].p1;
67264        if( n>nMaxArgs ) nMaxArgs = n;
67265        break;
67266      }
67267#endif
67268      case OP_Next:
67269      case OP_NextIfOpen:
67270      case OP_SorterNext: {
67271        pOp->p4.xAdvance = sqlite3BtreeNext;
67272        pOp->p4type = P4_ADVANCE;
67273        break;
67274      }
67275      case OP_Prev:
67276      case OP_PrevIfOpen: {
67277        pOp->p4.xAdvance = sqlite3BtreePrevious;
67278        pOp->p4type = P4_ADVANCE;
67279        break;
67280      }
67281    }
67282
67283    pOp->opflags = sqlite3OpcodeProperty[opcode];
67284    if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
67285      assert( -1-pOp->p2<pParse->nLabel );
67286      pOp->p2 = aLabel[-1-pOp->p2];
67287    }
67288  }
67289  sqlite3DbFree(p->db, pParse->aLabel);
67290  pParse->aLabel = 0;
67291  pParse->nLabel = 0;
67292  *pMaxFuncArgs = nMaxArgs;
67293  assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
67294}
67295
67296/*
67297** Return the address of the next instruction to be inserted.
67298*/
67299SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
67300  assert( p->magic==VDBE_MAGIC_INIT );
67301  return p->nOp;
67302}
67303
67304/*
67305** This function returns a pointer to the array of opcodes associated with
67306** the Vdbe passed as the first argument. It is the callers responsibility
67307** to arrange for the returned array to be eventually freed using the
67308** vdbeFreeOpArray() function.
67309**
67310** Before returning, *pnOp is set to the number of entries in the returned
67311** array. Also, *pnMaxArg is set to the larger of its current value and
67312** the number of entries in the Vdbe.apArg[] array required to execute the
67313** returned program.
67314*/
67315SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
67316  VdbeOp *aOp = p->aOp;
67317  assert( aOp && !p->db->mallocFailed );
67318
67319  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
67320  assert( DbMaskAllZero(p->btreeMask) );
67321
67322  resolveP2Values(p, pnMaxArg);
67323  *pnOp = p->nOp;
67324  p->aOp = 0;
67325  return aOp;
67326}
67327
67328/*
67329** Add a whole list of operations to the operation stack.  Return the
67330** address of the first operation added.
67331*/
67332SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
67333  int addr, i;
67334  VdbeOp *pOut;
67335  assert( nOp>0 );
67336  assert( p->magic==VDBE_MAGIC_INIT );
67337  if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
67338    return 0;
67339  }
67340  addr = p->nOp;
67341  pOut = &p->aOp[addr];
67342  for(i=0; i<nOp; i++, aOp++, pOut++){
67343    int p2 = aOp->p2;
67344    pOut->opcode = aOp->opcode;
67345    pOut->p1 = aOp->p1;
67346    if( p2<0 ){
67347      assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP );
67348      pOut->p2 = addr + ADDR(p2);
67349    }else{
67350      pOut->p2 = p2;
67351    }
67352    pOut->p3 = aOp->p3;
67353    pOut->p4type = P4_NOTUSED;
67354    pOut->p4.p = 0;
67355    pOut->p5 = 0;
67356#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
67357    pOut->zComment = 0;
67358#endif
67359#ifdef SQLITE_VDBE_COVERAGE
67360    pOut->iSrcLine = iLineno+i;
67361#else
67362    (void)iLineno;
67363#endif
67364#ifdef SQLITE_DEBUG
67365    if( p->db->flags & SQLITE_VdbeAddopTrace ){
67366      sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
67367    }
67368#endif
67369  }
67370  p->nOp += nOp;
67371  return addr;
67372}
67373
67374#if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
67375/*
67376** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
67377*/
67378SQLITE_PRIVATE void sqlite3VdbeScanStatus(
67379  Vdbe *p,                        /* VM to add scanstatus() to */
67380  int addrExplain,                /* Address of OP_Explain (or 0) */
67381  int addrLoop,                   /* Address of loop counter */
67382  int addrVisit,                  /* Address of rows visited counter */
67383  LogEst nEst,                    /* Estimated number of output rows */
67384  const char *zName               /* Name of table or index being scanned */
67385){
67386  int nByte = (p->nScan+1) * sizeof(ScanStatus);
67387  ScanStatus *aNew;
67388  aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
67389  if( aNew ){
67390    ScanStatus *pNew = &aNew[p->nScan++];
67391    pNew->addrExplain = addrExplain;
67392    pNew->addrLoop = addrLoop;
67393    pNew->addrVisit = addrVisit;
67394    pNew->nEst = nEst;
67395    pNew->zName = sqlite3DbStrDup(p->db, zName);
67396    p->aScan = aNew;
67397  }
67398}
67399#endif
67400
67401
67402/*
67403** Change the value of the opcode, or P1, P2, P3, or P5 operands
67404** for a specific instruction.
67405*/
67406SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
67407  sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
67408}
67409SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
67410  sqlite3VdbeGetOp(p,addr)->p1 = val;
67411}
67412SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
67413  sqlite3VdbeGetOp(p,addr)->p2 = val;
67414}
67415SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
67416  sqlite3VdbeGetOp(p,addr)->p3 = val;
67417}
67418SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 p5){
67419  sqlite3VdbeGetOp(p,-1)->p5 = p5;
67420}
67421
67422/*
67423** Change the P2 operand of instruction addr so that it points to
67424** the address of the next instruction to be coded.
67425*/
67426SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
67427  p->pParse->iFixedOp = p->nOp - 1;
67428  sqlite3VdbeChangeP2(p, addr, p->nOp);
67429}
67430
67431
67432/*
67433** If the input FuncDef structure is ephemeral, then free it.  If
67434** the FuncDef is not ephermal, then do nothing.
67435*/
67436static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
67437  if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
67438    sqlite3DbFree(db, pDef);
67439  }
67440}
67441
67442static void vdbeFreeOpArray(sqlite3 *, Op *, int);
67443
67444/*
67445** Delete a P4 value if necessary.
67446*/
67447static void freeP4(sqlite3 *db, int p4type, void *p4){
67448  if( p4 ){
67449    assert( db );
67450    switch( p4type ){
67451      case P4_FUNCCTX: {
67452        freeEphemeralFunction(db, ((sqlite3_context*)p4)->pFunc);
67453        /* Fall through into the next case */
67454      }
67455      case P4_REAL:
67456      case P4_INT64:
67457      case P4_DYNAMIC:
67458      case P4_INTARRAY: {
67459        sqlite3DbFree(db, p4);
67460        break;
67461      }
67462      case P4_KEYINFO: {
67463        if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
67464        break;
67465      }
67466      case P4_MPRINTF: {
67467        if( db->pnBytesFreed==0 ) sqlite3_free(p4);
67468        break;
67469      }
67470      case P4_FUNCDEF: {
67471        freeEphemeralFunction(db, (FuncDef*)p4);
67472        break;
67473      }
67474      case P4_MEM: {
67475        if( db->pnBytesFreed==0 ){
67476          sqlite3ValueFree((sqlite3_value*)p4);
67477        }else{
67478          Mem *p = (Mem*)p4;
67479          if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
67480          sqlite3DbFree(db, p);
67481        }
67482        break;
67483      }
67484      case P4_VTAB : {
67485        if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
67486        break;
67487      }
67488    }
67489  }
67490}
67491
67492/*
67493** Free the space allocated for aOp and any p4 values allocated for the
67494** opcodes contained within. If aOp is not NULL it is assumed to contain
67495** nOp entries.
67496*/
67497static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
67498  if( aOp ){
67499    Op *pOp;
67500    for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
67501      freeP4(db, pOp->p4type, pOp->p4.p);
67502#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
67503      sqlite3DbFree(db, pOp->zComment);
67504#endif
67505    }
67506  }
67507  sqlite3DbFree(db, aOp);
67508}
67509
67510/*
67511** Link the SubProgram object passed as the second argument into the linked
67512** list at Vdbe.pSubProgram. This list is used to delete all sub-program
67513** objects when the VM is no longer required.
67514*/
67515SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
67516  p->pNext = pVdbe->pProgram;
67517  pVdbe->pProgram = p;
67518}
67519
67520/*
67521** Change the opcode at addr into OP_Noop
67522*/
67523SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
67524  if( addr<p->nOp ){
67525    VdbeOp *pOp = &p->aOp[addr];
67526    sqlite3 *db = p->db;
67527    freeP4(db, pOp->p4type, pOp->p4.p);
67528    memset(pOp, 0, sizeof(pOp[0]));
67529    pOp->opcode = OP_Noop;
67530    if( addr==p->nOp-1 ) p->nOp--;
67531  }
67532}
67533
67534/*
67535** If the last opcode is "op" and it is not a jump destination,
67536** then remove it.  Return true if and only if an opcode was removed.
67537*/
67538SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
67539  if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
67540    sqlite3VdbeChangeToNoop(p, p->nOp-1);
67541    return 1;
67542  }else{
67543    return 0;
67544  }
67545}
67546
67547/*
67548** Change the value of the P4 operand for a specific instruction.
67549** This routine is useful when a large program is loaded from a
67550** static array using sqlite3VdbeAddOpList but we want to make a
67551** few minor changes to the program.
67552**
67553** If n>=0 then the P4 operand is dynamic, meaning that a copy of
67554** the string is made into memory obtained from sqlite3_malloc().
67555** A value of n==0 means copy bytes of zP4 up to and including the
67556** first null byte.  If n>0 then copy n+1 bytes of zP4.
67557**
67558** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
67559** to a string or structure that is guaranteed to exist for the lifetime of
67560** the Vdbe. In these cases we can just copy the pointer.
67561**
67562** If addr<0 then change P4 on the most recently inserted instruction.
67563*/
67564SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
67565  Op *pOp;
67566  sqlite3 *db;
67567  assert( p!=0 );
67568  db = p->db;
67569  assert( p->magic==VDBE_MAGIC_INIT );
67570  if( p->aOp==0 || db->mallocFailed ){
67571    if( n!=P4_VTAB ){
67572      freeP4(db, n, (void*)*(char**)&zP4);
67573    }
67574    return;
67575  }
67576  assert( p->nOp>0 );
67577  assert( addr<p->nOp );
67578  if( addr<0 ){
67579    addr = p->nOp - 1;
67580  }
67581  pOp = &p->aOp[addr];
67582  assert( pOp->p4type==P4_NOTUSED
67583       || pOp->p4type==P4_INT32
67584       || pOp->p4type==P4_KEYINFO );
67585  freeP4(db, pOp->p4type, pOp->p4.p);
67586  pOp->p4.p = 0;
67587  if( n==P4_INT32 ){
67588    /* Note: this cast is safe, because the origin data point was an int
67589    ** that was cast to a (const char *). */
67590    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
67591    pOp->p4type = P4_INT32;
67592  }else if( zP4==0 ){
67593    pOp->p4.p = 0;
67594    pOp->p4type = P4_NOTUSED;
67595  }else if( n==P4_KEYINFO ){
67596    pOp->p4.p = (void*)zP4;
67597    pOp->p4type = P4_KEYINFO;
67598  }else if( n==P4_VTAB ){
67599    pOp->p4.p = (void*)zP4;
67600    pOp->p4type = P4_VTAB;
67601    sqlite3VtabLock((VTable *)zP4);
67602    assert( ((VTable *)zP4)->db==p->db );
67603  }else if( n<0 ){
67604    pOp->p4.p = (void*)zP4;
67605    pOp->p4type = (signed char)n;
67606  }else{
67607    if( n==0 ) n = sqlite3Strlen30(zP4);
67608    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
67609    pOp->p4type = P4_DYNAMIC;
67610  }
67611}
67612
67613/*
67614** Set the P4 on the most recently added opcode to the KeyInfo for the
67615** index given.
67616*/
67617SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
67618  Vdbe *v = pParse->pVdbe;
67619  assert( v!=0 );
67620  assert( pIdx!=0 );
67621  sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
67622                      P4_KEYINFO);
67623}
67624
67625#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
67626/*
67627** Change the comment on the most recently coded instruction.  Or
67628** insert a No-op and add the comment to that new instruction.  This
67629** makes the code easier to read during debugging.  None of this happens
67630** in a production build.
67631*/
67632static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
67633  assert( p->nOp>0 || p->aOp==0 );
67634  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
67635  if( p->nOp ){
67636    assert( p->aOp );
67637    sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
67638    p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
67639  }
67640}
67641SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
67642  va_list ap;
67643  if( p ){
67644    va_start(ap, zFormat);
67645    vdbeVComment(p, zFormat, ap);
67646    va_end(ap);
67647  }
67648}
67649SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
67650  va_list ap;
67651  if( p ){
67652    sqlite3VdbeAddOp0(p, OP_Noop);
67653    va_start(ap, zFormat);
67654    vdbeVComment(p, zFormat, ap);
67655    va_end(ap);
67656  }
67657}
67658#endif  /* NDEBUG */
67659
67660#ifdef SQLITE_VDBE_COVERAGE
67661/*
67662** Set the value if the iSrcLine field for the previously coded instruction.
67663*/
67664SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
67665  sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
67666}
67667#endif /* SQLITE_VDBE_COVERAGE */
67668
67669/*
67670** Return the opcode for a given address.  If the address is -1, then
67671** return the most recently inserted opcode.
67672**
67673** If a memory allocation error has occurred prior to the calling of this
67674** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
67675** is readable but not writable, though it is cast to a writable value.
67676** The return of a dummy opcode allows the call to continue functioning
67677** after an OOM fault without having to check to see if the return from
67678** this routine is a valid pointer.  But because the dummy.opcode is 0,
67679** dummy will never be written to.  This is verified by code inspection and
67680** by running with Valgrind.
67681*/
67682SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
67683  /* C89 specifies that the constant "dummy" will be initialized to all
67684  ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
67685  static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
67686  assert( p->magic==VDBE_MAGIC_INIT );
67687  if( addr<0 ){
67688    addr = p->nOp - 1;
67689  }
67690  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
67691  if( p->db->mallocFailed ){
67692    return (VdbeOp*)&dummy;
67693  }else{
67694    return &p->aOp[addr];
67695  }
67696}
67697
67698#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
67699/*
67700** Return an integer value for one of the parameters to the opcode pOp
67701** determined by character c.
67702*/
67703static int translateP(char c, const Op *pOp){
67704  if( c=='1' ) return pOp->p1;
67705  if( c=='2' ) return pOp->p2;
67706  if( c=='3' ) return pOp->p3;
67707  if( c=='4' ) return pOp->p4.i;
67708  return pOp->p5;
67709}
67710
67711/*
67712** Compute a string for the "comment" field of a VDBE opcode listing.
67713**
67714** The Synopsis: field in comments in the vdbe.c source file gets converted
67715** to an extra string that is appended to the sqlite3OpcodeName().  In the
67716** absence of other comments, this synopsis becomes the comment on the opcode.
67717** Some translation occurs:
67718**
67719**       "PX"      ->  "r[X]"
67720**       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
67721**       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
67722**       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
67723*/
67724static int displayComment(
67725  const Op *pOp,     /* The opcode to be commented */
67726  const char *zP4,   /* Previously obtained value for P4 */
67727  char *zTemp,       /* Write result here */
67728  int nTemp          /* Space available in zTemp[] */
67729){
67730  const char *zOpName;
67731  const char *zSynopsis;
67732  int nOpName;
67733  int ii, jj;
67734  zOpName = sqlite3OpcodeName(pOp->opcode);
67735  nOpName = sqlite3Strlen30(zOpName);
67736  if( zOpName[nOpName+1] ){
67737    int seenCom = 0;
67738    char c;
67739    zSynopsis = zOpName += nOpName + 1;
67740    for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
67741      if( c=='P' ){
67742        c = zSynopsis[++ii];
67743        if( c=='4' ){
67744          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
67745        }else if( c=='X' ){
67746          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
67747          seenCom = 1;
67748        }else{
67749          int v1 = translateP(c, pOp);
67750          int v2;
67751          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
67752          if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
67753            ii += 3;
67754            jj += sqlite3Strlen30(zTemp+jj);
67755            v2 = translateP(zSynopsis[ii], pOp);
67756            if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
67757              ii += 2;
67758              v2++;
67759            }
67760            if( v2>1 ){
67761              sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
67762            }
67763          }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
67764            ii += 4;
67765          }
67766        }
67767        jj += sqlite3Strlen30(zTemp+jj);
67768      }else{
67769        zTemp[jj++] = c;
67770      }
67771    }
67772    if( !seenCom && jj<nTemp-5 && pOp->zComment ){
67773      sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
67774      jj += sqlite3Strlen30(zTemp+jj);
67775    }
67776    if( jj<nTemp ) zTemp[jj] = 0;
67777  }else if( pOp->zComment ){
67778    sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
67779    jj = sqlite3Strlen30(zTemp);
67780  }else{
67781    zTemp[0] = 0;
67782    jj = 0;
67783  }
67784  return jj;
67785}
67786#endif /* SQLITE_DEBUG */
67787
67788
67789#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
67790     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
67791/*
67792** Compute a string that describes the P4 parameter for an opcode.
67793** Use zTemp for any required temporary buffer space.
67794*/
67795static char *displayP4(Op *pOp, char *zTemp, int nTemp){
67796  char *zP4 = zTemp;
67797  assert( nTemp>=20 );
67798  switch( pOp->p4type ){
67799    case P4_KEYINFO: {
67800      int i, j;
67801      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
67802      assert( pKeyInfo->aSortOrder!=0 );
67803      sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
67804      i = sqlite3Strlen30(zTemp);
67805      for(j=0; j<pKeyInfo->nField; j++){
67806        CollSeq *pColl = pKeyInfo->aColl[j];
67807        const char *zColl = pColl ? pColl->zName : "nil";
67808        int n = sqlite3Strlen30(zColl);
67809        if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
67810          zColl = "B";
67811          n = 1;
67812        }
67813        if( i+n>nTemp-7 ){
67814          memcpy(&zTemp[i],",...",4);
67815          i += 4;
67816          break;
67817        }
67818        zTemp[i++] = ',';
67819        if( pKeyInfo->aSortOrder[j] ){
67820          zTemp[i++] = '-';
67821        }
67822        memcpy(&zTemp[i], zColl, n+1);
67823        i += n;
67824      }
67825      zTemp[i++] = ')';
67826      zTemp[i] = 0;
67827      assert( i<nTemp );
67828      break;
67829    }
67830    case P4_COLLSEQ: {
67831      CollSeq *pColl = pOp->p4.pColl;
67832      sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
67833      break;
67834    }
67835    case P4_FUNCDEF: {
67836      FuncDef *pDef = pOp->p4.pFunc;
67837      sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
67838      break;
67839    }
67840#ifdef SQLITE_DEBUG
67841    case P4_FUNCCTX: {
67842      FuncDef *pDef = pOp->p4.pCtx->pFunc;
67843      sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
67844      break;
67845    }
67846#endif
67847    case P4_INT64: {
67848      sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
67849      break;
67850    }
67851    case P4_INT32: {
67852      sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
67853      break;
67854    }
67855    case P4_REAL: {
67856      sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
67857      break;
67858    }
67859    case P4_MEM: {
67860      Mem *pMem = pOp->p4.pMem;
67861      if( pMem->flags & MEM_Str ){
67862        zP4 = pMem->z;
67863      }else if( pMem->flags & MEM_Int ){
67864        sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
67865      }else if( pMem->flags & MEM_Real ){
67866        sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->u.r);
67867      }else if( pMem->flags & MEM_Null ){
67868        sqlite3_snprintf(nTemp, zTemp, "NULL");
67869      }else{
67870        assert( pMem->flags & MEM_Blob );
67871        zP4 = "(blob)";
67872      }
67873      break;
67874    }
67875#ifndef SQLITE_OMIT_VIRTUALTABLE
67876    case P4_VTAB: {
67877      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
67878      sqlite3_snprintf(nTemp, zTemp, "vtab:%p", pVtab);
67879      break;
67880    }
67881#endif
67882    case P4_INTARRAY: {
67883      sqlite3_snprintf(nTemp, zTemp, "intarray");
67884      break;
67885    }
67886    case P4_SUBPROGRAM: {
67887      sqlite3_snprintf(nTemp, zTemp, "program");
67888      break;
67889    }
67890    case P4_ADVANCE: {
67891      zTemp[0] = 0;
67892      break;
67893    }
67894    default: {
67895      zP4 = pOp->p4.z;
67896      if( zP4==0 ){
67897        zP4 = zTemp;
67898        zTemp[0] = 0;
67899      }
67900    }
67901  }
67902  assert( zP4!=0 );
67903  return zP4;
67904}
67905#endif
67906
67907/*
67908** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
67909**
67910** The prepared statements need to know in advance the complete set of
67911** attached databases that will be use.  A mask of these databases
67912** is maintained in p->btreeMask.  The p->lockMask value is the subset of
67913** p->btreeMask of databases that will require a lock.
67914*/
67915SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
67916  assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
67917  assert( i<(int)sizeof(p->btreeMask)*8 );
67918  DbMaskSet(p->btreeMask, i);
67919  if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
67920    DbMaskSet(p->lockMask, i);
67921  }
67922}
67923
67924#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
67925/*
67926** If SQLite is compiled to support shared-cache mode and to be threadsafe,
67927** this routine obtains the mutex associated with each BtShared structure
67928** that may be accessed by the VM passed as an argument. In doing so it also
67929** sets the BtShared.db member of each of the BtShared structures, ensuring
67930** that the correct busy-handler callback is invoked if required.
67931**
67932** If SQLite is not threadsafe but does support shared-cache mode, then
67933** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
67934** of all of BtShared structures accessible via the database handle
67935** associated with the VM.
67936**
67937** If SQLite is not threadsafe and does not support shared-cache mode, this
67938** function is a no-op.
67939**
67940** The p->btreeMask field is a bitmask of all btrees that the prepared
67941** statement p will ever use.  Let N be the number of bits in p->btreeMask
67942** corresponding to btrees that use shared cache.  Then the runtime of
67943** this routine is N*N.  But as N is rarely more than 1, this should not
67944** be a problem.
67945*/
67946SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
67947  int i;
67948  sqlite3 *db;
67949  Db *aDb;
67950  int nDb;
67951  if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
67952  db = p->db;
67953  aDb = db->aDb;
67954  nDb = db->nDb;
67955  for(i=0; i<nDb; i++){
67956    if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
67957      sqlite3BtreeEnter(aDb[i].pBt);
67958    }
67959  }
67960}
67961#endif
67962
67963#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
67964/*
67965** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
67966*/
67967static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
67968  int i;
67969  sqlite3 *db;
67970  Db *aDb;
67971  int nDb;
67972  db = p->db;
67973  aDb = db->aDb;
67974  nDb = db->nDb;
67975  for(i=0; i<nDb; i++){
67976    if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
67977      sqlite3BtreeLeave(aDb[i].pBt);
67978    }
67979  }
67980}
67981SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
67982  if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
67983  vdbeLeave(p);
67984}
67985#endif
67986
67987#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
67988/*
67989** Print a single opcode.  This routine is used for debugging only.
67990*/
67991SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
67992  char *zP4;
67993  char zPtr[50];
67994  char zCom[100];
67995  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
67996  if( pOut==0 ) pOut = stdout;
67997  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
67998#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
67999  displayComment(pOp, zP4, zCom, sizeof(zCom));
68000#else
68001  zCom[0] = 0;
68002#endif
68003  /* NB:  The sqlite3OpcodeName() function is implemented by code created
68004  ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
68005  ** information from the vdbe.c source text */
68006  fprintf(pOut, zFormat1, pc,
68007      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
68008      zCom
68009  );
68010  fflush(pOut);
68011}
68012#endif
68013
68014/*
68015** Release an array of N Mem elements
68016*/
68017static void releaseMemArray(Mem *p, int N){
68018  if( p && N ){
68019    Mem *pEnd = &p[N];
68020    sqlite3 *db = p->db;
68021    u8 malloc_failed = db->mallocFailed;
68022    if( db->pnBytesFreed ){
68023      do{
68024        if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
68025      }while( (++p)<pEnd );
68026      return;
68027    }
68028    do{
68029      assert( (&p[1])==pEnd || p[0].db==p[1].db );
68030      assert( sqlite3VdbeCheckMemInvariants(p) );
68031
68032      /* This block is really an inlined version of sqlite3VdbeMemRelease()
68033      ** that takes advantage of the fact that the memory cell value is
68034      ** being set to NULL after releasing any dynamic resources.
68035      **
68036      ** The justification for duplicating code is that according to
68037      ** callgrind, this causes a certain test case to hit the CPU 4.7
68038      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
68039      ** sqlite3MemRelease() were called from here. With -O2, this jumps
68040      ** to 6.6 percent. The test case is inserting 1000 rows into a table
68041      ** with no indexes using a single prepared INSERT statement, bind()
68042      ** and reset(). Inserts are grouped into a transaction.
68043      */
68044      testcase( p->flags & MEM_Agg );
68045      testcase( p->flags & MEM_Dyn );
68046      testcase( p->flags & MEM_Frame );
68047      testcase( p->flags & MEM_RowSet );
68048      if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
68049        sqlite3VdbeMemRelease(p);
68050      }else if( p->szMalloc ){
68051        sqlite3DbFree(db, p->zMalloc);
68052        p->szMalloc = 0;
68053      }
68054
68055      p->flags = MEM_Undefined;
68056    }while( (++p)<pEnd );
68057    db->mallocFailed = malloc_failed;
68058  }
68059}
68060
68061/*
68062** Delete a VdbeFrame object and its contents. VdbeFrame objects are
68063** allocated by the OP_Program opcode in sqlite3VdbeExec().
68064*/
68065SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
68066  int i;
68067  Mem *aMem = VdbeFrameMem(p);
68068  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
68069  for(i=0; i<p->nChildCsr; i++){
68070    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
68071  }
68072  releaseMemArray(aMem, p->nChildMem);
68073  sqlite3DbFree(p->v->db, p);
68074}
68075
68076#ifndef SQLITE_OMIT_EXPLAIN
68077/*
68078** Give a listing of the program in the virtual machine.
68079**
68080** The interface is the same as sqlite3VdbeExec().  But instead of
68081** running the code, it invokes the callback once for each instruction.
68082** This feature is used to implement "EXPLAIN".
68083**
68084** When p->explain==1, each instruction is listed.  When
68085** p->explain==2, only OP_Explain instructions are listed and these
68086** are shown in a different format.  p->explain==2 is used to implement
68087** EXPLAIN QUERY PLAN.
68088**
68089** When p->explain==1, first the main program is listed, then each of
68090** the trigger subprograms are listed one by one.
68091*/
68092SQLITE_PRIVATE int sqlite3VdbeList(
68093  Vdbe *p                   /* The VDBE */
68094){
68095  int nRow;                            /* Stop when row count reaches this */
68096  int nSub = 0;                        /* Number of sub-vdbes seen so far */
68097  SubProgram **apSub = 0;              /* Array of sub-vdbes */
68098  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
68099  sqlite3 *db = p->db;                 /* The database connection */
68100  int i;                               /* Loop counter */
68101  int rc = SQLITE_OK;                  /* Return code */
68102  Mem *pMem = &p->aMem[1];             /* First Mem of result set */
68103
68104  assert( p->explain );
68105  assert( p->magic==VDBE_MAGIC_RUN );
68106  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
68107
68108  /* Even though this opcode does not use dynamic strings for
68109  ** the result, result columns may become dynamic if the user calls
68110  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
68111  */
68112  releaseMemArray(pMem, 8);
68113  p->pResultSet = 0;
68114
68115  if( p->rc==SQLITE_NOMEM ){
68116    /* This happens if a malloc() inside a call to sqlite3_column_text() or
68117    ** sqlite3_column_text16() failed.  */
68118    db->mallocFailed = 1;
68119    return SQLITE_ERROR;
68120  }
68121
68122  /* When the number of output rows reaches nRow, that means the
68123  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
68124  ** nRow is the sum of the number of rows in the main program, plus
68125  ** the sum of the number of rows in all trigger subprograms encountered
68126  ** so far.  The nRow value will increase as new trigger subprograms are
68127  ** encountered, but p->pc will eventually catch up to nRow.
68128  */
68129  nRow = p->nOp;
68130  if( p->explain==1 ){
68131    /* The first 8 memory cells are used for the result set.  So we will
68132    ** commandeer the 9th cell to use as storage for an array of pointers
68133    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
68134    ** cells.  */
68135    assert( p->nMem>9 );
68136    pSub = &p->aMem[9];
68137    if( pSub->flags&MEM_Blob ){
68138      /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
68139      ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
68140      nSub = pSub->n/sizeof(Vdbe*);
68141      apSub = (SubProgram **)pSub->z;
68142    }
68143    for(i=0; i<nSub; i++){
68144      nRow += apSub[i]->nOp;
68145    }
68146  }
68147
68148  do{
68149    i = p->pc++;
68150  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
68151  if( i>=nRow ){
68152    p->rc = SQLITE_OK;
68153    rc = SQLITE_DONE;
68154  }else if( db->u1.isInterrupted ){
68155    p->rc = SQLITE_INTERRUPT;
68156    rc = SQLITE_ERROR;
68157    sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
68158  }else{
68159    char *zP4;
68160    Op *pOp;
68161    if( i<p->nOp ){
68162      /* The output line number is small enough that we are still in the
68163      ** main program. */
68164      pOp = &p->aOp[i];
68165    }else{
68166      /* We are currently listing subprograms.  Figure out which one and
68167      ** pick up the appropriate opcode. */
68168      int j;
68169      i -= p->nOp;
68170      for(j=0; i>=apSub[j]->nOp; j++){
68171        i -= apSub[j]->nOp;
68172      }
68173      pOp = &apSub[j]->aOp[i];
68174    }
68175    if( p->explain==1 ){
68176      pMem->flags = MEM_Int;
68177      pMem->u.i = i;                                /* Program counter */
68178      pMem++;
68179
68180      pMem->flags = MEM_Static|MEM_Str|MEM_Term;
68181      pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
68182      assert( pMem->z!=0 );
68183      pMem->n = sqlite3Strlen30(pMem->z);
68184      pMem->enc = SQLITE_UTF8;
68185      pMem++;
68186
68187      /* When an OP_Program opcode is encounter (the only opcode that has
68188      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
68189      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
68190      ** has not already been seen.
68191      */
68192      if( pOp->p4type==P4_SUBPROGRAM ){
68193        int nByte = (nSub+1)*sizeof(SubProgram*);
68194        int j;
68195        for(j=0; j<nSub; j++){
68196          if( apSub[j]==pOp->p4.pProgram ) break;
68197        }
68198        if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
68199          apSub = (SubProgram **)pSub->z;
68200          apSub[nSub++] = pOp->p4.pProgram;
68201          pSub->flags |= MEM_Blob;
68202          pSub->n = nSub*sizeof(SubProgram*);
68203        }
68204      }
68205    }
68206
68207    pMem->flags = MEM_Int;
68208    pMem->u.i = pOp->p1;                          /* P1 */
68209    pMem++;
68210
68211    pMem->flags = MEM_Int;
68212    pMem->u.i = pOp->p2;                          /* P2 */
68213    pMem++;
68214
68215    pMem->flags = MEM_Int;
68216    pMem->u.i = pOp->p3;                          /* P3 */
68217    pMem++;
68218
68219    if( sqlite3VdbeMemClearAndResize(pMem, 32) ){ /* P4 */
68220      assert( p->db->mallocFailed );
68221      return SQLITE_ERROR;
68222    }
68223    pMem->flags = MEM_Str|MEM_Term;
68224    zP4 = displayP4(pOp, pMem->z, 32);
68225    if( zP4!=pMem->z ){
68226      sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
68227    }else{
68228      assert( pMem->z!=0 );
68229      pMem->n = sqlite3Strlen30(pMem->z);
68230      pMem->enc = SQLITE_UTF8;
68231    }
68232    pMem++;
68233
68234    if( p->explain==1 ){
68235      if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
68236        assert( p->db->mallocFailed );
68237        return SQLITE_ERROR;
68238      }
68239      pMem->flags = MEM_Str|MEM_Term;
68240      pMem->n = 2;
68241      sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
68242      pMem->enc = SQLITE_UTF8;
68243      pMem++;
68244
68245#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
68246      if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
68247        assert( p->db->mallocFailed );
68248        return SQLITE_ERROR;
68249      }
68250      pMem->flags = MEM_Str|MEM_Term;
68251      pMem->n = displayComment(pOp, zP4, pMem->z, 500);
68252      pMem->enc = SQLITE_UTF8;
68253#else
68254      pMem->flags = MEM_Null;                       /* Comment */
68255#endif
68256    }
68257
68258    p->nResColumn = 8 - 4*(p->explain-1);
68259    p->pResultSet = &p->aMem[1];
68260    p->rc = SQLITE_OK;
68261    rc = SQLITE_ROW;
68262  }
68263  return rc;
68264}
68265#endif /* SQLITE_OMIT_EXPLAIN */
68266
68267#ifdef SQLITE_DEBUG
68268/*
68269** Print the SQL that was used to generate a VDBE program.
68270*/
68271SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
68272  const char *z = 0;
68273  if( p->zSql ){
68274    z = p->zSql;
68275  }else if( p->nOp>=1 ){
68276    const VdbeOp *pOp = &p->aOp[0];
68277    if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
68278      z = pOp->p4.z;
68279      while( sqlite3Isspace(*z) ) z++;
68280    }
68281  }
68282  if( z ) printf("SQL: [%s]\n", z);
68283}
68284#endif
68285
68286#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
68287/*
68288** Print an IOTRACE message showing SQL content.
68289*/
68290SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
68291  int nOp = p->nOp;
68292  VdbeOp *pOp;
68293  if( sqlite3IoTrace==0 ) return;
68294  if( nOp<1 ) return;
68295  pOp = &p->aOp[0];
68296  if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
68297    int i, j;
68298    char z[1000];
68299    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
68300    for(i=0; sqlite3Isspace(z[i]); i++){}
68301    for(j=0; z[i]; i++){
68302      if( sqlite3Isspace(z[i]) ){
68303        if( z[i-1]!=' ' ){
68304          z[j++] = ' ';
68305        }
68306      }else{
68307        z[j++] = z[i];
68308      }
68309    }
68310    z[j] = 0;
68311    sqlite3IoTrace("SQL %s\n", z);
68312  }
68313}
68314#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
68315
68316/*
68317** Allocate space from a fixed size buffer and return a pointer to
68318** that space.  If insufficient space is available, return NULL.
68319**
68320** The pBuf parameter is the initial value of a pointer which will
68321** receive the new memory.  pBuf is normally NULL.  If pBuf is not
68322** NULL, it means that memory space has already been allocated and that
68323** this routine should not allocate any new memory.  When pBuf is not
68324** NULL simply return pBuf.  Only allocate new memory space when pBuf
68325** is NULL.
68326**
68327** nByte is the number of bytes of space needed.
68328**
68329** *ppFrom points to available space and pEnd points to the end of the
68330** available space.  When space is allocated, *ppFrom is advanced past
68331** the end of the allocated space.
68332**
68333** *pnByte is a counter of the number of bytes of space that have failed
68334** to allocate.  If there is insufficient space in *ppFrom to satisfy the
68335** request, then increment *pnByte by the amount of the request.
68336*/
68337static void *allocSpace(
68338  void *pBuf,          /* Where return pointer will be stored */
68339  int nByte,           /* Number of bytes to allocate */
68340  u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
68341  u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
68342  int *pnByte          /* If allocation cannot be made, increment *pnByte */
68343){
68344  assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
68345  if( pBuf ) return pBuf;
68346  nByte = ROUND8(nByte);
68347  if( &(*ppFrom)[nByte] <= pEnd ){
68348    pBuf = (void*)*ppFrom;
68349    *ppFrom += nByte;
68350  }else{
68351    *pnByte += nByte;
68352  }
68353  return pBuf;
68354}
68355
68356/*
68357** Rewind the VDBE back to the beginning in preparation for
68358** running it.
68359*/
68360SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
68361#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
68362  int i;
68363#endif
68364  assert( p!=0 );
68365  assert( p->magic==VDBE_MAGIC_INIT );
68366
68367  /* There should be at least one opcode.
68368  */
68369  assert( p->nOp>0 );
68370
68371  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
68372  p->magic = VDBE_MAGIC_RUN;
68373
68374#ifdef SQLITE_DEBUG
68375  for(i=1; i<p->nMem; i++){
68376    assert( p->aMem[i].db==p->db );
68377  }
68378#endif
68379  p->pc = -1;
68380  p->rc = SQLITE_OK;
68381  p->errorAction = OE_Abort;
68382  p->magic = VDBE_MAGIC_RUN;
68383  p->nChange = 0;
68384  p->cacheCtr = 1;
68385  p->minWriteFileFormat = 255;
68386  p->iStatement = 0;
68387  p->nFkConstraint = 0;
68388#ifdef VDBE_PROFILE
68389  for(i=0; i<p->nOp; i++){
68390    p->aOp[i].cnt = 0;
68391    p->aOp[i].cycles = 0;
68392  }
68393#endif
68394}
68395
68396/*
68397** Prepare a virtual machine for execution for the first time after
68398** creating the virtual machine.  This involves things such
68399** as allocating registers and initializing the program counter.
68400** After the VDBE has be prepped, it can be executed by one or more
68401** calls to sqlite3VdbeExec().
68402**
68403** This function may be called exactly once on each virtual machine.
68404** After this routine is called the VM has been "packaged" and is ready
68405** to run.  After this routine is called, further calls to
68406** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
68407** the Vdbe from the Parse object that helped generate it so that the
68408** the Vdbe becomes an independent entity and the Parse object can be
68409** destroyed.
68410**
68411** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
68412** to its initial state after it has been run.
68413*/
68414SQLITE_PRIVATE void sqlite3VdbeMakeReady(
68415  Vdbe *p,                       /* The VDBE */
68416  Parse *pParse                  /* Parsing context */
68417){
68418  sqlite3 *db;                   /* The database connection */
68419  int nVar;                      /* Number of parameters */
68420  int nMem;                      /* Number of VM memory registers */
68421  int nCursor;                   /* Number of cursors required */
68422  int nArg;                      /* Number of arguments in subprograms */
68423  int nOnce;                     /* Number of OP_Once instructions */
68424  int n;                         /* Loop counter */
68425  u8 *zCsr;                      /* Memory available for allocation */
68426  u8 *zEnd;                      /* First byte past allocated memory */
68427  int nByte;                     /* How much extra memory is needed */
68428
68429  assert( p!=0 );
68430  assert( p->nOp>0 );
68431  assert( pParse!=0 );
68432  assert( p->magic==VDBE_MAGIC_INIT );
68433  assert( pParse==p->pParse );
68434  db = p->db;
68435  assert( db->mallocFailed==0 );
68436  nVar = pParse->nVar;
68437  nMem = pParse->nMem;
68438  nCursor = pParse->nTab;
68439  nArg = pParse->nMaxArg;
68440  nOnce = pParse->nOnce;
68441  if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
68442
68443  /* For each cursor required, also allocate a memory cell. Memory
68444  ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
68445  ** the vdbe program. Instead they are used to allocate space for
68446  ** VdbeCursor/BtCursor structures. The blob of memory associated with
68447  ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
68448  ** stores the blob of memory associated with cursor 1, etc.
68449  **
68450  ** See also: allocateCursor().
68451  */
68452  nMem += nCursor;
68453
68454  /* Allocate space for memory registers, SQL variables, VDBE cursors and
68455  ** an array to marshal SQL function arguments in.
68456  */
68457  zCsr = (u8*)&p->aOp[p->nOp];            /* Memory avaliable for allocation */
68458  zEnd = (u8*)&p->aOp[pParse->nOpAlloc];  /* First byte past end of zCsr[] */
68459
68460  resolveP2Values(p, &nArg);
68461  p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
68462  if( pParse->explain && nMem<10 ){
68463    nMem = 10;
68464  }
68465  memset(zCsr, 0, zEnd-zCsr);
68466  zCsr += (zCsr - (u8*)0)&7;
68467  assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
68468  p->expired = 0;
68469
68470  /* Memory for registers, parameters, cursor, etc, is allocated in two
68471  ** passes.  On the first pass, we try to reuse unused space at the
68472  ** end of the opcode array.  If we are unable to satisfy all memory
68473  ** requirements by reusing the opcode array tail, then the second
68474  ** pass will fill in the rest using a fresh allocation.
68475  **
68476  ** This two-pass approach that reuses as much memory as possible from
68477  ** the leftover space at the end of the opcode array can significantly
68478  ** reduce the amount of memory held by a prepared statement.
68479  */
68480  do {
68481    nByte = 0;
68482    p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
68483    p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
68484    p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
68485    p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
68486    p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
68487                          &zCsr, zEnd, &nByte);
68488    p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
68489#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
68490    p->anExec = allocSpace(p->anExec, p->nOp*sizeof(i64), &zCsr, zEnd, &nByte);
68491#endif
68492    if( nByte ){
68493      p->pFree = sqlite3DbMallocZero(db, nByte);
68494    }
68495    zCsr = p->pFree;
68496    zEnd = &zCsr[nByte];
68497  }while( nByte && !db->mallocFailed );
68498
68499  p->nCursor = nCursor;
68500  p->nOnceFlag = nOnce;
68501  if( p->aVar ){
68502    p->nVar = (ynVar)nVar;
68503    for(n=0; n<nVar; n++){
68504      p->aVar[n].flags = MEM_Null;
68505      p->aVar[n].db = db;
68506    }
68507  }
68508  if( p->azVar && pParse->nzVar>0 ){
68509    p->nzVar = pParse->nzVar;
68510    memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
68511    memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
68512  }
68513  if( p->aMem ){
68514    p->aMem--;                      /* aMem[] goes from 1..nMem */
68515    p->nMem = nMem;                 /*       not from 0..nMem-1 */
68516    for(n=1; n<=nMem; n++){
68517      p->aMem[n].flags = MEM_Undefined;
68518      p->aMem[n].db = db;
68519    }
68520  }
68521  p->explain = pParse->explain;
68522  sqlite3VdbeRewind(p);
68523}
68524
68525/*
68526** Close a VDBE cursor and release all the resources that cursor
68527** happens to hold.
68528*/
68529SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
68530  if( pCx==0 ){
68531    return;
68532  }
68533  sqlite3VdbeSorterClose(p->db, pCx);
68534  if( pCx->pBt ){
68535    sqlite3BtreeClose(pCx->pBt);
68536    /* The pCx->pCursor will be close automatically, if it exists, by
68537    ** the call above. */
68538  }else if( pCx->pCursor ){
68539    sqlite3BtreeCloseCursor(pCx->pCursor);
68540  }
68541#ifndef SQLITE_OMIT_VIRTUALTABLE
68542  else if( pCx->pVtabCursor ){
68543    sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
68544    const sqlite3_module *pModule = pVtabCursor->pVtab->pModule;
68545    assert( pVtabCursor->pVtab->nRef>0 );
68546    pVtabCursor->pVtab->nRef--;
68547    pModule->xClose(pVtabCursor);
68548  }
68549#endif
68550}
68551
68552/*
68553** Close all cursors in the current frame.
68554*/
68555static void closeCursorsInFrame(Vdbe *p){
68556  if( p->apCsr ){
68557    int i;
68558    for(i=0; i<p->nCursor; i++){
68559      VdbeCursor *pC = p->apCsr[i];
68560      if( pC ){
68561        sqlite3VdbeFreeCursor(p, pC);
68562        p->apCsr[i] = 0;
68563      }
68564    }
68565  }
68566}
68567
68568/*
68569** Copy the values stored in the VdbeFrame structure to its Vdbe. This
68570** is used, for example, when a trigger sub-program is halted to restore
68571** control to the main program.
68572*/
68573SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
68574  Vdbe *v = pFrame->v;
68575  closeCursorsInFrame(v);
68576#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
68577  v->anExec = pFrame->anExec;
68578#endif
68579  v->aOnceFlag = pFrame->aOnceFlag;
68580  v->nOnceFlag = pFrame->nOnceFlag;
68581  v->aOp = pFrame->aOp;
68582  v->nOp = pFrame->nOp;
68583  v->aMem = pFrame->aMem;
68584  v->nMem = pFrame->nMem;
68585  v->apCsr = pFrame->apCsr;
68586  v->nCursor = pFrame->nCursor;
68587  v->db->lastRowid = pFrame->lastRowid;
68588  v->nChange = pFrame->nChange;
68589  v->db->nChange = pFrame->nDbChange;
68590  return pFrame->pc;
68591}
68592
68593/*
68594** Close all cursors.
68595**
68596** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
68597** cell array. This is necessary as the memory cell array may contain
68598** pointers to VdbeFrame objects, which may in turn contain pointers to
68599** open cursors.
68600*/
68601static void closeAllCursors(Vdbe *p){
68602  if( p->pFrame ){
68603    VdbeFrame *pFrame;
68604    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
68605    sqlite3VdbeFrameRestore(pFrame);
68606    p->pFrame = 0;
68607    p->nFrame = 0;
68608  }
68609  assert( p->nFrame==0 );
68610  closeCursorsInFrame(p);
68611  if( p->aMem ){
68612    releaseMemArray(&p->aMem[1], p->nMem);
68613  }
68614  while( p->pDelFrame ){
68615    VdbeFrame *pDel = p->pDelFrame;
68616    p->pDelFrame = pDel->pParent;
68617    sqlite3VdbeFrameDelete(pDel);
68618  }
68619
68620  /* Delete any auxdata allocations made by the VM */
68621  if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p, -1, 0);
68622  assert( p->pAuxData==0 );
68623}
68624
68625/*
68626** Clean up the VM after a single run.
68627*/
68628static void Cleanup(Vdbe *p){
68629  sqlite3 *db = p->db;
68630
68631#ifdef SQLITE_DEBUG
68632  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
68633  ** Vdbe.aMem[] arrays have already been cleaned up.  */
68634  int i;
68635  if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
68636  if( p->aMem ){
68637    for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
68638  }
68639#endif
68640
68641  sqlite3DbFree(db, p->zErrMsg);
68642  p->zErrMsg = 0;
68643  p->pResultSet = 0;
68644}
68645
68646/*
68647** Set the number of result columns that will be returned by this SQL
68648** statement. This is now set at compile time, rather than during
68649** execution of the vdbe program so that sqlite3_column_count() can
68650** be called on an SQL statement before sqlite3_step().
68651*/
68652SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
68653  Mem *pColName;
68654  int n;
68655  sqlite3 *db = p->db;
68656
68657  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
68658  sqlite3DbFree(db, p->aColName);
68659  n = nResColumn*COLNAME_N;
68660  p->nResColumn = (u16)nResColumn;
68661  p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
68662  if( p->aColName==0 ) return;
68663  while( n-- > 0 ){
68664    pColName->flags = MEM_Null;
68665    pColName->db = p->db;
68666    pColName++;
68667  }
68668}
68669
68670/*
68671** Set the name of the idx'th column to be returned by the SQL statement.
68672** zName must be a pointer to a nul terminated string.
68673**
68674** This call must be made after a call to sqlite3VdbeSetNumCols().
68675**
68676** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
68677** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
68678** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
68679*/
68680SQLITE_PRIVATE int sqlite3VdbeSetColName(
68681  Vdbe *p,                         /* Vdbe being configured */
68682  int idx,                         /* Index of column zName applies to */
68683  int var,                         /* One of the COLNAME_* constants */
68684  const char *zName,               /* Pointer to buffer containing name */
68685  void (*xDel)(void*)              /* Memory management strategy for zName */
68686){
68687  int rc;
68688  Mem *pColName;
68689  assert( idx<p->nResColumn );
68690  assert( var<COLNAME_N );
68691  if( p->db->mallocFailed ){
68692    assert( !zName || xDel!=SQLITE_DYNAMIC );
68693    return SQLITE_NOMEM;
68694  }
68695  assert( p->aColName!=0 );
68696  pColName = &(p->aColName[idx+var*p->nResColumn]);
68697  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
68698  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
68699  return rc;
68700}
68701
68702/*
68703** A read or write transaction may or may not be active on database handle
68704** db. If a transaction is active, commit it. If there is a
68705** write-transaction spanning more than one database file, this routine
68706** takes care of the master journal trickery.
68707*/
68708static int vdbeCommit(sqlite3 *db, Vdbe *p){
68709  int i;
68710  int nTrans = 0;  /* Number of databases with an active write-transaction */
68711  int rc = SQLITE_OK;
68712  int needXcommit = 0;
68713
68714#ifdef SQLITE_OMIT_VIRTUALTABLE
68715  /* With this option, sqlite3VtabSync() is defined to be simply
68716  ** SQLITE_OK so p is not used.
68717  */
68718  UNUSED_PARAMETER(p);
68719#endif
68720
68721  /* Before doing anything else, call the xSync() callback for any
68722  ** virtual module tables written in this transaction. This has to
68723  ** be done before determining whether a master journal file is
68724  ** required, as an xSync() callback may add an attached database
68725  ** to the transaction.
68726  */
68727  rc = sqlite3VtabSync(db, p);
68728
68729  /* This loop determines (a) if the commit hook should be invoked and
68730  ** (b) how many database files have open write transactions, not
68731  ** including the temp database. (b) is important because if more than
68732  ** one database file has an open write transaction, a master journal
68733  ** file is required for an atomic commit.
68734  */
68735  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
68736    Btree *pBt = db->aDb[i].pBt;
68737    if( sqlite3BtreeIsInTrans(pBt) ){
68738      needXcommit = 1;
68739      if( i!=1 ) nTrans++;
68740      sqlite3BtreeEnter(pBt);
68741      rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
68742      sqlite3BtreeLeave(pBt);
68743    }
68744  }
68745  if( rc!=SQLITE_OK ){
68746    return rc;
68747  }
68748
68749  /* If there are any write-transactions at all, invoke the commit hook */
68750  if( needXcommit && db->xCommitCallback ){
68751    rc = db->xCommitCallback(db->pCommitArg);
68752    if( rc ){
68753      return SQLITE_CONSTRAINT_COMMITHOOK;
68754    }
68755  }
68756
68757  /* The simple case - no more than one database file (not counting the
68758  ** TEMP database) has a transaction active.   There is no need for the
68759  ** master-journal.
68760  **
68761  ** If the return value of sqlite3BtreeGetFilename() is a zero length
68762  ** string, it means the main database is :memory: or a temp file.  In
68763  ** that case we do not support atomic multi-file commits, so use the
68764  ** simple case then too.
68765  */
68766  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
68767   || nTrans<=1
68768  ){
68769    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
68770      Btree *pBt = db->aDb[i].pBt;
68771      if( pBt ){
68772        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
68773      }
68774    }
68775
68776    /* Do the commit only if all databases successfully complete phase 1.
68777    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
68778    ** IO error while deleting or truncating a journal file. It is unlikely,
68779    ** but could happen. In this case abandon processing and return the error.
68780    */
68781    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
68782      Btree *pBt = db->aDb[i].pBt;
68783      if( pBt ){
68784        rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
68785      }
68786    }
68787    if( rc==SQLITE_OK ){
68788      sqlite3VtabCommit(db);
68789    }
68790  }
68791
68792  /* The complex case - There is a multi-file write-transaction active.
68793  ** This requires a master journal file to ensure the transaction is
68794  ** committed atomically.
68795  */
68796#ifndef SQLITE_OMIT_DISKIO
68797  else{
68798    sqlite3_vfs *pVfs = db->pVfs;
68799    int needSync = 0;
68800    char *zMaster = 0;   /* File-name for the master journal */
68801    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
68802    sqlite3_file *pMaster = 0;
68803    i64 offset = 0;
68804    int res;
68805    int retryCount = 0;
68806    int nMainFile;
68807
68808    /* Select a master journal file name */
68809    nMainFile = sqlite3Strlen30(zMainFile);
68810    zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
68811    if( zMaster==0 ) return SQLITE_NOMEM;
68812    do {
68813      u32 iRandom;
68814      if( retryCount ){
68815        if( retryCount>100 ){
68816          sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
68817          sqlite3OsDelete(pVfs, zMaster, 0);
68818          break;
68819        }else if( retryCount==1 ){
68820          sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
68821        }
68822      }
68823      retryCount++;
68824      sqlite3_randomness(sizeof(iRandom), &iRandom);
68825      sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
68826                               (iRandom>>8)&0xffffff, iRandom&0xff);
68827      /* The antipenultimate character of the master journal name must
68828      ** be "9" to avoid name collisions when using 8+3 filenames. */
68829      assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
68830      sqlite3FileSuffix3(zMainFile, zMaster);
68831      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
68832    }while( rc==SQLITE_OK && res );
68833    if( rc==SQLITE_OK ){
68834      /* Open the master journal. */
68835      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
68836          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
68837          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
68838      );
68839    }
68840    if( rc!=SQLITE_OK ){
68841      sqlite3DbFree(db, zMaster);
68842      return rc;
68843    }
68844
68845    /* Write the name of each database file in the transaction into the new
68846    ** master journal file. If an error occurs at this point close
68847    ** and delete the master journal file. All the individual journal files
68848    ** still have 'null' as the master journal pointer, so they will roll
68849    ** back independently if a failure occurs.
68850    */
68851    for(i=0; i<db->nDb; i++){
68852      Btree *pBt = db->aDb[i].pBt;
68853      if( sqlite3BtreeIsInTrans(pBt) ){
68854        char const *zFile = sqlite3BtreeGetJournalname(pBt);
68855        if( zFile==0 ){
68856          continue;  /* Ignore TEMP and :memory: databases */
68857        }
68858        assert( zFile[0]!=0 );
68859        if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
68860          needSync = 1;
68861        }
68862        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
68863        offset += sqlite3Strlen30(zFile)+1;
68864        if( rc!=SQLITE_OK ){
68865          sqlite3OsCloseFree(pMaster);
68866          sqlite3OsDelete(pVfs, zMaster, 0);
68867          sqlite3DbFree(db, zMaster);
68868          return rc;
68869        }
68870      }
68871    }
68872
68873    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
68874    ** flag is set this is not required.
68875    */
68876    if( needSync
68877     && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
68878     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
68879    ){
68880      sqlite3OsCloseFree(pMaster);
68881      sqlite3OsDelete(pVfs, zMaster, 0);
68882      sqlite3DbFree(db, zMaster);
68883      return rc;
68884    }
68885
68886    /* Sync all the db files involved in the transaction. The same call
68887    ** sets the master journal pointer in each individual journal. If
68888    ** an error occurs here, do not delete the master journal file.
68889    **
68890    ** If the error occurs during the first call to
68891    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
68892    ** master journal file will be orphaned. But we cannot delete it,
68893    ** in case the master journal file name was written into the journal
68894    ** file before the failure occurred.
68895    */
68896    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
68897      Btree *pBt = db->aDb[i].pBt;
68898      if( pBt ){
68899        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
68900      }
68901    }
68902    sqlite3OsCloseFree(pMaster);
68903    assert( rc!=SQLITE_BUSY );
68904    if( rc!=SQLITE_OK ){
68905      sqlite3DbFree(db, zMaster);
68906      return rc;
68907    }
68908
68909    /* Delete the master journal file. This commits the transaction. After
68910    ** doing this the directory is synced again before any individual
68911    ** transaction files are deleted.
68912    */
68913    rc = sqlite3OsDelete(pVfs, zMaster, needSync);
68914    sqlite3DbFree(db, zMaster);
68915    zMaster = 0;
68916    if( rc ){
68917      return rc;
68918    }
68919
68920    /* All files and directories have already been synced, so the following
68921    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
68922    ** deleting or truncating journals. If something goes wrong while
68923    ** this is happening we don't really care. The integrity of the
68924    ** transaction is already guaranteed, but some stray 'cold' journals
68925    ** may be lying around. Returning an error code won't help matters.
68926    */
68927    disable_simulated_io_errors();
68928    sqlite3BeginBenignMalloc();
68929    for(i=0; i<db->nDb; i++){
68930      Btree *pBt = db->aDb[i].pBt;
68931      if( pBt ){
68932        sqlite3BtreeCommitPhaseTwo(pBt, 1);
68933      }
68934    }
68935    sqlite3EndBenignMalloc();
68936    enable_simulated_io_errors();
68937
68938    sqlite3VtabCommit(db);
68939  }
68940#endif
68941
68942  return rc;
68943}
68944
68945/*
68946** This routine checks that the sqlite3.nVdbeActive count variable
68947** matches the number of vdbe's in the list sqlite3.pVdbe that are
68948** currently active. An assertion fails if the two counts do not match.
68949** This is an internal self-check only - it is not an essential processing
68950** step.
68951**
68952** This is a no-op if NDEBUG is defined.
68953*/
68954#ifndef NDEBUG
68955static void checkActiveVdbeCnt(sqlite3 *db){
68956  Vdbe *p;
68957  int cnt = 0;
68958  int nWrite = 0;
68959  int nRead = 0;
68960  p = db->pVdbe;
68961  while( p ){
68962    if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
68963      cnt++;
68964      if( p->readOnly==0 ) nWrite++;
68965      if( p->bIsReader ) nRead++;
68966    }
68967    p = p->pNext;
68968  }
68969  assert( cnt==db->nVdbeActive );
68970  assert( nWrite==db->nVdbeWrite );
68971  assert( nRead==db->nVdbeRead );
68972}
68973#else
68974#define checkActiveVdbeCnt(x)
68975#endif
68976
68977/*
68978** If the Vdbe passed as the first argument opened a statement-transaction,
68979** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
68980** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
68981** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
68982** statement transaction is committed.
68983**
68984** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
68985** Otherwise SQLITE_OK.
68986*/
68987SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
68988  sqlite3 *const db = p->db;
68989  int rc = SQLITE_OK;
68990
68991  /* If p->iStatement is greater than zero, then this Vdbe opened a
68992  ** statement transaction that should be closed here. The only exception
68993  ** is that an IO error may have occurred, causing an emergency rollback.
68994  ** In this case (db->nStatement==0), and there is nothing to do.
68995  */
68996  if( db->nStatement && p->iStatement ){
68997    int i;
68998    const int iSavepoint = p->iStatement-1;
68999
69000    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
69001    assert( db->nStatement>0 );
69002    assert( p->iStatement==(db->nStatement+db->nSavepoint) );
69003
69004    for(i=0; i<db->nDb; i++){
69005      int rc2 = SQLITE_OK;
69006      Btree *pBt = db->aDb[i].pBt;
69007      if( pBt ){
69008        if( eOp==SAVEPOINT_ROLLBACK ){
69009          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
69010        }
69011        if( rc2==SQLITE_OK ){
69012          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
69013        }
69014        if( rc==SQLITE_OK ){
69015          rc = rc2;
69016        }
69017      }
69018    }
69019    db->nStatement--;
69020    p->iStatement = 0;
69021
69022    if( rc==SQLITE_OK ){
69023      if( eOp==SAVEPOINT_ROLLBACK ){
69024        rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
69025      }
69026      if( rc==SQLITE_OK ){
69027        rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
69028      }
69029    }
69030
69031    /* If the statement transaction is being rolled back, also restore the
69032    ** database handles deferred constraint counter to the value it had when
69033    ** the statement transaction was opened.  */
69034    if( eOp==SAVEPOINT_ROLLBACK ){
69035      db->nDeferredCons = p->nStmtDefCons;
69036      db->nDeferredImmCons = p->nStmtDefImmCons;
69037    }
69038  }
69039  return rc;
69040}
69041
69042/*
69043** This function is called when a transaction opened by the database
69044** handle associated with the VM passed as an argument is about to be
69045** committed. If there are outstanding deferred foreign key constraint
69046** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
69047**
69048** If there are outstanding FK violations and this function returns
69049** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
69050** and write an error message to it. Then return SQLITE_ERROR.
69051*/
69052#ifndef SQLITE_OMIT_FOREIGN_KEY
69053SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
69054  sqlite3 *db = p->db;
69055  if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
69056   || (!deferred && p->nFkConstraint>0)
69057  ){
69058    p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
69059    p->errorAction = OE_Abort;
69060    sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
69061    return SQLITE_ERROR;
69062  }
69063  return SQLITE_OK;
69064}
69065#endif
69066
69067/*
69068** This routine is called the when a VDBE tries to halt.  If the VDBE
69069** has made changes and is in autocommit mode, then commit those
69070** changes.  If a rollback is needed, then do the rollback.
69071**
69072** This routine is the only way to move the state of a VM from
69073** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
69074** call this on a VM that is in the SQLITE_MAGIC_HALT state.
69075**
69076** Return an error code.  If the commit could not complete because of
69077** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
69078** means the close did not happen and needs to be repeated.
69079*/
69080SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
69081  int rc;                         /* Used to store transient return codes */
69082  sqlite3 *db = p->db;
69083
69084  /* This function contains the logic that determines if a statement or
69085  ** transaction will be committed or rolled back as a result of the
69086  ** execution of this virtual machine.
69087  **
69088  ** If any of the following errors occur:
69089  **
69090  **     SQLITE_NOMEM
69091  **     SQLITE_IOERR
69092  **     SQLITE_FULL
69093  **     SQLITE_INTERRUPT
69094  **
69095  ** Then the internal cache might have been left in an inconsistent
69096  ** state.  We need to rollback the statement transaction, if there is
69097  ** one, or the complete transaction if there is no statement transaction.
69098  */
69099
69100  if( p->db->mallocFailed ){
69101    p->rc = SQLITE_NOMEM;
69102  }
69103  if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
69104  closeAllCursors(p);
69105  if( p->magic!=VDBE_MAGIC_RUN ){
69106    return SQLITE_OK;
69107  }
69108  checkActiveVdbeCnt(db);
69109
69110  /* No commit or rollback needed if the program never started or if the
69111  ** SQL statement does not read or write a database file.  */
69112  if( p->pc>=0 && p->bIsReader ){
69113    int mrc;   /* Primary error code from p->rc */
69114    int eStatementOp = 0;
69115    int isSpecialError;            /* Set to true if a 'special' error */
69116
69117    /* Lock all btrees used by the statement */
69118    sqlite3VdbeEnter(p);
69119
69120    /* Check for one of the special errors */
69121    mrc = p->rc & 0xff;
69122    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
69123                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
69124    if( isSpecialError ){
69125      /* If the query was read-only and the error code is SQLITE_INTERRUPT,
69126      ** no rollback is necessary. Otherwise, at least a savepoint
69127      ** transaction must be rolled back to restore the database to a
69128      ** consistent state.
69129      **
69130      ** Even if the statement is read-only, it is important to perform
69131      ** a statement or transaction rollback operation. If the error
69132      ** occurred while writing to the journal, sub-journal or database
69133      ** file as part of an effort to free up cache space (see function
69134      ** pagerStress() in pager.c), the rollback is required to restore
69135      ** the pager to a consistent state.
69136      */
69137      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
69138        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
69139          eStatementOp = SAVEPOINT_ROLLBACK;
69140        }else{
69141          /* We are forced to roll back the active transaction. Before doing
69142          ** so, abort any other statements this handle currently has active.
69143          */
69144          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
69145          sqlite3CloseSavepoints(db);
69146          db->autoCommit = 1;
69147          p->nChange = 0;
69148        }
69149      }
69150    }
69151
69152    /* Check for immediate foreign key violations. */
69153    if( p->rc==SQLITE_OK ){
69154      sqlite3VdbeCheckFk(p, 0);
69155    }
69156
69157    /* If the auto-commit flag is set and this is the only active writer
69158    ** VM, then we do either a commit or rollback of the current transaction.
69159    **
69160    ** Note: This block also runs if one of the special errors handled
69161    ** above has occurred.
69162    */
69163    if( !sqlite3VtabInSync(db)
69164     && db->autoCommit
69165     && db->nVdbeWrite==(p->readOnly==0)
69166    ){
69167      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
69168        rc = sqlite3VdbeCheckFk(p, 1);
69169        if( rc!=SQLITE_OK ){
69170          if( NEVER(p->readOnly) ){
69171            sqlite3VdbeLeave(p);
69172            return SQLITE_ERROR;
69173          }
69174          rc = SQLITE_CONSTRAINT_FOREIGNKEY;
69175        }else{
69176          /* The auto-commit flag is true, the vdbe program was successful
69177          ** or hit an 'OR FAIL' constraint and there are no deferred foreign
69178          ** key constraints to hold up the transaction. This means a commit
69179          ** is required. */
69180          rc = vdbeCommit(db, p);
69181        }
69182        if( rc==SQLITE_BUSY && p->readOnly ){
69183          sqlite3VdbeLeave(p);
69184          return SQLITE_BUSY;
69185        }else if( rc!=SQLITE_OK ){
69186          p->rc = rc;
69187          sqlite3RollbackAll(db, SQLITE_OK);
69188          p->nChange = 0;
69189        }else{
69190          db->nDeferredCons = 0;
69191          db->nDeferredImmCons = 0;
69192          db->flags &= ~SQLITE_DeferFKs;
69193          sqlite3CommitInternalChanges(db);
69194        }
69195      }else{
69196        sqlite3RollbackAll(db, SQLITE_OK);
69197        p->nChange = 0;
69198      }
69199      db->nStatement = 0;
69200    }else if( eStatementOp==0 ){
69201      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
69202        eStatementOp = SAVEPOINT_RELEASE;
69203      }else if( p->errorAction==OE_Abort ){
69204        eStatementOp = SAVEPOINT_ROLLBACK;
69205      }else{
69206        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
69207        sqlite3CloseSavepoints(db);
69208        db->autoCommit = 1;
69209        p->nChange = 0;
69210      }
69211    }
69212
69213    /* If eStatementOp is non-zero, then a statement transaction needs to
69214    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
69215    ** do so. If this operation returns an error, and the current statement
69216    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
69217    ** current statement error code.
69218    */
69219    if( eStatementOp ){
69220      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
69221      if( rc ){
69222        if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
69223          p->rc = rc;
69224          sqlite3DbFree(db, p->zErrMsg);
69225          p->zErrMsg = 0;
69226        }
69227        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
69228        sqlite3CloseSavepoints(db);
69229        db->autoCommit = 1;
69230        p->nChange = 0;
69231      }
69232    }
69233
69234    /* If this was an INSERT, UPDATE or DELETE and no statement transaction
69235    ** has been rolled back, update the database connection change-counter.
69236    */
69237    if( p->changeCntOn ){
69238      if( eStatementOp!=SAVEPOINT_ROLLBACK ){
69239        sqlite3VdbeSetChanges(db, p->nChange);
69240      }else{
69241        sqlite3VdbeSetChanges(db, 0);
69242      }
69243      p->nChange = 0;
69244    }
69245
69246    /* Release the locks */
69247    sqlite3VdbeLeave(p);
69248  }
69249
69250  /* We have successfully halted and closed the VM.  Record this fact. */
69251  if( p->pc>=0 ){
69252    db->nVdbeActive--;
69253    if( !p->readOnly ) db->nVdbeWrite--;
69254    if( p->bIsReader ) db->nVdbeRead--;
69255    assert( db->nVdbeActive>=db->nVdbeRead );
69256    assert( db->nVdbeRead>=db->nVdbeWrite );
69257    assert( db->nVdbeWrite>=0 );
69258  }
69259  p->magic = VDBE_MAGIC_HALT;
69260  checkActiveVdbeCnt(db);
69261  if( p->db->mallocFailed ){
69262    p->rc = SQLITE_NOMEM;
69263  }
69264
69265  /* If the auto-commit flag is set to true, then any locks that were held
69266  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
69267  ** to invoke any required unlock-notify callbacks.
69268  */
69269  if( db->autoCommit ){
69270    sqlite3ConnectionUnlocked(db);
69271  }
69272
69273  assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
69274  return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
69275}
69276
69277
69278/*
69279** Each VDBE holds the result of the most recent sqlite3_step() call
69280** in p->rc.  This routine sets that result back to SQLITE_OK.
69281*/
69282SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
69283  p->rc = SQLITE_OK;
69284}
69285
69286/*
69287** Copy the error code and error message belonging to the VDBE passed
69288** as the first argument to its database handle (so that they will be
69289** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
69290**
69291** This function does not clear the VDBE error code or message, just
69292** copies them to the database handle.
69293*/
69294SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
69295  sqlite3 *db = p->db;
69296  int rc = p->rc;
69297  if( p->zErrMsg ){
69298    u8 mallocFailed = db->mallocFailed;
69299    sqlite3BeginBenignMalloc();
69300    if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
69301    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
69302    sqlite3EndBenignMalloc();
69303    db->mallocFailed = mallocFailed;
69304    db->errCode = rc;
69305  }else{
69306    sqlite3Error(db, rc);
69307  }
69308  return rc;
69309}
69310
69311#ifdef SQLITE_ENABLE_SQLLOG
69312/*
69313** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
69314** invoke it.
69315*/
69316static void vdbeInvokeSqllog(Vdbe *v){
69317  if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
69318    char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
69319    assert( v->db->init.busy==0 );
69320    if( zExpanded ){
69321      sqlite3GlobalConfig.xSqllog(
69322          sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
69323      );
69324      sqlite3DbFree(v->db, zExpanded);
69325    }
69326  }
69327}
69328#else
69329# define vdbeInvokeSqllog(x)
69330#endif
69331
69332/*
69333** Clean up a VDBE after execution but do not delete the VDBE just yet.
69334** Write any error messages into *pzErrMsg.  Return the result code.
69335**
69336** After this routine is run, the VDBE should be ready to be executed
69337** again.
69338**
69339** To look at it another way, this routine resets the state of the
69340** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
69341** VDBE_MAGIC_INIT.
69342*/
69343SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
69344  sqlite3 *db;
69345  db = p->db;
69346
69347  /* If the VM did not run to completion or if it encountered an
69348  ** error, then it might not have been halted properly.  So halt
69349  ** it now.
69350  */
69351  sqlite3VdbeHalt(p);
69352
69353  /* If the VDBE has be run even partially, then transfer the error code
69354  ** and error message from the VDBE into the main database structure.  But
69355  ** if the VDBE has just been set to run but has not actually executed any
69356  ** instructions yet, leave the main database error information unchanged.
69357  */
69358  if( p->pc>=0 ){
69359    vdbeInvokeSqllog(p);
69360    sqlite3VdbeTransferError(p);
69361    sqlite3DbFree(db, p->zErrMsg);
69362    p->zErrMsg = 0;
69363    if( p->runOnlyOnce ) p->expired = 1;
69364  }else if( p->rc && p->expired ){
69365    /* The expired flag was set on the VDBE before the first call
69366    ** to sqlite3_step(). For consistency (since sqlite3_step() was
69367    ** called), set the database error in this case as well.
69368    */
69369    sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
69370    sqlite3DbFree(db, p->zErrMsg);
69371    p->zErrMsg = 0;
69372  }
69373
69374  /* Reclaim all memory used by the VDBE
69375  */
69376  Cleanup(p);
69377
69378  /* Save profiling information from this VDBE run.
69379  */
69380#ifdef VDBE_PROFILE
69381  {
69382    FILE *out = fopen("vdbe_profile.out", "a");
69383    if( out ){
69384      int i;
69385      fprintf(out, "---- ");
69386      for(i=0; i<p->nOp; i++){
69387        fprintf(out, "%02x", p->aOp[i].opcode);
69388      }
69389      fprintf(out, "\n");
69390      if( p->zSql ){
69391        char c, pc = 0;
69392        fprintf(out, "-- ");
69393        for(i=0; (c = p->zSql[i])!=0; i++){
69394          if( pc=='\n' ) fprintf(out, "-- ");
69395          putc(c, out);
69396          pc = c;
69397        }
69398        if( pc!='\n' ) fprintf(out, "\n");
69399      }
69400      for(i=0; i<p->nOp; i++){
69401        char zHdr[100];
69402        sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
69403           p->aOp[i].cnt,
69404           p->aOp[i].cycles,
69405           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
69406        );
69407        fprintf(out, "%s", zHdr);
69408        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
69409      }
69410      fclose(out);
69411    }
69412  }
69413#endif
69414  p->iCurrentTime = 0;
69415  p->magic = VDBE_MAGIC_INIT;
69416  return p->rc & db->errMask;
69417}
69418
69419/*
69420** Clean up and delete a VDBE after execution.  Return an integer which is
69421** the result code.  Write any error message text into *pzErrMsg.
69422*/
69423SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
69424  int rc = SQLITE_OK;
69425  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
69426    rc = sqlite3VdbeReset(p);
69427    assert( (rc & p->db->errMask)==rc );
69428  }
69429  sqlite3VdbeDelete(p);
69430  return rc;
69431}
69432
69433/*
69434** If parameter iOp is less than zero, then invoke the destructor for
69435** all auxiliary data pointers currently cached by the VM passed as
69436** the first argument.
69437**
69438** Or, if iOp is greater than or equal to zero, then the destructor is
69439** only invoked for those auxiliary data pointers created by the user
69440** function invoked by the OP_Function opcode at instruction iOp of
69441** VM pVdbe, and only then if:
69442**
69443**    * the associated function parameter is the 32nd or later (counting
69444**      from left to right), or
69445**
69446**    * the corresponding bit in argument mask is clear (where the first
69447**      function parameter corresponds to bit 0 etc.).
69448*/
69449SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
69450  AuxData **pp = &pVdbe->pAuxData;
69451  while( *pp ){
69452    AuxData *pAux = *pp;
69453    if( (iOp<0)
69454     || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
69455    ){
69456      testcase( pAux->iArg==31 );
69457      if( pAux->xDelete ){
69458        pAux->xDelete(pAux->pAux);
69459      }
69460      *pp = pAux->pNext;
69461      sqlite3DbFree(pVdbe->db, pAux);
69462    }else{
69463      pp= &pAux->pNext;
69464    }
69465  }
69466}
69467
69468/*
69469** Free all memory associated with the Vdbe passed as the second argument,
69470** except for object itself, which is preserved.
69471**
69472** The difference between this function and sqlite3VdbeDelete() is that
69473** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
69474** the database connection and frees the object itself.
69475*/
69476SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
69477  SubProgram *pSub, *pNext;
69478  int i;
69479  assert( p->db==0 || p->db==db );
69480  releaseMemArray(p->aVar, p->nVar);
69481  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
69482  for(pSub=p->pProgram; pSub; pSub=pNext){
69483    pNext = pSub->pNext;
69484    vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
69485    sqlite3DbFree(db, pSub);
69486  }
69487  for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
69488  vdbeFreeOpArray(db, p->aOp, p->nOp);
69489  sqlite3DbFree(db, p->aColName);
69490  sqlite3DbFree(db, p->zSql);
69491  sqlite3DbFree(db, p->pFree);
69492#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
69493  for(i=0; i<p->nScan; i++){
69494    sqlite3DbFree(db, p->aScan[i].zName);
69495  }
69496  sqlite3DbFree(db, p->aScan);
69497#endif
69498}
69499
69500/*
69501** Delete an entire VDBE.
69502*/
69503SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
69504  sqlite3 *db;
69505
69506  if( NEVER(p==0) ) return;
69507  db = p->db;
69508  assert( sqlite3_mutex_held(db->mutex) );
69509  sqlite3VdbeClearObject(db, p);
69510  if( p->pPrev ){
69511    p->pPrev->pNext = p->pNext;
69512  }else{
69513    assert( db->pVdbe==p );
69514    db->pVdbe = p->pNext;
69515  }
69516  if( p->pNext ){
69517    p->pNext->pPrev = p->pPrev;
69518  }
69519  p->magic = VDBE_MAGIC_DEAD;
69520  p->db = 0;
69521  sqlite3DbFree(db, p);
69522}
69523
69524/*
69525** The cursor "p" has a pending seek operation that has not yet been
69526** carried out.  Seek the cursor now.  If an error occurs, return
69527** the appropriate error code.
69528*/
69529static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
69530  int res, rc;
69531#ifdef SQLITE_TEST
69532  extern int sqlite3_search_count;
69533#endif
69534  assert( p->deferredMoveto );
69535  assert( p->isTable );
69536  rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
69537  if( rc ) return rc;
69538  if( res!=0 ) return SQLITE_CORRUPT_BKPT;
69539#ifdef SQLITE_TEST
69540  sqlite3_search_count++;
69541#endif
69542  p->deferredMoveto = 0;
69543  p->cacheStatus = CACHE_STALE;
69544  return SQLITE_OK;
69545}
69546
69547/*
69548** Something has moved cursor "p" out of place.  Maybe the row it was
69549** pointed to was deleted out from under it.  Or maybe the btree was
69550** rebalanced.  Whatever the cause, try to restore "p" to the place it
69551** is supposed to be pointing.  If the row was deleted out from under the
69552** cursor, set the cursor to point to a NULL row.
69553*/
69554static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
69555  int isDifferentRow, rc;
69556  assert( p->pCursor!=0 );
69557  assert( sqlite3BtreeCursorHasMoved(p->pCursor) );
69558  rc = sqlite3BtreeCursorRestore(p->pCursor, &isDifferentRow);
69559  p->cacheStatus = CACHE_STALE;
69560  if( isDifferentRow ) p->nullRow = 1;
69561  return rc;
69562}
69563
69564/*
69565** Check to ensure that the cursor is valid.  Restore the cursor
69566** if need be.  Return any I/O error from the restore operation.
69567*/
69568SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
69569  if( sqlite3BtreeCursorHasMoved(p->pCursor) ){
69570    return handleMovedCursor(p);
69571  }
69572  return SQLITE_OK;
69573}
69574
69575/*
69576** Make sure the cursor p is ready to read or write the row to which it
69577** was last positioned.  Return an error code if an OOM fault or I/O error
69578** prevents us from positioning the cursor to its correct position.
69579**
69580** If a MoveTo operation is pending on the given cursor, then do that
69581** MoveTo now.  If no move is pending, check to see if the row has been
69582** deleted out from under the cursor and if it has, mark the row as
69583** a NULL row.
69584**
69585** If the cursor is already pointing to the correct row and that row has
69586** not been deleted out from under the cursor, then this routine is a no-op.
69587*/
69588SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
69589  if( p->deferredMoveto ){
69590    return handleDeferredMoveto(p);
69591  }
69592  if( p->pCursor && sqlite3BtreeCursorHasMoved(p->pCursor) ){
69593    return handleMovedCursor(p);
69594  }
69595  return SQLITE_OK;
69596}
69597
69598/*
69599** The following functions:
69600**
69601** sqlite3VdbeSerialType()
69602** sqlite3VdbeSerialTypeLen()
69603** sqlite3VdbeSerialLen()
69604** sqlite3VdbeSerialPut()
69605** sqlite3VdbeSerialGet()
69606**
69607** encapsulate the code that serializes values for storage in SQLite
69608** data and index records. Each serialized value consists of a
69609** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
69610** integer, stored as a varint.
69611**
69612** In an SQLite index record, the serial type is stored directly before
69613** the blob of data that it corresponds to. In a table record, all serial
69614** types are stored at the start of the record, and the blobs of data at
69615** the end. Hence these functions allow the caller to handle the
69616** serial-type and data blob separately.
69617**
69618** The following table describes the various storage classes for data:
69619**
69620**   serial type        bytes of data      type
69621**   --------------     ---------------    ---------------
69622**      0                     0            NULL
69623**      1                     1            signed integer
69624**      2                     2            signed integer
69625**      3                     3            signed integer
69626**      4                     4            signed integer
69627**      5                     6            signed integer
69628**      6                     8            signed integer
69629**      7                     8            IEEE float
69630**      8                     0            Integer constant 0
69631**      9                     0            Integer constant 1
69632**     10,11                               reserved for expansion
69633**    N>=12 and even       (N-12)/2        BLOB
69634**    N>=13 and odd        (N-13)/2        text
69635**
69636** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
69637** of SQLite will not understand those serial types.
69638*/
69639
69640/*
69641** Return the serial-type for the value stored in pMem.
69642*/
69643SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
69644  int flags = pMem->flags;
69645  u32 n;
69646
69647  if( flags&MEM_Null ){
69648    return 0;
69649  }
69650  if( flags&MEM_Int ){
69651    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
69652#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
69653    i64 i = pMem->u.i;
69654    u64 u;
69655    if( i<0 ){
69656      u = ~i;
69657    }else{
69658      u = i;
69659    }
69660    if( u<=127 ){
69661      return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
69662    }
69663    if( u<=32767 ) return 2;
69664    if( u<=8388607 ) return 3;
69665    if( u<=2147483647 ) return 4;
69666    if( u<=MAX_6BYTE ) return 5;
69667    return 6;
69668  }
69669  if( flags&MEM_Real ){
69670    return 7;
69671  }
69672  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
69673  assert( pMem->n>=0 );
69674  n = (u32)pMem->n;
69675  if( flags & MEM_Zero ){
69676    n += pMem->u.nZero;
69677  }
69678  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
69679}
69680
69681/*
69682** The sizes for serial types less than 12
69683*/
69684static const u8 sqlite3SmallTypeSizes[] = {
69685  0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0
69686};
69687
69688/*
69689** Return the length of the data corresponding to the supplied serial-type.
69690*/
69691SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
69692  if( serial_type>=12 ){
69693    return (serial_type-12)/2;
69694  }else{
69695    return sqlite3SmallTypeSizes[serial_type];
69696  }
69697}
69698
69699/*
69700** If we are on an architecture with mixed-endian floating
69701** points (ex: ARM7) then swap the lower 4 bytes with the
69702** upper 4 bytes.  Return the result.
69703**
69704** For most architectures, this is a no-op.
69705**
69706** (later):  It is reported to me that the mixed-endian problem
69707** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
69708** that early versions of GCC stored the two words of a 64-bit
69709** float in the wrong order.  And that error has been propagated
69710** ever since.  The blame is not necessarily with GCC, though.
69711** GCC might have just copying the problem from a prior compiler.
69712** I am also told that newer versions of GCC that follow a different
69713** ABI get the byte order right.
69714**
69715** Developers using SQLite on an ARM7 should compile and run their
69716** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
69717** enabled, some asserts below will ensure that the byte order of
69718** floating point values is correct.
69719**
69720** (2007-08-30)  Frank van Vugt has studied this problem closely
69721** and has send his findings to the SQLite developers.  Frank
69722** writes that some Linux kernels offer floating point hardware
69723** emulation that uses only 32-bit mantissas instead of a full
69724** 48-bits as required by the IEEE standard.  (This is the
69725** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
69726** byte swapping becomes very complicated.  To avoid problems,
69727** the necessary byte swapping is carried out using a 64-bit integer
69728** rather than a 64-bit float.  Frank assures us that the code here
69729** works for him.  We, the developers, have no way to independently
69730** verify this, but Frank seems to know what he is talking about
69731** so we trust him.
69732*/
69733#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
69734static u64 floatSwap(u64 in){
69735  union {
69736    u64 r;
69737    u32 i[2];
69738  } u;
69739  u32 t;
69740
69741  u.r = in;
69742  t = u.i[0];
69743  u.i[0] = u.i[1];
69744  u.i[1] = t;
69745  return u.r;
69746}
69747# define swapMixedEndianFloat(X)  X = floatSwap(X)
69748#else
69749# define swapMixedEndianFloat(X)
69750#endif
69751
69752/*
69753** Write the serialized data blob for the value stored in pMem into
69754** buf. It is assumed that the caller has allocated sufficient space.
69755** Return the number of bytes written.
69756**
69757** nBuf is the amount of space left in buf[].  The caller is responsible
69758** for allocating enough space to buf[] to hold the entire field, exclusive
69759** of the pMem->u.nZero bytes for a MEM_Zero value.
69760**
69761** Return the number of bytes actually written into buf[].  The number
69762** of bytes in the zero-filled tail is included in the return value only
69763** if those bytes were zeroed in buf[].
69764*/
69765SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
69766  u32 len;
69767
69768  /* Integer and Real */
69769  if( serial_type<=7 && serial_type>0 ){
69770    u64 v;
69771    u32 i;
69772    if( serial_type==7 ){
69773      assert( sizeof(v)==sizeof(pMem->u.r) );
69774      memcpy(&v, &pMem->u.r, sizeof(v));
69775      swapMixedEndianFloat(v);
69776    }else{
69777      v = pMem->u.i;
69778    }
69779    len = i = sqlite3SmallTypeSizes[serial_type];
69780    assert( i>0 );
69781    do{
69782      buf[--i] = (u8)(v&0xFF);
69783      v >>= 8;
69784    }while( i );
69785    return len;
69786  }
69787
69788  /* String or blob */
69789  if( serial_type>=12 ){
69790    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
69791             == (int)sqlite3VdbeSerialTypeLen(serial_type) );
69792    len = pMem->n;
69793    memcpy(buf, pMem->z, len);
69794    return len;
69795  }
69796
69797  /* NULL or constants 0 or 1 */
69798  return 0;
69799}
69800
69801/* Input "x" is a sequence of unsigned characters that represent a
69802** big-endian integer.  Return the equivalent native integer
69803*/
69804#define ONE_BYTE_INT(x)    ((i8)(x)[0])
69805#define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
69806#define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
69807#define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
69808#define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
69809
69810/*
69811** Deserialize the data blob pointed to by buf as serial type serial_type
69812** and store the result in pMem.  Return the number of bytes read.
69813**
69814** This function is implemented as two separate routines for performance.
69815** The few cases that require local variables are broken out into a separate
69816** routine so that in most cases the overhead of moving the stack pointer
69817** is avoided.
69818*/
69819static u32 SQLITE_NOINLINE serialGet(
69820  const unsigned char *buf,     /* Buffer to deserialize from */
69821  u32 serial_type,              /* Serial type to deserialize */
69822  Mem *pMem                     /* Memory cell to write value into */
69823){
69824  u64 x = FOUR_BYTE_UINT(buf);
69825  u32 y = FOUR_BYTE_UINT(buf+4);
69826  x = (x<<32) + y;
69827  if( serial_type==6 ){
69828    /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
69829    ** twos-complement integer. */
69830    pMem->u.i = *(i64*)&x;
69831    pMem->flags = MEM_Int;
69832    testcase( pMem->u.i<0 );
69833  }else{
69834    /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
69835    ** floating point number. */
69836#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
69837    /* Verify that integers and floating point values use the same
69838    ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
69839    ** defined that 64-bit floating point values really are mixed
69840    ** endian.
69841    */
69842    static const u64 t1 = ((u64)0x3ff00000)<<32;
69843    static const double r1 = 1.0;
69844    u64 t2 = t1;
69845    swapMixedEndianFloat(t2);
69846    assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
69847#endif
69848    assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
69849    swapMixedEndianFloat(x);
69850    memcpy(&pMem->u.r, &x, sizeof(x));
69851    pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
69852  }
69853  return 8;
69854}
69855SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
69856  const unsigned char *buf,     /* Buffer to deserialize from */
69857  u32 serial_type,              /* Serial type to deserialize */
69858  Mem *pMem                     /* Memory cell to write value into */
69859){
69860  switch( serial_type ){
69861    case 10:   /* Reserved for future use */
69862    case 11:   /* Reserved for future use */
69863    case 0: {  /* Null */
69864      /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
69865      pMem->flags = MEM_Null;
69866      break;
69867    }
69868    case 1: {
69869      /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
69870      ** integer. */
69871      pMem->u.i = ONE_BYTE_INT(buf);
69872      pMem->flags = MEM_Int;
69873      testcase( pMem->u.i<0 );
69874      return 1;
69875    }
69876    case 2: { /* 2-byte signed integer */
69877      /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
69878      ** twos-complement integer. */
69879      pMem->u.i = TWO_BYTE_INT(buf);
69880      pMem->flags = MEM_Int;
69881      testcase( pMem->u.i<0 );
69882      return 2;
69883    }
69884    case 3: { /* 3-byte signed integer */
69885      /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
69886      ** twos-complement integer. */
69887      pMem->u.i = THREE_BYTE_INT(buf);
69888      pMem->flags = MEM_Int;
69889      testcase( pMem->u.i<0 );
69890      return 3;
69891    }
69892    case 4: { /* 4-byte signed integer */
69893      /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
69894      ** twos-complement integer. */
69895      pMem->u.i = FOUR_BYTE_INT(buf);
69896      pMem->flags = MEM_Int;
69897      testcase( pMem->u.i<0 );
69898      return 4;
69899    }
69900    case 5: { /* 6-byte signed integer */
69901      /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
69902      ** twos-complement integer. */
69903      pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
69904      pMem->flags = MEM_Int;
69905      testcase( pMem->u.i<0 );
69906      return 6;
69907    }
69908    case 6:   /* 8-byte signed integer */
69909    case 7: { /* IEEE floating point */
69910      /* These use local variables, so do them in a separate routine
69911      ** to avoid having to move the frame pointer in the common case */
69912      return serialGet(buf,serial_type,pMem);
69913    }
69914    case 8:    /* Integer 0 */
69915    case 9: {  /* Integer 1 */
69916      /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
69917      /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
69918      pMem->u.i = serial_type-8;
69919      pMem->flags = MEM_Int;
69920      return 0;
69921    }
69922    default: {
69923      /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
69924      ** length.
69925      ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
69926      ** (N-13)/2 bytes in length. */
69927      static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
69928      pMem->z = (char *)buf;
69929      pMem->n = (serial_type-12)/2;
69930      pMem->flags = aFlag[serial_type&1];
69931      return pMem->n;
69932    }
69933  }
69934  return 0;
69935}
69936/*
69937** This routine is used to allocate sufficient space for an UnpackedRecord
69938** structure large enough to be used with sqlite3VdbeRecordUnpack() if
69939** the first argument is a pointer to KeyInfo structure pKeyInfo.
69940**
69941** The space is either allocated using sqlite3DbMallocRaw() or from within
69942** the unaligned buffer passed via the second and third arguments (presumably
69943** stack space). If the former, then *ppFree is set to a pointer that should
69944** be eventually freed by the caller using sqlite3DbFree(). Or, if the
69945** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
69946** before returning.
69947**
69948** If an OOM error occurs, NULL is returned.
69949*/
69950SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
69951  KeyInfo *pKeyInfo,              /* Description of the record */
69952  char *pSpace,                   /* Unaligned space available */
69953  int szSpace,                    /* Size of pSpace[] in bytes */
69954  char **ppFree                   /* OUT: Caller should free this pointer */
69955){
69956  UnpackedRecord *p;              /* Unpacked record to return */
69957  int nOff;                       /* Increment pSpace by nOff to align it */
69958  int nByte;                      /* Number of bytes required for *p */
69959
69960  /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
69961  ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
69962  ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
69963  */
69964  nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
69965  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
69966  if( nByte>szSpace+nOff ){
69967    p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
69968    *ppFree = (char *)p;
69969    if( !p ) return 0;
69970  }else{
69971    p = (UnpackedRecord*)&pSpace[nOff];
69972    *ppFree = 0;
69973  }
69974
69975  p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
69976  assert( pKeyInfo->aSortOrder!=0 );
69977  p->pKeyInfo = pKeyInfo;
69978  p->nField = pKeyInfo->nField + 1;
69979  return p;
69980}
69981
69982/*
69983** Given the nKey-byte encoding of a record in pKey[], populate the
69984** UnpackedRecord structure indicated by the fourth argument with the
69985** contents of the decoded record.
69986*/
69987SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
69988  KeyInfo *pKeyInfo,     /* Information about the record format */
69989  int nKey,              /* Size of the binary record */
69990  const void *pKey,      /* The binary record */
69991  UnpackedRecord *p      /* Populate this structure before returning. */
69992){
69993  const unsigned char *aKey = (const unsigned char *)pKey;
69994  int d;
69995  u32 idx;                        /* Offset in aKey[] to read from */
69996  u16 u;                          /* Unsigned loop counter */
69997  u32 szHdr;
69998  Mem *pMem = p->aMem;
69999
70000  p->default_rc = 0;
70001  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
70002  idx = getVarint32(aKey, szHdr);
70003  d = szHdr;
70004  u = 0;
70005  while( idx<szHdr && d<=nKey ){
70006    u32 serial_type;
70007
70008    idx += getVarint32(&aKey[idx], serial_type);
70009    pMem->enc = pKeyInfo->enc;
70010    pMem->db = pKeyInfo->db;
70011    /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
70012    pMem->szMalloc = 0;
70013    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
70014    pMem++;
70015    if( (++u)>=p->nField ) break;
70016  }
70017  assert( u<=pKeyInfo->nField + 1 );
70018  p->nField = u;
70019}
70020
70021#if SQLITE_DEBUG
70022/*
70023** This function compares two index or table record keys in the same way
70024** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
70025** this function deserializes and compares values using the
70026** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
70027** in assert() statements to ensure that the optimized code in
70028** sqlite3VdbeRecordCompare() returns results with these two primitives.
70029**
70030** Return true if the result of comparison is equivalent to desiredResult.
70031** Return false if there is a disagreement.
70032*/
70033static int vdbeRecordCompareDebug(
70034  int nKey1, const void *pKey1, /* Left key */
70035  const UnpackedRecord *pPKey2, /* Right key */
70036  int desiredResult             /* Correct answer */
70037){
70038  u32 d1;            /* Offset into aKey[] of next data element */
70039  u32 idx1;          /* Offset into aKey[] of next header element */
70040  u32 szHdr1;        /* Number of bytes in header */
70041  int i = 0;
70042  int rc = 0;
70043  const unsigned char *aKey1 = (const unsigned char *)pKey1;
70044  KeyInfo *pKeyInfo;
70045  Mem mem1;
70046
70047  pKeyInfo = pPKey2->pKeyInfo;
70048  if( pKeyInfo->db==0 ) return 1;
70049  mem1.enc = pKeyInfo->enc;
70050  mem1.db = pKeyInfo->db;
70051  /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
70052  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
70053
70054  /* Compilers may complain that mem1.u.i is potentially uninitialized.
70055  ** We could initialize it, as shown here, to silence those complaints.
70056  ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
70057  ** the unnecessary initialization has a measurable negative performance
70058  ** impact, since this routine is a very high runner.  And so, we choose
70059  ** to ignore the compiler warnings and leave this variable uninitialized.
70060  */
70061  /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
70062
70063  idx1 = getVarint32(aKey1, szHdr1);
70064  if( szHdr1>98307 ) return SQLITE_CORRUPT;
70065  d1 = szHdr1;
70066  assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
70067  assert( pKeyInfo->aSortOrder!=0 );
70068  assert( pKeyInfo->nField>0 );
70069  assert( idx1<=szHdr1 || CORRUPT_DB );
70070  do{
70071    u32 serial_type1;
70072
70073    /* Read the serial types for the next element in each key. */
70074    idx1 += getVarint32( aKey1+idx1, serial_type1 );
70075
70076    /* Verify that there is enough key space remaining to avoid
70077    ** a buffer overread.  The "d1+serial_type1+2" subexpression will
70078    ** always be greater than or equal to the amount of required key space.
70079    ** Use that approximation to avoid the more expensive call to
70080    ** sqlite3VdbeSerialTypeLen() in the common case.
70081    */
70082    if( d1+serial_type1+2>(u32)nKey1
70083     && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
70084    ){
70085      break;
70086    }
70087
70088    /* Extract the values to be compared.
70089    */
70090    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
70091
70092    /* Do the comparison
70093    */
70094    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
70095    if( rc!=0 ){
70096      assert( mem1.szMalloc==0 );  /* See comment below */
70097      if( pKeyInfo->aSortOrder[i] ){
70098        rc = -rc;  /* Invert the result for DESC sort order. */
70099      }
70100      goto debugCompareEnd;
70101    }
70102    i++;
70103  }while( idx1<szHdr1 && i<pPKey2->nField );
70104
70105  /* No memory allocation is ever used on mem1.  Prove this using
70106  ** the following assert().  If the assert() fails, it indicates a
70107  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
70108  */
70109  assert( mem1.szMalloc==0 );
70110
70111  /* rc==0 here means that one of the keys ran out of fields and
70112  ** all the fields up to that point were equal. Return the default_rc
70113  ** value.  */
70114  rc = pPKey2->default_rc;
70115
70116debugCompareEnd:
70117  if( desiredResult==0 && rc==0 ) return 1;
70118  if( desiredResult<0 && rc<0 ) return 1;
70119  if( desiredResult>0 && rc>0 ) return 1;
70120  if( CORRUPT_DB ) return 1;
70121  if( pKeyInfo->db->mallocFailed ) return 1;
70122  return 0;
70123}
70124#endif
70125
70126#if SQLITE_DEBUG
70127/*
70128** Count the number of fields (a.k.a. columns) in the record given by
70129** pKey,nKey.  The verify that this count is less than or equal to the
70130** limit given by pKeyInfo->nField + pKeyInfo->nXField.
70131**
70132** If this constraint is not satisfied, it means that the high-speed
70133** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
70134** not work correctly.  If this assert() ever fires, it probably means
70135** that the KeyInfo.nField or KeyInfo.nXField values were computed
70136** incorrectly.
70137*/
70138static void vdbeAssertFieldCountWithinLimits(
70139  int nKey, const void *pKey,   /* The record to verify */
70140  const KeyInfo *pKeyInfo       /* Compare size with this KeyInfo */
70141){
70142  int nField = 0;
70143  u32 szHdr;
70144  u32 idx;
70145  u32 notUsed;
70146  const unsigned char *aKey = (const unsigned char*)pKey;
70147
70148  if( CORRUPT_DB ) return;
70149  idx = getVarint32(aKey, szHdr);
70150  assert( nKey>=0 );
70151  assert( szHdr<=(u32)nKey );
70152  while( idx<szHdr ){
70153    idx += getVarint32(aKey+idx, notUsed);
70154    nField++;
70155  }
70156  assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
70157}
70158#else
70159# define vdbeAssertFieldCountWithinLimits(A,B,C)
70160#endif
70161
70162/*
70163** Both *pMem1 and *pMem2 contain string values. Compare the two values
70164** using the collation sequence pColl. As usual, return a negative , zero
70165** or positive value if *pMem1 is less than, equal to or greater than
70166** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
70167*/
70168static int vdbeCompareMemString(
70169  const Mem *pMem1,
70170  const Mem *pMem2,
70171  const CollSeq *pColl,
70172  u8 *prcErr                      /* If an OOM occurs, set to SQLITE_NOMEM */
70173){
70174  if( pMem1->enc==pColl->enc ){
70175    /* The strings are already in the correct encoding.  Call the
70176     ** comparison function directly */
70177    return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
70178  }else{
70179    int rc;
70180    const void *v1, *v2;
70181    int n1, n2;
70182    Mem c1;
70183    Mem c2;
70184    sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
70185    sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
70186    sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
70187    sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
70188    v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
70189    n1 = v1==0 ? 0 : c1.n;
70190    v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
70191    n2 = v2==0 ? 0 : c2.n;
70192    rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
70193    sqlite3VdbeMemRelease(&c1);
70194    sqlite3VdbeMemRelease(&c2);
70195    if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM;
70196    return rc;
70197  }
70198}
70199
70200/*
70201** Compare two blobs.  Return negative, zero, or positive if the first
70202** is less than, equal to, or greater than the second, respectively.
70203** If one blob is a prefix of the other, then the shorter is the lessor.
70204*/
70205static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
70206  int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
70207  if( c ) return c;
70208  return pB1->n - pB2->n;
70209}
70210
70211
70212/*
70213** Compare the values contained by the two memory cells, returning
70214** negative, zero or positive if pMem1 is less than, equal to, or greater
70215** than pMem2. Sorting order is NULL's first, followed by numbers (integers
70216** and reals) sorted numerically, followed by text ordered by the collating
70217** sequence pColl and finally blob's ordered by memcmp().
70218**
70219** Two NULL values are considered equal by this function.
70220*/
70221SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
70222  int f1, f2;
70223  int combined_flags;
70224
70225  f1 = pMem1->flags;
70226  f2 = pMem2->flags;
70227  combined_flags = f1|f2;
70228  assert( (combined_flags & MEM_RowSet)==0 );
70229
70230  /* If one value is NULL, it is less than the other. If both values
70231  ** are NULL, return 0.
70232  */
70233  if( combined_flags&MEM_Null ){
70234    return (f2&MEM_Null) - (f1&MEM_Null);
70235  }
70236
70237  /* If one value is a number and the other is not, the number is less.
70238  ** If both are numbers, compare as reals if one is a real, or as integers
70239  ** if both values are integers.
70240  */
70241  if( combined_flags&(MEM_Int|MEM_Real) ){
70242    double r1, r2;
70243    if( (f1 & f2 & MEM_Int)!=0 ){
70244      if( pMem1->u.i < pMem2->u.i ) return -1;
70245      if( pMem1->u.i > pMem2->u.i ) return 1;
70246      return 0;
70247    }
70248    if( (f1&MEM_Real)!=0 ){
70249      r1 = pMem1->u.r;
70250    }else if( (f1&MEM_Int)!=0 ){
70251      r1 = (double)pMem1->u.i;
70252    }else{
70253      return 1;
70254    }
70255    if( (f2&MEM_Real)!=0 ){
70256      r2 = pMem2->u.r;
70257    }else if( (f2&MEM_Int)!=0 ){
70258      r2 = (double)pMem2->u.i;
70259    }else{
70260      return -1;
70261    }
70262    if( r1<r2 ) return -1;
70263    if( r1>r2 ) return 1;
70264    return 0;
70265  }
70266
70267  /* If one value is a string and the other is a blob, the string is less.
70268  ** If both are strings, compare using the collating functions.
70269  */
70270  if( combined_flags&MEM_Str ){
70271    if( (f1 & MEM_Str)==0 ){
70272      return 1;
70273    }
70274    if( (f2 & MEM_Str)==0 ){
70275      return -1;
70276    }
70277
70278    assert( pMem1->enc==pMem2->enc );
70279    assert( pMem1->enc==SQLITE_UTF8 ||
70280            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
70281
70282    /* The collation sequence must be defined at this point, even if
70283    ** the user deletes the collation sequence after the vdbe program is
70284    ** compiled (this was not always the case).
70285    */
70286    assert( !pColl || pColl->xCmp );
70287
70288    if( pColl ){
70289      return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
70290    }
70291    /* If a NULL pointer was passed as the collate function, fall through
70292    ** to the blob case and use memcmp().  */
70293  }
70294
70295  /* Both values must be blobs.  Compare using memcmp().  */
70296  return sqlite3BlobCompare(pMem1, pMem2);
70297}
70298
70299
70300/*
70301** The first argument passed to this function is a serial-type that
70302** corresponds to an integer - all values between 1 and 9 inclusive
70303** except 7. The second points to a buffer containing an integer value
70304** serialized according to serial_type. This function deserializes
70305** and returns the value.
70306*/
70307static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
70308  u32 y;
70309  assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
70310  switch( serial_type ){
70311    case 0:
70312    case 1:
70313      testcase( aKey[0]&0x80 );
70314      return ONE_BYTE_INT(aKey);
70315    case 2:
70316      testcase( aKey[0]&0x80 );
70317      return TWO_BYTE_INT(aKey);
70318    case 3:
70319      testcase( aKey[0]&0x80 );
70320      return THREE_BYTE_INT(aKey);
70321    case 4: {
70322      testcase( aKey[0]&0x80 );
70323      y = FOUR_BYTE_UINT(aKey);
70324      return (i64)*(int*)&y;
70325    }
70326    case 5: {
70327      testcase( aKey[0]&0x80 );
70328      return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
70329    }
70330    case 6: {
70331      u64 x = FOUR_BYTE_UINT(aKey);
70332      testcase( aKey[0]&0x80 );
70333      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
70334      return (i64)*(i64*)&x;
70335    }
70336  }
70337
70338  return (serial_type - 8);
70339}
70340
70341/*
70342** This function compares the two table rows or index records
70343** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
70344** or positive integer if key1 is less than, equal to or
70345** greater than key2.  The {nKey1, pKey1} key must be a blob
70346** created by the OP_MakeRecord opcode of the VDBE.  The pPKey2
70347** key must be a parsed key such as obtained from
70348** sqlite3VdbeParseRecord.
70349**
70350** If argument bSkip is non-zero, it is assumed that the caller has already
70351** determined that the first fields of the keys are equal.
70352**
70353** Key1 and Key2 do not have to contain the same number of fields. If all
70354** fields that appear in both keys are equal, then pPKey2->default_rc is
70355** returned.
70356**
70357** If database corruption is discovered, set pPKey2->errCode to
70358** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
70359** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
70360** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
70361*/
70362SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
70363  int nKey1, const void *pKey1,   /* Left key */
70364  UnpackedRecord *pPKey2,         /* Right key */
70365  int bSkip                       /* If true, skip the first field */
70366){
70367  u32 d1;                         /* Offset into aKey[] of next data element */
70368  int i;                          /* Index of next field to compare */
70369  u32 szHdr1;                     /* Size of record header in bytes */
70370  u32 idx1;                       /* Offset of first type in header */
70371  int rc = 0;                     /* Return value */
70372  Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
70373  KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
70374  const unsigned char *aKey1 = (const unsigned char *)pKey1;
70375  Mem mem1;
70376
70377  /* If bSkip is true, then the caller has already determined that the first
70378  ** two elements in the keys are equal. Fix the various stack variables so
70379  ** that this routine begins comparing at the second field. */
70380  if( bSkip ){
70381    u32 s1;
70382    idx1 = 1 + getVarint32(&aKey1[1], s1);
70383    szHdr1 = aKey1[0];
70384    d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
70385    i = 1;
70386    pRhs++;
70387  }else{
70388    idx1 = getVarint32(aKey1, szHdr1);
70389    d1 = szHdr1;
70390    if( d1>(unsigned)nKey1 ){
70391      pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
70392      return 0;  /* Corruption */
70393    }
70394    i = 0;
70395  }
70396
70397  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
70398  assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
70399       || CORRUPT_DB );
70400  assert( pPKey2->pKeyInfo->aSortOrder!=0 );
70401  assert( pPKey2->pKeyInfo->nField>0 );
70402  assert( idx1<=szHdr1 || CORRUPT_DB );
70403  do{
70404    u32 serial_type;
70405
70406    /* RHS is an integer */
70407    if( pRhs->flags & MEM_Int ){
70408      serial_type = aKey1[idx1];
70409      testcase( serial_type==12 );
70410      if( serial_type>=10 ){
70411        rc = +1;
70412      }else if( serial_type==0 ){
70413        rc = -1;
70414      }else if( serial_type==7 ){
70415        double rhs = (double)pRhs->u.i;
70416        sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
70417        if( mem1.u.r<rhs ){
70418          rc = -1;
70419        }else if( mem1.u.r>rhs ){
70420          rc = +1;
70421        }
70422      }else{
70423        i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
70424        i64 rhs = pRhs->u.i;
70425        if( lhs<rhs ){
70426          rc = -1;
70427        }else if( lhs>rhs ){
70428          rc = +1;
70429        }
70430      }
70431    }
70432
70433    /* RHS is real */
70434    else if( pRhs->flags & MEM_Real ){
70435      serial_type = aKey1[idx1];
70436      if( serial_type>=10 ){
70437        /* Serial types 12 or greater are strings and blobs (greater than
70438        ** numbers). Types 10 and 11 are currently "reserved for future
70439        ** use", so it doesn't really matter what the results of comparing
70440        ** them to numberic values are.  */
70441        rc = +1;
70442      }else if( serial_type==0 ){
70443        rc = -1;
70444      }else{
70445        double rhs = pRhs->u.r;
70446        double lhs;
70447        sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
70448        if( serial_type==7 ){
70449          lhs = mem1.u.r;
70450        }else{
70451          lhs = (double)mem1.u.i;
70452        }
70453        if( lhs<rhs ){
70454          rc = -1;
70455        }else if( lhs>rhs ){
70456          rc = +1;
70457        }
70458      }
70459    }
70460
70461    /* RHS is a string */
70462    else if( pRhs->flags & MEM_Str ){
70463      getVarint32(&aKey1[idx1], serial_type);
70464      testcase( serial_type==12 );
70465      if( serial_type<12 ){
70466        rc = -1;
70467      }else if( !(serial_type & 0x01) ){
70468        rc = +1;
70469      }else{
70470        mem1.n = (serial_type - 12) / 2;
70471        testcase( (d1+mem1.n)==(unsigned)nKey1 );
70472        testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
70473        if( (d1+mem1.n) > (unsigned)nKey1 ){
70474          pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
70475          return 0;                /* Corruption */
70476        }else if( pKeyInfo->aColl[i] ){
70477          mem1.enc = pKeyInfo->enc;
70478          mem1.db = pKeyInfo->db;
70479          mem1.flags = MEM_Str;
70480          mem1.z = (char*)&aKey1[d1];
70481          rc = vdbeCompareMemString(
70482              &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
70483          );
70484        }else{
70485          int nCmp = MIN(mem1.n, pRhs->n);
70486          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
70487          if( rc==0 ) rc = mem1.n - pRhs->n;
70488        }
70489      }
70490    }
70491
70492    /* RHS is a blob */
70493    else if( pRhs->flags & MEM_Blob ){
70494      getVarint32(&aKey1[idx1], serial_type);
70495      testcase( serial_type==12 );
70496      if( serial_type<12 || (serial_type & 0x01) ){
70497        rc = -1;
70498      }else{
70499        int nStr = (serial_type - 12) / 2;
70500        testcase( (d1+nStr)==(unsigned)nKey1 );
70501        testcase( (d1+nStr+1)==(unsigned)nKey1 );
70502        if( (d1+nStr) > (unsigned)nKey1 ){
70503          pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
70504          return 0;                /* Corruption */
70505        }else{
70506          int nCmp = MIN(nStr, pRhs->n);
70507          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
70508          if( rc==0 ) rc = nStr - pRhs->n;
70509        }
70510      }
70511    }
70512
70513    /* RHS is null */
70514    else{
70515      serial_type = aKey1[idx1];
70516      rc = (serial_type!=0);
70517    }
70518
70519    if( rc!=0 ){
70520      if( pKeyInfo->aSortOrder[i] ){
70521        rc = -rc;
70522      }
70523      assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
70524      assert( mem1.szMalloc==0 );  /* See comment below */
70525      return rc;
70526    }
70527
70528    i++;
70529    pRhs++;
70530    d1 += sqlite3VdbeSerialTypeLen(serial_type);
70531    idx1 += sqlite3VarintLen(serial_type);
70532  }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
70533
70534  /* No memory allocation is ever used on mem1.  Prove this using
70535  ** the following assert().  If the assert() fails, it indicates a
70536  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
70537  assert( mem1.szMalloc==0 );
70538
70539  /* rc==0 here means that one or both of the keys ran out of fields and
70540  ** all the fields up to that point were equal. Return the default_rc
70541  ** value.  */
70542  assert( CORRUPT_DB
70543       || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
70544       || pKeyInfo->db->mallocFailed
70545  );
70546  return pPKey2->default_rc;
70547}
70548SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
70549  int nKey1, const void *pKey1,   /* Left key */
70550  UnpackedRecord *pPKey2          /* Right key */
70551){
70552  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
70553}
70554
70555
70556/*
70557** This function is an optimized version of sqlite3VdbeRecordCompare()
70558** that (a) the first field of pPKey2 is an integer, and (b) the
70559** size-of-header varint at the start of (pKey1/nKey1) fits in a single
70560** byte (i.e. is less than 128).
70561**
70562** To avoid concerns about buffer overreads, this routine is only used
70563** on schemas where the maximum valid header size is 63 bytes or less.
70564*/
70565static int vdbeRecordCompareInt(
70566  int nKey1, const void *pKey1, /* Left key */
70567  UnpackedRecord *pPKey2        /* Right key */
70568){
70569  const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
70570  int serial_type = ((const u8*)pKey1)[1];
70571  int res;
70572  u32 y;
70573  u64 x;
70574  i64 v = pPKey2->aMem[0].u.i;
70575  i64 lhs;
70576
70577  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
70578  assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
70579  switch( serial_type ){
70580    case 1: { /* 1-byte signed integer */
70581      lhs = ONE_BYTE_INT(aKey);
70582      testcase( lhs<0 );
70583      break;
70584    }
70585    case 2: { /* 2-byte signed integer */
70586      lhs = TWO_BYTE_INT(aKey);
70587      testcase( lhs<0 );
70588      break;
70589    }
70590    case 3: { /* 3-byte signed integer */
70591      lhs = THREE_BYTE_INT(aKey);
70592      testcase( lhs<0 );
70593      break;
70594    }
70595    case 4: { /* 4-byte signed integer */
70596      y = FOUR_BYTE_UINT(aKey);
70597      lhs = (i64)*(int*)&y;
70598      testcase( lhs<0 );
70599      break;
70600    }
70601    case 5: { /* 6-byte signed integer */
70602      lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
70603      testcase( lhs<0 );
70604      break;
70605    }
70606    case 6: { /* 8-byte signed integer */
70607      x = FOUR_BYTE_UINT(aKey);
70608      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
70609      lhs = *(i64*)&x;
70610      testcase( lhs<0 );
70611      break;
70612    }
70613    case 8:
70614      lhs = 0;
70615      break;
70616    case 9:
70617      lhs = 1;
70618      break;
70619
70620    /* This case could be removed without changing the results of running
70621    ** this code. Including it causes gcc to generate a faster switch
70622    ** statement (since the range of switch targets now starts at zero and
70623    ** is contiguous) but does not cause any duplicate code to be generated
70624    ** (as gcc is clever enough to combine the two like cases). Other
70625    ** compilers might be similar.  */
70626    case 0: case 7:
70627      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
70628
70629    default:
70630      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
70631  }
70632
70633  if( v>lhs ){
70634    res = pPKey2->r1;
70635  }else if( v<lhs ){
70636    res = pPKey2->r2;
70637  }else if( pPKey2->nField>1 ){
70638    /* The first fields of the two keys are equal. Compare the trailing
70639    ** fields.  */
70640    res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
70641  }else{
70642    /* The first fields of the two keys are equal and there are no trailing
70643    ** fields. Return pPKey2->default_rc in this case. */
70644    res = pPKey2->default_rc;
70645  }
70646
70647  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
70648  return res;
70649}
70650
70651/*
70652** This function is an optimized version of sqlite3VdbeRecordCompare()
70653** that (a) the first field of pPKey2 is a string, that (b) the first field
70654** uses the collation sequence BINARY and (c) that the size-of-header varint
70655** at the start of (pKey1/nKey1) fits in a single byte.
70656*/
70657static int vdbeRecordCompareString(
70658  int nKey1, const void *pKey1, /* Left key */
70659  UnpackedRecord *pPKey2        /* Right key */
70660){
70661  const u8 *aKey1 = (const u8*)pKey1;
70662  int serial_type;
70663  int res;
70664
70665  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
70666  getVarint32(&aKey1[1], serial_type);
70667  if( serial_type<12 ){
70668    res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
70669  }else if( !(serial_type & 0x01) ){
70670    res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
70671  }else{
70672    int nCmp;
70673    int nStr;
70674    int szHdr = aKey1[0];
70675
70676    nStr = (serial_type-12) / 2;
70677    if( (szHdr + nStr) > nKey1 ){
70678      pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
70679      return 0;    /* Corruption */
70680    }
70681    nCmp = MIN( pPKey2->aMem[0].n, nStr );
70682    res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
70683
70684    if( res==0 ){
70685      res = nStr - pPKey2->aMem[0].n;
70686      if( res==0 ){
70687        if( pPKey2->nField>1 ){
70688          res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
70689        }else{
70690          res = pPKey2->default_rc;
70691        }
70692      }else if( res>0 ){
70693        res = pPKey2->r2;
70694      }else{
70695        res = pPKey2->r1;
70696      }
70697    }else if( res>0 ){
70698      res = pPKey2->r2;
70699    }else{
70700      res = pPKey2->r1;
70701    }
70702  }
70703
70704  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
70705       || CORRUPT_DB
70706       || pPKey2->pKeyInfo->db->mallocFailed
70707  );
70708  return res;
70709}
70710
70711/*
70712** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
70713** suitable for comparing serialized records to the unpacked record passed
70714** as the only argument.
70715*/
70716SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
70717  /* varintRecordCompareInt() and varintRecordCompareString() both assume
70718  ** that the size-of-header varint that occurs at the start of each record
70719  ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
70720  ** also assumes that it is safe to overread a buffer by at least the
70721  ** maximum possible legal header size plus 8 bytes. Because there is
70722  ** guaranteed to be at least 74 (but not 136) bytes of padding following each
70723  ** buffer passed to varintRecordCompareInt() this makes it convenient to
70724  ** limit the size of the header to 64 bytes in cases where the first field
70725  ** is an integer.
70726  **
70727  ** The easiest way to enforce this limit is to consider only records with
70728  ** 13 fields or less. If the first field is an integer, the maximum legal
70729  ** header size is (12*5 + 1 + 1) bytes.  */
70730  if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
70731    int flags = p->aMem[0].flags;
70732    if( p->pKeyInfo->aSortOrder[0] ){
70733      p->r1 = 1;
70734      p->r2 = -1;
70735    }else{
70736      p->r1 = -1;
70737      p->r2 = 1;
70738    }
70739    if( (flags & MEM_Int) ){
70740      return vdbeRecordCompareInt;
70741    }
70742    testcase( flags & MEM_Real );
70743    testcase( flags & MEM_Null );
70744    testcase( flags & MEM_Blob );
70745    if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
70746      assert( flags & MEM_Str );
70747      return vdbeRecordCompareString;
70748    }
70749  }
70750
70751  return sqlite3VdbeRecordCompare;
70752}
70753
70754/*
70755** pCur points at an index entry created using the OP_MakeRecord opcode.
70756** Read the rowid (the last field in the record) and store it in *rowid.
70757** Return SQLITE_OK if everything works, or an error code otherwise.
70758**
70759** pCur might be pointing to text obtained from a corrupt database file.
70760** So the content cannot be trusted.  Do appropriate checks on the content.
70761*/
70762SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
70763  i64 nCellKey = 0;
70764  int rc;
70765  u32 szHdr;        /* Size of the header */
70766  u32 typeRowid;    /* Serial type of the rowid */
70767  u32 lenRowid;     /* Size of the rowid */
70768  Mem m, v;
70769
70770  /* Get the size of the index entry.  Only indices entries of less
70771  ** than 2GiB are support - anything large must be database corruption.
70772  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
70773  ** this code can safely assume that nCellKey is 32-bits
70774  */
70775  assert( sqlite3BtreeCursorIsValid(pCur) );
70776  VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
70777  assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
70778  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
70779
70780  /* Read in the complete content of the index entry */
70781  sqlite3VdbeMemInit(&m, db, 0);
70782  rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
70783  if( rc ){
70784    return rc;
70785  }
70786
70787  /* The index entry must begin with a header size */
70788  (void)getVarint32((u8*)m.z, szHdr);
70789  testcase( szHdr==3 );
70790  testcase( szHdr==m.n );
70791  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
70792    goto idx_rowid_corruption;
70793  }
70794
70795  /* The last field of the index should be an integer - the ROWID.
70796  ** Verify that the last entry really is an integer. */
70797  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
70798  testcase( typeRowid==1 );
70799  testcase( typeRowid==2 );
70800  testcase( typeRowid==3 );
70801  testcase( typeRowid==4 );
70802  testcase( typeRowid==5 );
70803  testcase( typeRowid==6 );
70804  testcase( typeRowid==8 );
70805  testcase( typeRowid==9 );
70806  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
70807    goto idx_rowid_corruption;
70808  }
70809  lenRowid = sqlite3SmallTypeSizes[typeRowid];
70810  testcase( (u32)m.n==szHdr+lenRowid );
70811  if( unlikely((u32)m.n<szHdr+lenRowid) ){
70812    goto idx_rowid_corruption;
70813  }
70814
70815  /* Fetch the integer off the end of the index record */
70816  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
70817  *rowid = v.u.i;
70818  sqlite3VdbeMemRelease(&m);
70819  return SQLITE_OK;
70820
70821  /* Jump here if database corruption is detected after m has been
70822  ** allocated.  Free the m object and return SQLITE_CORRUPT. */
70823idx_rowid_corruption:
70824  testcase( m.szMalloc!=0 );
70825  sqlite3VdbeMemRelease(&m);
70826  return SQLITE_CORRUPT_BKPT;
70827}
70828
70829/*
70830** Compare the key of the index entry that cursor pC is pointing to against
70831** the key string in pUnpacked.  Write into *pRes a number
70832** that is negative, zero, or positive if pC is less than, equal to,
70833** or greater than pUnpacked.  Return SQLITE_OK on success.
70834**
70835** pUnpacked is either created without a rowid or is truncated so that it
70836** omits the rowid at the end.  The rowid at the end of the index entry
70837** is ignored as well.  Hence, this routine only compares the prefixes
70838** of the keys prior to the final rowid, not the entire key.
70839*/
70840SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
70841  sqlite3 *db,                     /* Database connection */
70842  VdbeCursor *pC,                  /* The cursor to compare against */
70843  UnpackedRecord *pUnpacked,       /* Unpacked version of key */
70844  int *res                         /* Write the comparison result here */
70845){
70846  i64 nCellKey = 0;
70847  int rc;
70848  BtCursor *pCur = pC->pCursor;
70849  Mem m;
70850
70851  assert( sqlite3BtreeCursorIsValid(pCur) );
70852  VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
70853  assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
70854  /* nCellKey will always be between 0 and 0xffffffff because of the way
70855  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
70856  if( nCellKey<=0 || nCellKey>0x7fffffff ){
70857    *res = 0;
70858    return SQLITE_CORRUPT_BKPT;
70859  }
70860  sqlite3VdbeMemInit(&m, db, 0);
70861  rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (u32)nCellKey, 1, &m);
70862  if( rc ){
70863    return rc;
70864  }
70865  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
70866  sqlite3VdbeMemRelease(&m);
70867  return SQLITE_OK;
70868}
70869
70870/*
70871** This routine sets the value to be returned by subsequent calls to
70872** sqlite3_changes() on the database handle 'db'.
70873*/
70874SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
70875  assert( sqlite3_mutex_held(db->mutex) );
70876  db->nChange = nChange;
70877  db->nTotalChange += nChange;
70878}
70879
70880/*
70881** Set a flag in the vdbe to update the change counter when it is finalised
70882** or reset.
70883*/
70884SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
70885  v->changeCntOn = 1;
70886}
70887
70888/*
70889** Mark every prepared statement associated with a database connection
70890** as expired.
70891**
70892** An expired statement means that recompilation of the statement is
70893** recommend.  Statements expire when things happen that make their
70894** programs obsolete.  Removing user-defined functions or collating
70895** sequences, or changing an authorization function are the types of
70896** things that make prepared statements obsolete.
70897*/
70898SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
70899  Vdbe *p;
70900  for(p = db->pVdbe; p; p=p->pNext){
70901    p->expired = 1;
70902  }
70903}
70904
70905/*
70906** Return the database associated with the Vdbe.
70907*/
70908SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
70909  return v->db;
70910}
70911
70912/*
70913** Return a pointer to an sqlite3_value structure containing the value bound
70914** parameter iVar of VM v. Except, if the value is an SQL NULL, return
70915** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
70916** constants) to the value before returning it.
70917**
70918** The returned value must be freed by the caller using sqlite3ValueFree().
70919*/
70920SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
70921  assert( iVar>0 );
70922  if( v ){
70923    Mem *pMem = &v->aVar[iVar-1];
70924    if( 0==(pMem->flags & MEM_Null) ){
70925      sqlite3_value *pRet = sqlite3ValueNew(v->db);
70926      if( pRet ){
70927        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
70928        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
70929      }
70930      return pRet;
70931    }
70932  }
70933  return 0;
70934}
70935
70936/*
70937** Configure SQL variable iVar so that binding a new value to it signals
70938** to sqlite3_reoptimize() that re-preparing the statement may result
70939** in a better query plan.
70940*/
70941SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
70942  assert( iVar>0 );
70943  if( iVar>32 ){
70944    v->expmask = 0xffffffff;
70945  }else{
70946    v->expmask |= ((u32)1 << (iVar-1));
70947  }
70948}
70949
70950#ifndef SQLITE_OMIT_VIRTUALTABLE
70951/*
70952** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
70953** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
70954** in memory obtained from sqlite3DbMalloc).
70955*/
70956SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
70957  sqlite3 *db = p->db;
70958  sqlite3DbFree(db, p->zErrMsg);
70959  p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
70960  sqlite3_free(pVtab->zErrMsg);
70961  pVtab->zErrMsg = 0;
70962}
70963#endif /* SQLITE_OMIT_VIRTUALTABLE */
70964
70965/************** End of vdbeaux.c *********************************************/
70966/************** Begin file vdbeapi.c *****************************************/
70967/*
70968** 2004 May 26
70969**
70970** The author disclaims copyright to this source code.  In place of
70971** a legal notice, here is a blessing:
70972**
70973**    May you do good and not evil.
70974**    May you find forgiveness for yourself and forgive others.
70975**    May you share freely, never taking more than you give.
70976**
70977*************************************************************************
70978**
70979** This file contains code use to implement APIs that are part of the
70980** VDBE.
70981*/
70982/* #include "sqliteInt.h" */
70983/* #include "vdbeInt.h" */
70984
70985#ifndef SQLITE_OMIT_DEPRECATED
70986/*
70987** Return TRUE (non-zero) of the statement supplied as an argument needs
70988** to be recompiled.  A statement needs to be recompiled whenever the
70989** execution environment changes in a way that would alter the program
70990** that sqlite3_prepare() generates.  For example, if new functions or
70991** collating sequences are registered or if an authorizer function is
70992** added or changed.
70993*/
70994SQLITE_API int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt *pStmt){
70995  Vdbe *p = (Vdbe*)pStmt;
70996  return p==0 || p->expired;
70997}
70998#endif
70999
71000/*
71001** Check on a Vdbe to make sure it has not been finalized.  Log
71002** an error and return true if it has been finalized (or is otherwise
71003** invalid).  Return false if it is ok.
71004*/
71005static int vdbeSafety(Vdbe *p){
71006  if( p->db==0 ){
71007    sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
71008    return 1;
71009  }else{
71010    return 0;
71011  }
71012}
71013static int vdbeSafetyNotNull(Vdbe *p){
71014  if( p==0 ){
71015    sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
71016    return 1;
71017  }else{
71018    return vdbeSafety(p);
71019  }
71020}
71021
71022#ifndef SQLITE_OMIT_TRACE
71023/*
71024** Invoke the profile callback.  This routine is only called if we already
71025** know that the profile callback is defined and needs to be invoked.
71026*/
71027static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
71028  sqlite3_int64 iNow;
71029  assert( p->startTime>0 );
71030  assert( db->xProfile!=0 );
71031  assert( db->init.busy==0 );
71032  assert( p->zSql!=0 );
71033  sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
71034  db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
71035  p->startTime = 0;
71036}
71037/*
71038** The checkProfileCallback(DB,P) macro checks to see if a profile callback
71039** is needed, and it invokes the callback if it is needed.
71040*/
71041# define checkProfileCallback(DB,P) \
71042   if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
71043#else
71044# define checkProfileCallback(DB,P)  /*no-op*/
71045#endif
71046
71047/*
71048** The following routine destroys a virtual machine that is created by
71049** the sqlite3_compile() routine. The integer returned is an SQLITE_
71050** success/failure code that describes the result of executing the virtual
71051** machine.
71052**
71053** This routine sets the error code and string returned by
71054** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
71055*/
71056SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt){
71057  int rc;
71058  if( pStmt==0 ){
71059    /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
71060    ** pointer is a harmless no-op. */
71061    rc = SQLITE_OK;
71062  }else{
71063    Vdbe *v = (Vdbe*)pStmt;
71064    sqlite3 *db = v->db;
71065    if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
71066    sqlite3_mutex_enter(db->mutex);
71067    checkProfileCallback(db, v);
71068    rc = sqlite3VdbeFinalize(v);
71069    rc = sqlite3ApiExit(db, rc);
71070    sqlite3LeaveMutexAndCloseZombie(db);
71071  }
71072  return rc;
71073}
71074
71075/*
71076** Terminate the current execution of an SQL statement and reset it
71077** back to its starting state so that it can be reused. A success code from
71078** the prior execution is returned.
71079**
71080** This routine sets the error code and string returned by
71081** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
71082*/
71083SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt){
71084  int rc;
71085  if( pStmt==0 ){
71086    rc = SQLITE_OK;
71087  }else{
71088    Vdbe *v = (Vdbe*)pStmt;
71089    sqlite3 *db = v->db;
71090    sqlite3_mutex_enter(db->mutex);
71091    checkProfileCallback(db, v);
71092    rc = sqlite3VdbeReset(v);
71093    sqlite3VdbeRewind(v);
71094    assert( (rc & (db->errMask))==rc );
71095    rc = sqlite3ApiExit(db, rc);
71096    sqlite3_mutex_leave(db->mutex);
71097  }
71098  return rc;
71099}
71100
71101/*
71102** Set all the parameters in the compiled SQL statement to NULL.
71103*/
71104SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt *pStmt){
71105  int i;
71106  int rc = SQLITE_OK;
71107  Vdbe *p = (Vdbe*)pStmt;
71108#if SQLITE_THREADSAFE
71109  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
71110#endif
71111  sqlite3_mutex_enter(mutex);
71112  for(i=0; i<p->nVar; i++){
71113    sqlite3VdbeMemRelease(&p->aVar[i]);
71114    p->aVar[i].flags = MEM_Null;
71115  }
71116  if( p->isPrepareV2 && p->expmask ){
71117    p->expired = 1;
71118  }
71119  sqlite3_mutex_leave(mutex);
71120  return rc;
71121}
71122
71123
71124/**************************** sqlite3_value_  *******************************
71125** The following routines extract information from a Mem or sqlite3_value
71126** structure.
71127*/
71128SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value *pVal){
71129  Mem *p = (Mem*)pVal;
71130  if( p->flags & (MEM_Blob|MEM_Str) ){
71131    if( sqlite3VdbeMemExpandBlob(p)!=SQLITE_OK ){
71132      assert( p->flags==MEM_Null && p->z==0 );
71133      return 0;
71134    }
71135    p->flags |= MEM_Blob;
71136    return p->n ? p->z : 0;
71137  }else{
71138    return sqlite3_value_text(pVal);
71139  }
71140}
71141SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value *pVal){
71142  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
71143}
71144SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value *pVal){
71145  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
71146}
71147SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value *pVal){
71148  return sqlite3VdbeRealValue((Mem*)pVal);
71149}
71150SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value *pVal){
71151  return (int)sqlite3VdbeIntValue((Mem*)pVal);
71152}
71153SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value *pVal){
71154  return sqlite3VdbeIntValue((Mem*)pVal);
71155}
71156SQLITE_API unsigned int SQLITE_STDCALL sqlite3_value_subtype(sqlite3_value *pVal){
71157  return ((Mem*)pVal)->eSubtype;
71158}
71159SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value *pVal){
71160  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
71161}
71162#ifndef SQLITE_OMIT_UTF16
71163SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value* pVal){
71164  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
71165}
71166SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value *pVal){
71167  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
71168}
71169SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value *pVal){
71170  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
71171}
71172#endif /* SQLITE_OMIT_UTF16 */
71173/* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
71174** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
71175** point number string BLOB NULL
71176*/
71177SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value* pVal){
71178  static const u8 aType[] = {
71179     SQLITE_BLOB,     /* 0x00 */
71180     SQLITE_NULL,     /* 0x01 */
71181     SQLITE_TEXT,     /* 0x02 */
71182     SQLITE_NULL,     /* 0x03 */
71183     SQLITE_INTEGER,  /* 0x04 */
71184     SQLITE_NULL,     /* 0x05 */
71185     SQLITE_INTEGER,  /* 0x06 */
71186     SQLITE_NULL,     /* 0x07 */
71187     SQLITE_FLOAT,    /* 0x08 */
71188     SQLITE_NULL,     /* 0x09 */
71189     SQLITE_FLOAT,    /* 0x0a */
71190     SQLITE_NULL,     /* 0x0b */
71191     SQLITE_INTEGER,  /* 0x0c */
71192     SQLITE_NULL,     /* 0x0d */
71193     SQLITE_INTEGER,  /* 0x0e */
71194     SQLITE_NULL,     /* 0x0f */
71195     SQLITE_BLOB,     /* 0x10 */
71196     SQLITE_NULL,     /* 0x11 */
71197     SQLITE_TEXT,     /* 0x12 */
71198     SQLITE_NULL,     /* 0x13 */
71199     SQLITE_INTEGER,  /* 0x14 */
71200     SQLITE_NULL,     /* 0x15 */
71201     SQLITE_INTEGER,  /* 0x16 */
71202     SQLITE_NULL,     /* 0x17 */
71203     SQLITE_FLOAT,    /* 0x18 */
71204     SQLITE_NULL,     /* 0x19 */
71205     SQLITE_FLOAT,    /* 0x1a */
71206     SQLITE_NULL,     /* 0x1b */
71207     SQLITE_INTEGER,  /* 0x1c */
71208     SQLITE_NULL,     /* 0x1d */
71209     SQLITE_INTEGER,  /* 0x1e */
71210     SQLITE_NULL,     /* 0x1f */
71211  };
71212  return aType[pVal->flags&MEM_AffMask];
71213}
71214
71215/* Make a copy of an sqlite3_value object
71216*/
71217SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_value_dup(const sqlite3_value *pOrig){
71218  sqlite3_value *pNew;
71219  if( pOrig==0 ) return 0;
71220  pNew = sqlite3_malloc( sizeof(*pNew) );
71221  if( pNew==0 ) return 0;
71222  memset(pNew, 0, sizeof(*pNew));
71223  memcpy(pNew, pOrig, MEMCELLSIZE);
71224  pNew->flags &= ~MEM_Dyn;
71225  pNew->db = 0;
71226  if( pNew->flags&(MEM_Str|MEM_Blob) ){
71227    pNew->flags &= ~(MEM_Static|MEM_Dyn);
71228    pNew->flags |= MEM_Ephem;
71229    if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
71230      sqlite3ValueFree(pNew);
71231      pNew = 0;
71232    }
71233  }
71234  return pNew;
71235}
71236
71237/* Destroy an sqlite3_value object previously obtained from
71238** sqlite3_value_dup().
71239*/
71240SQLITE_API void SQLITE_STDCALL sqlite3_value_free(sqlite3_value *pOld){
71241  sqlite3ValueFree(pOld);
71242}
71243
71244
71245/**************************** sqlite3_result_  *******************************
71246** The following routines are used by user-defined functions to specify
71247** the function result.
71248**
71249** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
71250** result as a string or blob but if the string or blob is too large, it
71251** then sets the error code to SQLITE_TOOBIG
71252**
71253** The invokeValueDestructor(P,X) routine invokes destructor function X()
71254** on value P is not going to be used and need to be destroyed.
71255*/
71256static void setResultStrOrError(
71257  sqlite3_context *pCtx,  /* Function context */
71258  const char *z,          /* String pointer */
71259  int n,                  /* Bytes in string, or negative */
71260  u8 enc,                 /* Encoding of z.  0 for BLOBs */
71261  void (*xDel)(void*)     /* Destructor function */
71262){
71263  if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
71264    sqlite3_result_error_toobig(pCtx);
71265  }
71266}
71267static int invokeValueDestructor(
71268  const void *p,             /* Value to destroy */
71269  void (*xDel)(void*),       /* The destructor */
71270  sqlite3_context *pCtx      /* Set a SQLITE_TOOBIG error if no NULL */
71271){
71272  assert( xDel!=SQLITE_DYNAMIC );
71273  if( xDel==0 ){
71274    /* noop */
71275  }else if( xDel==SQLITE_TRANSIENT ){
71276    /* noop */
71277  }else{
71278    xDel((void*)p);
71279  }
71280  if( pCtx ) sqlite3_result_error_toobig(pCtx);
71281  return SQLITE_TOOBIG;
71282}
71283SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(
71284  sqlite3_context *pCtx,
71285  const void *z,
71286  int n,
71287  void (*xDel)(void *)
71288){
71289  assert( n>=0 );
71290  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71291  setResultStrOrError(pCtx, z, n, 0, xDel);
71292}
71293SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(
71294  sqlite3_context *pCtx,
71295  const void *z,
71296  sqlite3_uint64 n,
71297  void (*xDel)(void *)
71298){
71299  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71300  assert( xDel!=SQLITE_DYNAMIC );
71301  if( n>0x7fffffff ){
71302    (void)invokeValueDestructor(z, xDel, pCtx);
71303  }else{
71304    setResultStrOrError(pCtx, z, (int)n, 0, xDel);
71305  }
71306}
71307SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context *pCtx, double rVal){
71308  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71309  sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
71310}
71311SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
71312  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71313  pCtx->isError = SQLITE_ERROR;
71314  pCtx->fErrorOrAux = 1;
71315  sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
71316}
71317#ifndef SQLITE_OMIT_UTF16
71318SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
71319  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71320  pCtx->isError = SQLITE_ERROR;
71321  pCtx->fErrorOrAux = 1;
71322  sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
71323}
71324#endif
71325SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context *pCtx, int iVal){
71326  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71327  sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
71328}
71329SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
71330  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71331  sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
71332}
71333SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context *pCtx){
71334  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71335  sqlite3VdbeMemSetNull(pCtx->pOut);
71336}
71337SQLITE_API void SQLITE_STDCALL sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
71338  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71339  pCtx->pOut->eSubtype = eSubtype & 0xff;
71340}
71341SQLITE_API void SQLITE_STDCALL sqlite3_result_text(
71342  sqlite3_context *pCtx,
71343  const char *z,
71344  int n,
71345  void (*xDel)(void *)
71346){
71347  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71348  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
71349}
71350SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(
71351  sqlite3_context *pCtx,
71352  const char *z,
71353  sqlite3_uint64 n,
71354  void (*xDel)(void *),
71355  unsigned char enc
71356){
71357  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71358  assert( xDel!=SQLITE_DYNAMIC );
71359  if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
71360  if( n>0x7fffffff ){
71361    (void)invokeValueDestructor(z, xDel, pCtx);
71362  }else{
71363    setResultStrOrError(pCtx, z, (int)n, enc, xDel);
71364  }
71365}
71366#ifndef SQLITE_OMIT_UTF16
71367SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(
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_UTF16NATIVE, xDel);
71375}
71376SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(
71377  sqlite3_context *pCtx,
71378  const void *z,
71379  int n,
71380  void (*xDel)(void *)
71381){
71382  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71383  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
71384}
71385SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(
71386  sqlite3_context *pCtx,
71387  const void *z,
71388  int n,
71389  void (*xDel)(void *)
71390){
71391  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71392  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
71393}
71394#endif /* SQLITE_OMIT_UTF16 */
71395SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
71396  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71397  sqlite3VdbeMemCopy(pCtx->pOut, pValue);
71398}
71399SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
71400  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71401  sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
71402}
71403SQLITE_API int SQLITE_STDCALL sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
71404  Mem *pOut = pCtx->pOut;
71405  assert( sqlite3_mutex_held(pOut->db->mutex) );
71406  if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
71407    return SQLITE_TOOBIG;
71408  }
71409  sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
71410  return SQLITE_OK;
71411}
71412SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
71413  pCtx->isError = errCode;
71414  pCtx->fErrorOrAux = 1;
71415#ifdef SQLITE_DEBUG
71416  if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
71417#endif
71418  if( pCtx->pOut->flags & MEM_Null ){
71419    sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
71420                         SQLITE_UTF8, SQLITE_STATIC);
71421  }
71422}
71423
71424/* Force an SQLITE_TOOBIG error. */
71425SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context *pCtx){
71426  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71427  pCtx->isError = SQLITE_TOOBIG;
71428  pCtx->fErrorOrAux = 1;
71429  sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
71430                       SQLITE_UTF8, SQLITE_STATIC);
71431}
71432
71433/* An SQLITE_NOMEM error. */
71434SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context *pCtx){
71435  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71436  sqlite3VdbeMemSetNull(pCtx->pOut);
71437  pCtx->isError = SQLITE_NOMEM;
71438  pCtx->fErrorOrAux = 1;
71439  pCtx->pOut->db->mallocFailed = 1;
71440}
71441
71442/*
71443** This function is called after a transaction has been committed. It
71444** invokes callbacks registered with sqlite3_wal_hook() as required.
71445*/
71446static int doWalCallbacks(sqlite3 *db){
71447  int rc = SQLITE_OK;
71448#ifndef SQLITE_OMIT_WAL
71449  int i;
71450  for(i=0; i<db->nDb; i++){
71451    Btree *pBt = db->aDb[i].pBt;
71452    if( pBt ){
71453      int nEntry;
71454      sqlite3BtreeEnter(pBt);
71455      nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
71456      sqlite3BtreeLeave(pBt);
71457      if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
71458        rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
71459      }
71460    }
71461  }
71462#endif
71463  return rc;
71464}
71465
71466
71467/*
71468** Execute the statement pStmt, either until a row of data is ready, the
71469** statement is completely executed or an error occurs.
71470**
71471** This routine implements the bulk of the logic behind the sqlite_step()
71472** API.  The only thing omitted is the automatic recompile if a
71473** schema change has occurred.  That detail is handled by the
71474** outer sqlite3_step() wrapper procedure.
71475*/
71476static int sqlite3Step(Vdbe *p){
71477  sqlite3 *db;
71478  int rc;
71479
71480  assert(p);
71481  if( p->magic!=VDBE_MAGIC_RUN ){
71482    /* We used to require that sqlite3_reset() be called before retrying
71483    ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
71484    ** with version 3.7.0, we changed this so that sqlite3_reset() would
71485    ** be called automatically instead of throwing the SQLITE_MISUSE error.
71486    ** This "automatic-reset" change is not technically an incompatibility,
71487    ** since any application that receives an SQLITE_MISUSE is broken by
71488    ** definition.
71489    **
71490    ** Nevertheless, some published applications that were originally written
71491    ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
71492    ** returns, and those were broken by the automatic-reset change.  As a
71493    ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
71494    ** legacy behavior of returning SQLITE_MISUSE for cases where the
71495    ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
71496    ** or SQLITE_BUSY error.
71497    */
71498#ifdef SQLITE_OMIT_AUTORESET
71499    if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
71500      sqlite3_reset((sqlite3_stmt*)p);
71501    }else{
71502      return SQLITE_MISUSE_BKPT;
71503    }
71504#else
71505    sqlite3_reset((sqlite3_stmt*)p);
71506#endif
71507  }
71508
71509  /* Check that malloc() has not failed. If it has, return early. */
71510  db = p->db;
71511  if( db->mallocFailed ){
71512    p->rc = SQLITE_NOMEM;
71513    return SQLITE_NOMEM;
71514  }
71515
71516  if( p->pc<=0 && p->expired ){
71517    p->rc = SQLITE_SCHEMA;
71518    rc = SQLITE_ERROR;
71519    goto end_of_step;
71520  }
71521  if( p->pc<0 ){
71522    /* If there are no other statements currently running, then
71523    ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
71524    ** from interrupting a statement that has not yet started.
71525    */
71526    if( db->nVdbeActive==0 ){
71527      db->u1.isInterrupted = 0;
71528    }
71529
71530    assert( db->nVdbeWrite>0 || db->autoCommit==0
71531        || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
71532    );
71533
71534#ifndef SQLITE_OMIT_TRACE
71535    if( db->xProfile && !db->init.busy && p->zSql ){
71536      sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
71537    }else{
71538      assert( p->startTime==0 );
71539    }
71540#endif
71541
71542    db->nVdbeActive++;
71543    if( p->readOnly==0 ) db->nVdbeWrite++;
71544    if( p->bIsReader ) db->nVdbeRead++;
71545    p->pc = 0;
71546  }
71547#ifdef SQLITE_DEBUG
71548  p->rcApp = SQLITE_OK;
71549#endif
71550#ifndef SQLITE_OMIT_EXPLAIN
71551  if( p->explain ){
71552    rc = sqlite3VdbeList(p);
71553  }else
71554#endif /* SQLITE_OMIT_EXPLAIN */
71555  {
71556    db->nVdbeExec++;
71557    rc = sqlite3VdbeExec(p);
71558    db->nVdbeExec--;
71559  }
71560
71561#ifndef SQLITE_OMIT_TRACE
71562  /* If the statement completed successfully, invoke the profile callback */
71563  if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
71564#endif
71565
71566  if( rc==SQLITE_DONE ){
71567    assert( p->rc==SQLITE_OK );
71568    p->rc = doWalCallbacks(db);
71569    if( p->rc!=SQLITE_OK ){
71570      rc = SQLITE_ERROR;
71571    }
71572  }
71573
71574  db->errCode = rc;
71575  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
71576    p->rc = SQLITE_NOMEM;
71577  }
71578end_of_step:
71579  /* At this point local variable rc holds the value that should be
71580  ** returned if this statement was compiled using the legacy
71581  ** sqlite3_prepare() interface. According to the docs, this can only
71582  ** be one of the values in the first assert() below. Variable p->rc
71583  ** contains the value that would be returned if sqlite3_finalize()
71584  ** were called on statement p.
71585  */
71586  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
71587       || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
71588  );
71589  assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
71590  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
71591    /* If this statement was prepared using sqlite3_prepare_v2(), and an
71592    ** error has occurred, then return the error code in p->rc to the
71593    ** caller. Set the error code in the database handle to the same value.
71594    */
71595    rc = sqlite3VdbeTransferError(p);
71596  }
71597  return (rc&db->errMask);
71598}
71599
71600/*
71601** This is the top-level implementation of sqlite3_step().  Call
71602** sqlite3Step() to do most of the work.  If a schema error occurs,
71603** call sqlite3Reprepare() and try again.
71604*/
71605SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt *pStmt){
71606  int rc = SQLITE_OK;      /* Result from sqlite3Step() */
71607  int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
71608  Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
71609  int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
71610  sqlite3 *db;             /* The database connection */
71611
71612  if( vdbeSafetyNotNull(v) ){
71613    return SQLITE_MISUSE_BKPT;
71614  }
71615  db = v->db;
71616  sqlite3_mutex_enter(db->mutex);
71617  v->doingRerun = 0;
71618  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
71619         && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
71620    int savedPc = v->pc;
71621    rc2 = rc = sqlite3Reprepare(v);
71622    if( rc!=SQLITE_OK) break;
71623    sqlite3_reset(pStmt);
71624    if( savedPc>=0 ) v->doingRerun = 1;
71625    assert( v->expired==0 );
71626  }
71627  if( rc2!=SQLITE_OK ){
71628    /* This case occurs after failing to recompile an sql statement.
71629    ** The error message from the SQL compiler has already been loaded
71630    ** into the database handle. This block copies the error message
71631    ** from the database handle into the statement and sets the statement
71632    ** program counter to 0 to ensure that when the statement is
71633    ** finalized or reset the parser error message is available via
71634    ** sqlite3_errmsg() and sqlite3_errcode().
71635    */
71636    const char *zErr = (const char *)sqlite3_value_text(db->pErr);
71637    sqlite3DbFree(db, v->zErrMsg);
71638    if( !db->mallocFailed ){
71639      v->zErrMsg = sqlite3DbStrDup(db, zErr);
71640      v->rc = rc2;
71641    } else {
71642      v->zErrMsg = 0;
71643      v->rc = rc = SQLITE_NOMEM;
71644    }
71645  }
71646  rc = sqlite3ApiExit(db, rc);
71647  sqlite3_mutex_leave(db->mutex);
71648  return rc;
71649}
71650
71651
71652/*
71653** Extract the user data from a sqlite3_context structure and return a
71654** pointer to it.
71655*/
71656SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context *p){
71657  assert( p && p->pFunc );
71658  return p->pFunc->pUserData;
71659}
71660
71661/*
71662** Extract the user data from a sqlite3_context structure and return a
71663** pointer to it.
71664**
71665** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
71666** returns a copy of the pointer to the database connection (the 1st
71667** parameter) of the sqlite3_create_function() and
71668** sqlite3_create_function16() routines that originally registered the
71669** application defined function.
71670*/
71671SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context *p){
71672  assert( p && p->pOut );
71673  return p->pOut->db;
71674}
71675
71676/*
71677** Return the current time for a statement.  If the current time
71678** is requested more than once within the same run of a single prepared
71679** statement, the exact same time is returned for each invocation regardless
71680** of the amount of time that elapses between invocations.  In other words,
71681** the time returned is always the time of the first call.
71682*/
71683SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
71684  int rc;
71685#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
71686  sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
71687  assert( p->pVdbe!=0 );
71688#else
71689  sqlite3_int64 iTime = 0;
71690  sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
71691#endif
71692  if( *piTime==0 ){
71693    rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
71694    if( rc ) *piTime = 0;
71695  }
71696  return *piTime;
71697}
71698
71699/*
71700** The following is the implementation of an SQL function that always
71701** fails with an error message stating that the function is used in the
71702** wrong context.  The sqlite3_overload_function() API might construct
71703** SQL function that use this routine so that the functions will exist
71704** for name resolution but are actually overloaded by the xFindFunction
71705** method of virtual tables.
71706*/
71707SQLITE_PRIVATE void sqlite3InvalidFunction(
71708  sqlite3_context *context,  /* The function calling context */
71709  int NotUsed,               /* Number of arguments to the function */
71710  sqlite3_value **NotUsed2   /* Value of each argument */
71711){
71712  const char *zName = context->pFunc->zName;
71713  char *zErr;
71714  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71715  zErr = sqlite3_mprintf(
71716      "unable to use function %s in the requested context", zName);
71717  sqlite3_result_error(context, zErr, -1);
71718  sqlite3_free(zErr);
71719}
71720
71721/*
71722** Create a new aggregate context for p and return a pointer to
71723** its pMem->z element.
71724*/
71725static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
71726  Mem *pMem = p->pMem;
71727  assert( (pMem->flags & MEM_Agg)==0 );
71728  if( nByte<=0 ){
71729    sqlite3VdbeMemSetNull(pMem);
71730    pMem->z = 0;
71731  }else{
71732    sqlite3VdbeMemClearAndResize(pMem, nByte);
71733    pMem->flags = MEM_Agg;
71734    pMem->u.pDef = p->pFunc;
71735    if( pMem->z ){
71736      memset(pMem->z, 0, nByte);
71737    }
71738  }
71739  return (void*)pMem->z;
71740}
71741
71742/*
71743** Allocate or return the aggregate context for a user function.  A new
71744** context is allocated on the first call.  Subsequent calls return the
71745** same context that was returned on prior calls.
71746*/
71747SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context *p, int nByte){
71748  assert( p && p->pFunc && p->pFunc->xStep );
71749  assert( sqlite3_mutex_held(p->pOut->db->mutex) );
71750  testcase( nByte<0 );
71751  if( (p->pMem->flags & MEM_Agg)==0 ){
71752    return createAggContext(p, nByte);
71753  }else{
71754    return (void*)p->pMem->z;
71755  }
71756}
71757
71758/*
71759** Return the auxiliary data pointer, if any, for the iArg'th argument to
71760** the user-function defined by pCtx.
71761*/
71762SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
71763  AuxData *pAuxData;
71764
71765  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71766#if SQLITE_ENABLE_STAT3_OR_STAT4
71767  if( pCtx->pVdbe==0 ) return 0;
71768#else
71769  assert( pCtx->pVdbe!=0 );
71770#endif
71771  for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
71772    if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
71773  }
71774
71775  return (pAuxData ? pAuxData->pAux : 0);
71776}
71777
71778/*
71779** Set the auxiliary data pointer and delete function, for the iArg'th
71780** argument to the user-function defined by pCtx. Any previous value is
71781** deleted by calling the delete function specified when it was set.
71782*/
71783SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(
71784  sqlite3_context *pCtx,
71785  int iArg,
71786  void *pAux,
71787  void (*xDelete)(void*)
71788){
71789  AuxData *pAuxData;
71790  Vdbe *pVdbe = pCtx->pVdbe;
71791
71792  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
71793  if( iArg<0 ) goto failed;
71794#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
71795  if( pVdbe==0 ) goto failed;
71796#else
71797  assert( pVdbe!=0 );
71798#endif
71799
71800  for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
71801    if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
71802  }
71803  if( pAuxData==0 ){
71804    pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
71805    if( !pAuxData ) goto failed;
71806    pAuxData->iOp = pCtx->iOp;
71807    pAuxData->iArg = iArg;
71808    pAuxData->pNext = pVdbe->pAuxData;
71809    pVdbe->pAuxData = pAuxData;
71810    if( pCtx->fErrorOrAux==0 ){
71811      pCtx->isError = 0;
71812      pCtx->fErrorOrAux = 1;
71813    }
71814  }else if( pAuxData->xDelete ){
71815    pAuxData->xDelete(pAuxData->pAux);
71816  }
71817
71818  pAuxData->pAux = pAux;
71819  pAuxData->xDelete = xDelete;
71820  return;
71821
71822failed:
71823  if( xDelete ){
71824    xDelete(pAux);
71825  }
71826}
71827
71828#ifndef SQLITE_OMIT_DEPRECATED
71829/*
71830** Return the number of times the Step function of an aggregate has been
71831** called.
71832**
71833** This function is deprecated.  Do not use it for new code.  It is
71834** provide only to avoid breaking legacy code.  New aggregate function
71835** implementations should keep their own counts within their aggregate
71836** context.
71837*/
71838SQLITE_API int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context *p){
71839  assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
71840  return p->pMem->n;
71841}
71842#endif
71843
71844/*
71845** Return the number of columns in the result set for the statement pStmt.
71846*/
71847SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt){
71848  Vdbe *pVm = (Vdbe *)pStmt;
71849  return pVm ? pVm->nResColumn : 0;
71850}
71851
71852/*
71853** Return the number of values available from the current row of the
71854** currently executing statement pStmt.
71855*/
71856SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt){
71857  Vdbe *pVm = (Vdbe *)pStmt;
71858  if( pVm==0 || pVm->pResultSet==0 ) return 0;
71859  return pVm->nResColumn;
71860}
71861
71862/*
71863** Return a pointer to static memory containing an SQL NULL value.
71864*/
71865static const Mem *columnNullValue(void){
71866  /* Even though the Mem structure contains an element
71867  ** of type i64, on certain architectures (x86) with certain compiler
71868  ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
71869  ** instead of an 8-byte one. This all works fine, except that when
71870  ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
71871  ** that a Mem structure is located on an 8-byte boundary. To prevent
71872  ** these assert()s from failing, when building with SQLITE_DEBUG defined
71873  ** using gcc, we force nullMem to be 8-byte aligned using the magical
71874  ** __attribute__((aligned(8))) macro.  */
71875  static const Mem nullMem
71876#if defined(SQLITE_DEBUG) && defined(__GNUC__)
71877    __attribute__((aligned(8)))
71878#endif
71879    = {
71880        /* .u          = */ {0},
71881        /* .flags      = */ (u16)MEM_Null,
71882        /* .enc        = */ (u8)0,
71883        /* .eSubtype   = */ (u8)0,
71884        /* .n          = */ (int)0,
71885        /* .z          = */ (char*)0,
71886        /* .zMalloc    = */ (char*)0,
71887        /* .szMalloc   = */ (int)0,
71888        /* .uTemp      = */ (u32)0,
71889        /* .db         = */ (sqlite3*)0,
71890        /* .xDel       = */ (void(*)(void*))0,
71891#ifdef SQLITE_DEBUG
71892        /* .pScopyFrom = */ (Mem*)0,
71893        /* .pFiller    = */ (void*)0,
71894#endif
71895      };
71896  return &nullMem;
71897}
71898
71899/*
71900** Check to see if column iCol of the given statement is valid.  If
71901** it is, return a pointer to the Mem for the value of that column.
71902** If iCol is not valid, return a pointer to a Mem which has a value
71903** of NULL.
71904*/
71905static Mem *columnMem(sqlite3_stmt *pStmt, int i){
71906  Vdbe *pVm;
71907  Mem *pOut;
71908
71909  pVm = (Vdbe *)pStmt;
71910  if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
71911    sqlite3_mutex_enter(pVm->db->mutex);
71912    pOut = &pVm->pResultSet[i];
71913  }else{
71914    if( pVm && ALWAYS(pVm->db) ){
71915      sqlite3_mutex_enter(pVm->db->mutex);
71916      sqlite3Error(pVm->db, SQLITE_RANGE);
71917    }
71918    pOut = (Mem*)columnNullValue();
71919  }
71920  return pOut;
71921}
71922
71923/*
71924** This function is called after invoking an sqlite3_value_XXX function on a
71925** column value (i.e. a value returned by evaluating an SQL expression in the
71926** select list of a SELECT statement) that may cause a malloc() failure. If
71927** malloc() has failed, the threads mallocFailed flag is cleared and the result
71928** code of statement pStmt set to SQLITE_NOMEM.
71929**
71930** Specifically, this is called from within:
71931**
71932**     sqlite3_column_int()
71933**     sqlite3_column_int64()
71934**     sqlite3_column_text()
71935**     sqlite3_column_text16()
71936**     sqlite3_column_real()
71937**     sqlite3_column_bytes()
71938**     sqlite3_column_bytes16()
71939**     sqiite3_column_blob()
71940*/
71941static void columnMallocFailure(sqlite3_stmt *pStmt)
71942{
71943  /* If malloc() failed during an encoding conversion within an
71944  ** sqlite3_column_XXX API, then set the return code of the statement to
71945  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
71946  ** and _finalize() will return NOMEM.
71947  */
71948  Vdbe *p = (Vdbe *)pStmt;
71949  if( p ){
71950    p->rc = sqlite3ApiExit(p->db, p->rc);
71951    sqlite3_mutex_leave(p->db->mutex);
71952  }
71953}
71954
71955/**************************** sqlite3_column_  *******************************
71956** The following routines are used to access elements of the current row
71957** in the result set.
71958*/
71959SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
71960  const void *val;
71961  val = sqlite3_value_blob( columnMem(pStmt,i) );
71962  /* Even though there is no encoding conversion, value_blob() might
71963  ** need to call malloc() to expand the result of a zeroblob()
71964  ** expression.
71965  */
71966  columnMallocFailure(pStmt);
71967  return val;
71968}
71969SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
71970  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
71971  columnMallocFailure(pStmt);
71972  return val;
71973}
71974SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
71975  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
71976  columnMallocFailure(pStmt);
71977  return val;
71978}
71979SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt *pStmt, int i){
71980  double val = sqlite3_value_double( columnMem(pStmt,i) );
71981  columnMallocFailure(pStmt);
71982  return val;
71983}
71984SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt *pStmt, int i){
71985  int val = sqlite3_value_int( columnMem(pStmt,i) );
71986  columnMallocFailure(pStmt);
71987  return val;
71988}
71989SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
71990  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
71991  columnMallocFailure(pStmt);
71992  return val;
71993}
71994SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt *pStmt, int i){
71995  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
71996  columnMallocFailure(pStmt);
71997  return val;
71998}
71999SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt *pStmt, int i){
72000  Mem *pOut = columnMem(pStmt, i);
72001  if( pOut->flags&MEM_Static ){
72002    pOut->flags &= ~MEM_Static;
72003    pOut->flags |= MEM_Ephem;
72004  }
72005  columnMallocFailure(pStmt);
72006  return (sqlite3_value *)pOut;
72007}
72008#ifndef SQLITE_OMIT_UTF16
72009SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
72010  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
72011  columnMallocFailure(pStmt);
72012  return val;
72013}
72014#endif /* SQLITE_OMIT_UTF16 */
72015SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt *pStmt, int i){
72016  int iType = sqlite3_value_type( columnMem(pStmt,i) );
72017  columnMallocFailure(pStmt);
72018  return iType;
72019}
72020
72021/*
72022** Convert the N-th element of pStmt->pColName[] into a string using
72023** xFunc() then return that string.  If N is out of range, return 0.
72024**
72025** There are up to 5 names for each column.  useType determines which
72026** name is returned.  Here are the names:
72027**
72028**    0      The column name as it should be displayed for output
72029**    1      The datatype name for the column
72030**    2      The name of the database that the column derives from
72031**    3      The name of the table that the column derives from
72032**    4      The name of the table column that the result column derives from
72033**
72034** If the result is not a simple column reference (if it is an expression
72035** or a constant) then useTypes 2, 3, and 4 return NULL.
72036*/
72037static const void *columnName(
72038  sqlite3_stmt *pStmt,
72039  int N,
72040  const void *(*xFunc)(Mem*),
72041  int useType
72042){
72043  const void *ret;
72044  Vdbe *p;
72045  int n;
72046  sqlite3 *db;
72047#ifdef SQLITE_ENABLE_API_ARMOR
72048  if( pStmt==0 ){
72049    (void)SQLITE_MISUSE_BKPT;
72050    return 0;
72051  }
72052#endif
72053  ret = 0;
72054  p = (Vdbe *)pStmt;
72055  db = p->db;
72056  assert( db!=0 );
72057  n = sqlite3_column_count(pStmt);
72058  if( N<n && N>=0 ){
72059    N += useType*n;
72060    sqlite3_mutex_enter(db->mutex);
72061    assert( db->mallocFailed==0 );
72062    ret = xFunc(&p->aColName[N]);
72063     /* A malloc may have failed inside of the xFunc() call. If this
72064    ** is the case, clear the mallocFailed flag and return NULL.
72065    */
72066    if( db->mallocFailed ){
72067      db->mallocFailed = 0;
72068      ret = 0;
72069    }
72070    sqlite3_mutex_leave(db->mutex);
72071  }
72072  return ret;
72073}
72074
72075/*
72076** Return the name of the Nth column of the result set returned by SQL
72077** statement pStmt.
72078*/
72079SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt *pStmt, int N){
72080  return columnName(
72081      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
72082}
72083#ifndef SQLITE_OMIT_UTF16
72084SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
72085  return columnName(
72086      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
72087}
72088#endif
72089
72090/*
72091** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
72092** not define OMIT_DECLTYPE.
72093*/
72094#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
72095# error "Must not define both SQLITE_OMIT_DECLTYPE \
72096         and SQLITE_ENABLE_COLUMN_METADATA"
72097#endif
72098
72099#ifndef SQLITE_OMIT_DECLTYPE
72100/*
72101** Return the column declaration type (if applicable) of the 'i'th column
72102** of the result set of SQL statement pStmt.
72103*/
72104SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
72105  return columnName(
72106      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
72107}
72108#ifndef SQLITE_OMIT_UTF16
72109SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
72110  return columnName(
72111      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
72112}
72113#endif /* SQLITE_OMIT_UTF16 */
72114#endif /* SQLITE_OMIT_DECLTYPE */
72115
72116#ifdef SQLITE_ENABLE_COLUMN_METADATA
72117/*
72118** Return the name of the database from which a result column derives.
72119** NULL is returned if the result column is an expression or constant or
72120** anything else which is not an unambiguous reference to a database column.
72121*/
72122SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
72123  return columnName(
72124      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
72125}
72126#ifndef SQLITE_OMIT_UTF16
72127SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
72128  return columnName(
72129      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
72130}
72131#endif /* SQLITE_OMIT_UTF16 */
72132
72133/*
72134** Return the name of the table from which a result column derives.
72135** NULL is returned if the result column is an expression or constant or
72136** anything else which is not an unambiguous reference to a database column.
72137*/
72138SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
72139  return columnName(
72140      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
72141}
72142#ifndef SQLITE_OMIT_UTF16
72143SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
72144  return columnName(
72145      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
72146}
72147#endif /* SQLITE_OMIT_UTF16 */
72148
72149/*
72150** Return the name of the table column from which a result column derives.
72151** NULL is returned if the result column is an expression or constant or
72152** anything else which is not an unambiguous reference to a database column.
72153*/
72154SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
72155  return columnName(
72156      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
72157}
72158#ifndef SQLITE_OMIT_UTF16
72159SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
72160  return columnName(
72161      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
72162}
72163#endif /* SQLITE_OMIT_UTF16 */
72164#endif /* SQLITE_ENABLE_COLUMN_METADATA */
72165
72166
72167/******************************* sqlite3_bind_  ***************************
72168**
72169** Routines used to attach values to wildcards in a compiled SQL statement.
72170*/
72171/*
72172** Unbind the value bound to variable i in virtual machine p. This is the
72173** the same as binding a NULL value to the column. If the "i" parameter is
72174** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
72175**
72176** A successful evaluation of this routine acquires the mutex on p.
72177** the mutex is released if any kind of error occurs.
72178**
72179** The error code stored in database p->db is overwritten with the return
72180** value in any case.
72181*/
72182static int vdbeUnbind(Vdbe *p, int i){
72183  Mem *pVar;
72184  if( vdbeSafetyNotNull(p) ){
72185    return SQLITE_MISUSE_BKPT;
72186  }
72187  sqlite3_mutex_enter(p->db->mutex);
72188  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
72189    sqlite3Error(p->db, SQLITE_MISUSE);
72190    sqlite3_mutex_leave(p->db->mutex);
72191    sqlite3_log(SQLITE_MISUSE,
72192        "bind on a busy prepared statement: [%s]", p->zSql);
72193    return SQLITE_MISUSE_BKPT;
72194  }
72195  if( i<1 || i>p->nVar ){
72196    sqlite3Error(p->db, SQLITE_RANGE);
72197    sqlite3_mutex_leave(p->db->mutex);
72198    return SQLITE_RANGE;
72199  }
72200  i--;
72201  pVar = &p->aVar[i];
72202  sqlite3VdbeMemRelease(pVar);
72203  pVar->flags = MEM_Null;
72204  sqlite3Error(p->db, SQLITE_OK);
72205
72206  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
72207  ** binding a new value to this variable invalidates the current query plan.
72208  **
72209  ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
72210  ** parameter in the WHERE clause might influence the choice of query plan
72211  ** for a statement, then the statement will be automatically recompiled,
72212  ** as if there had been a schema change, on the first sqlite3_step() call
72213  ** following any change to the bindings of that parameter.
72214  */
72215  if( p->isPrepareV2 &&
72216     ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
72217  ){
72218    p->expired = 1;
72219  }
72220  return SQLITE_OK;
72221}
72222
72223/*
72224** Bind a text or BLOB value.
72225*/
72226static int bindText(
72227  sqlite3_stmt *pStmt,   /* The statement to bind against */
72228  int i,                 /* Index of the parameter to bind */
72229  const void *zData,     /* Pointer to the data to be bound */
72230  int nData,             /* Number of bytes of data to be bound */
72231  void (*xDel)(void*),   /* Destructor for the data */
72232  u8 encoding            /* Encoding for the data */
72233){
72234  Vdbe *p = (Vdbe *)pStmt;
72235  Mem *pVar;
72236  int rc;
72237
72238  rc = vdbeUnbind(p, i);
72239  if( rc==SQLITE_OK ){
72240    if( zData!=0 ){
72241      pVar = &p->aVar[i-1];
72242      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
72243      if( rc==SQLITE_OK && encoding!=0 ){
72244        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
72245      }
72246      sqlite3Error(p->db, rc);
72247      rc = sqlite3ApiExit(p->db, rc);
72248    }
72249    sqlite3_mutex_leave(p->db->mutex);
72250  }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
72251    xDel((void*)zData);
72252  }
72253  return rc;
72254}
72255
72256
72257/*
72258** Bind a blob value to an SQL statement variable.
72259*/
72260SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(
72261  sqlite3_stmt *pStmt,
72262  int i,
72263  const void *zData,
72264  int nData,
72265  void (*xDel)(void*)
72266){
72267  return bindText(pStmt, i, zData, nData, xDel, 0);
72268}
72269SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(
72270  sqlite3_stmt *pStmt,
72271  int i,
72272  const void *zData,
72273  sqlite3_uint64 nData,
72274  void (*xDel)(void*)
72275){
72276  assert( xDel!=SQLITE_DYNAMIC );
72277  if( nData>0x7fffffff ){
72278    return invokeValueDestructor(zData, xDel, 0);
72279  }else{
72280    return bindText(pStmt, i, zData, (int)nData, xDel, 0);
72281  }
72282}
72283SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
72284  int rc;
72285  Vdbe *p = (Vdbe *)pStmt;
72286  rc = vdbeUnbind(p, i);
72287  if( rc==SQLITE_OK ){
72288    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
72289    sqlite3_mutex_leave(p->db->mutex);
72290  }
72291  return rc;
72292}
72293SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
72294  return sqlite3_bind_int64(p, i, (i64)iValue);
72295}
72296SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
72297  int rc;
72298  Vdbe *p = (Vdbe *)pStmt;
72299  rc = vdbeUnbind(p, i);
72300  if( rc==SQLITE_OK ){
72301    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
72302    sqlite3_mutex_leave(p->db->mutex);
72303  }
72304  return rc;
72305}
72306SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
72307  int rc;
72308  Vdbe *p = (Vdbe*)pStmt;
72309  rc = vdbeUnbind(p, i);
72310  if( rc==SQLITE_OK ){
72311    sqlite3_mutex_leave(p->db->mutex);
72312  }
72313  return rc;
72314}
72315SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(
72316  sqlite3_stmt *pStmt,
72317  int i,
72318  const char *zData,
72319  int nData,
72320  void (*xDel)(void*)
72321){
72322  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
72323}
72324SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(
72325  sqlite3_stmt *pStmt,
72326  int i,
72327  const char *zData,
72328  sqlite3_uint64 nData,
72329  void (*xDel)(void*),
72330  unsigned char enc
72331){
72332  assert( xDel!=SQLITE_DYNAMIC );
72333  if( nData>0x7fffffff ){
72334    return invokeValueDestructor(zData, xDel, 0);
72335  }else{
72336    if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
72337    return bindText(pStmt, i, zData, (int)nData, xDel, enc);
72338  }
72339}
72340#ifndef SQLITE_OMIT_UTF16
72341SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(
72342  sqlite3_stmt *pStmt,
72343  int i,
72344  const void *zData,
72345  int nData,
72346  void (*xDel)(void*)
72347){
72348  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
72349}
72350#endif /* SQLITE_OMIT_UTF16 */
72351SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
72352  int rc;
72353  switch( sqlite3_value_type((sqlite3_value*)pValue) ){
72354    case SQLITE_INTEGER: {
72355      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
72356      break;
72357    }
72358    case SQLITE_FLOAT: {
72359      rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
72360      break;
72361    }
72362    case SQLITE_BLOB: {
72363      if( pValue->flags & MEM_Zero ){
72364        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
72365      }else{
72366        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
72367      }
72368      break;
72369    }
72370    case SQLITE_TEXT: {
72371      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
72372                              pValue->enc);
72373      break;
72374    }
72375    default: {
72376      rc = sqlite3_bind_null(pStmt, i);
72377      break;
72378    }
72379  }
72380  return rc;
72381}
72382SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
72383  int rc;
72384  Vdbe *p = (Vdbe *)pStmt;
72385  rc = vdbeUnbind(p, i);
72386  if( rc==SQLITE_OK ){
72387    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
72388    sqlite3_mutex_leave(p->db->mutex);
72389  }
72390  return rc;
72391}
72392SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
72393  int rc;
72394  Vdbe *p = (Vdbe *)pStmt;
72395  sqlite3_mutex_enter(p->db->mutex);
72396  if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
72397    rc = SQLITE_TOOBIG;
72398  }else{
72399    assert( (n & 0x7FFFFFFF)==n );
72400    rc = sqlite3_bind_zeroblob(pStmt, i, n);
72401  }
72402  rc = sqlite3ApiExit(p->db, rc);
72403  sqlite3_mutex_leave(p->db->mutex);
72404  return rc;
72405}
72406
72407/*
72408** Return the number of wildcards that can be potentially bound to.
72409** This routine is added to support DBD::SQLite.
72410*/
72411SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
72412  Vdbe *p = (Vdbe*)pStmt;
72413  return p ? p->nVar : 0;
72414}
72415
72416/*
72417** Return the name of a wildcard parameter.  Return NULL if the index
72418** is out of range or if the wildcard is unnamed.
72419**
72420** The result is always UTF-8.
72421*/
72422SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
72423  Vdbe *p = (Vdbe*)pStmt;
72424  if( p==0 || i<1 || i>p->nzVar ){
72425    return 0;
72426  }
72427  return p->azVar[i-1];
72428}
72429
72430/*
72431** Given a wildcard parameter name, return the index of the variable
72432** with that name.  If there is no variable with the given name,
72433** return 0.
72434*/
72435SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
72436  int i;
72437  if( p==0 ){
72438    return 0;
72439  }
72440  if( zName ){
72441    for(i=0; i<p->nzVar; i++){
72442      const char *z = p->azVar[i];
72443      if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
72444        return i+1;
72445      }
72446    }
72447  }
72448  return 0;
72449}
72450SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
72451  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
72452}
72453
72454/*
72455** Transfer all bindings from the first statement over to the second.
72456*/
72457SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
72458  Vdbe *pFrom = (Vdbe*)pFromStmt;
72459  Vdbe *pTo = (Vdbe*)pToStmt;
72460  int i;
72461  assert( pTo->db==pFrom->db );
72462  assert( pTo->nVar==pFrom->nVar );
72463  sqlite3_mutex_enter(pTo->db->mutex);
72464  for(i=0; i<pFrom->nVar; i++){
72465    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
72466  }
72467  sqlite3_mutex_leave(pTo->db->mutex);
72468  return SQLITE_OK;
72469}
72470
72471#ifndef SQLITE_OMIT_DEPRECATED
72472/*
72473** Deprecated external interface.  Internal/core SQLite code
72474** should call sqlite3TransferBindings.
72475**
72476** It is misuse to call this routine with statements from different
72477** database connections.  But as this is a deprecated interface, we
72478** will not bother to check for that condition.
72479**
72480** If the two statements contain a different number of bindings, then
72481** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
72482** SQLITE_OK is returned.
72483*/
72484SQLITE_API int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
72485  Vdbe *pFrom = (Vdbe*)pFromStmt;
72486  Vdbe *pTo = (Vdbe*)pToStmt;
72487  if( pFrom->nVar!=pTo->nVar ){
72488    return SQLITE_ERROR;
72489  }
72490  if( pTo->isPrepareV2 && pTo->expmask ){
72491    pTo->expired = 1;
72492  }
72493  if( pFrom->isPrepareV2 && pFrom->expmask ){
72494    pFrom->expired = 1;
72495  }
72496  return sqlite3TransferBindings(pFromStmt, pToStmt);
72497}
72498#endif
72499
72500/*
72501** Return the sqlite3* database handle to which the prepared statement given
72502** in the argument belongs.  This is the same database handle that was
72503** the first argument to the sqlite3_prepare() that was used to create
72504** the statement in the first place.
72505*/
72506SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt *pStmt){
72507  return pStmt ? ((Vdbe*)pStmt)->db : 0;
72508}
72509
72510/*
72511** Return true if the prepared statement is guaranteed to not modify the
72512** database.
72513*/
72514SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
72515  return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
72516}
72517
72518/*
72519** Return true if the prepared statement is in need of being reset.
72520*/
72521SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt *pStmt){
72522  Vdbe *v = (Vdbe*)pStmt;
72523  return v!=0 && v->pc>=0 && v->magic==VDBE_MAGIC_RUN;
72524}
72525
72526/*
72527** Return a pointer to the next prepared statement after pStmt associated
72528** with database connection pDb.  If pStmt is NULL, return the first
72529** prepared statement for the database connection.  Return NULL if there
72530** are no more.
72531*/
72532SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
72533  sqlite3_stmt *pNext;
72534#ifdef SQLITE_ENABLE_API_ARMOR
72535  if( !sqlite3SafetyCheckOk(pDb) ){
72536    (void)SQLITE_MISUSE_BKPT;
72537    return 0;
72538  }
72539#endif
72540  sqlite3_mutex_enter(pDb->mutex);
72541  if( pStmt==0 ){
72542    pNext = (sqlite3_stmt*)pDb->pVdbe;
72543  }else{
72544    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
72545  }
72546  sqlite3_mutex_leave(pDb->mutex);
72547  return pNext;
72548}
72549
72550/*
72551** Return the value of a status counter for a prepared statement
72552*/
72553SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
72554  Vdbe *pVdbe = (Vdbe*)pStmt;
72555  u32 v;
72556#ifdef SQLITE_ENABLE_API_ARMOR
72557  if( !pStmt ){
72558    (void)SQLITE_MISUSE_BKPT;
72559    return 0;
72560  }
72561#endif
72562  v = pVdbe->aCounter[op];
72563  if( resetFlag ) pVdbe->aCounter[op] = 0;
72564  return (int)v;
72565}
72566
72567#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
72568/*
72569** Return status data for a single loop within query pStmt.
72570*/
72571SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
72572  sqlite3_stmt *pStmt,            /* Prepared statement being queried */
72573  int idx,                        /* Index of loop to report on */
72574  int iScanStatusOp,              /* Which metric to return */
72575  void *pOut                      /* OUT: Write the answer here */
72576){
72577  Vdbe *p = (Vdbe*)pStmt;
72578  ScanStatus *pScan;
72579  if( idx<0 || idx>=p->nScan ) return 1;
72580  pScan = &p->aScan[idx];
72581  switch( iScanStatusOp ){
72582    case SQLITE_SCANSTAT_NLOOP: {
72583      *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
72584      break;
72585    }
72586    case SQLITE_SCANSTAT_NVISIT: {
72587      *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
72588      break;
72589    }
72590    case SQLITE_SCANSTAT_EST: {
72591      double r = 1.0;
72592      LogEst x = pScan->nEst;
72593      while( x<100 ){
72594        x += 10;
72595        r *= 0.5;
72596      }
72597      *(double*)pOut = r*sqlite3LogEstToInt(x);
72598      break;
72599    }
72600    case SQLITE_SCANSTAT_NAME: {
72601      *(const char**)pOut = pScan->zName;
72602      break;
72603    }
72604    case SQLITE_SCANSTAT_EXPLAIN: {
72605      if( pScan->addrExplain ){
72606        *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
72607      }else{
72608        *(const char**)pOut = 0;
72609      }
72610      break;
72611    }
72612    case SQLITE_SCANSTAT_SELECTID: {
72613      if( pScan->addrExplain ){
72614        *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
72615      }else{
72616        *(int*)pOut = -1;
72617      }
72618      break;
72619    }
72620    default: {
72621      return 1;
72622    }
72623  }
72624  return 0;
72625}
72626
72627/*
72628** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
72629*/
72630SQLITE_API void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
72631  Vdbe *p = (Vdbe*)pStmt;
72632  memset(p->anExec, 0, p->nOp * sizeof(i64));
72633}
72634#endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
72635
72636/************** End of vdbeapi.c *********************************************/
72637/************** Begin file vdbetrace.c ***************************************/
72638/*
72639** 2009 November 25
72640**
72641** The author disclaims copyright to this source code.  In place of
72642** a legal notice, here is a blessing:
72643**
72644**    May you do good and not evil.
72645**    May you find forgiveness for yourself and forgive others.
72646**    May you share freely, never taking more than you give.
72647**
72648*************************************************************************
72649**
72650** This file contains code used to insert the values of host parameters
72651** (aka "wildcards") into the SQL text output by sqlite3_trace().
72652**
72653** The Vdbe parse-tree explainer is also found here.
72654*/
72655/* #include "sqliteInt.h" */
72656/* #include "vdbeInt.h" */
72657
72658#ifndef SQLITE_OMIT_TRACE
72659
72660/*
72661** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
72662** bytes in this text up to but excluding the first character in
72663** a host parameter.  If the text contains no host parameters, return
72664** the total number of bytes in the text.
72665*/
72666static int findNextHostParameter(const char *zSql, int *pnToken){
72667  int tokenType;
72668  int nTotal = 0;
72669  int n;
72670
72671  *pnToken = 0;
72672  while( zSql[0] ){
72673    n = sqlite3GetToken((u8*)zSql, &tokenType);
72674    assert( n>0 && tokenType!=TK_ILLEGAL );
72675    if( tokenType==TK_VARIABLE ){
72676      *pnToken = n;
72677      break;
72678    }
72679    nTotal += n;
72680    zSql += n;
72681  }
72682  return nTotal;
72683}
72684
72685/*
72686** This function returns a pointer to a nul-terminated string in memory
72687** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
72688** string contains a copy of zRawSql but with host parameters expanded to
72689** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
72690** then the returned string holds a copy of zRawSql with "-- " prepended
72691** to each line of text.
72692**
72693** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
72694** then long strings and blobs are truncated to that many bytes.  This
72695** can be used to prevent unreasonably large trace strings when dealing
72696** with large (multi-megabyte) strings and blobs.
72697**
72698** The calling function is responsible for making sure the memory returned
72699** is eventually freed.
72700**
72701** ALGORITHM:  Scan the input string looking for host parameters in any of
72702** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
72703** string literals, quoted identifier names, and comments.  For text forms,
72704** the host parameter index is found by scanning the prepared
72705** statement for the corresponding OP_Variable opcode.  Once the host
72706** parameter index is known, locate the value in p->aVar[].  Then render
72707** the value as a literal in place of the host parameter name.
72708*/
72709SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
72710  Vdbe *p,                 /* The prepared statement being evaluated */
72711  const char *zRawSql      /* Raw text of the SQL statement */
72712){
72713  sqlite3 *db;             /* The database connection */
72714  int idx = 0;             /* Index of a host parameter */
72715  int nextIndex = 1;       /* Index of next ? host parameter */
72716  int n;                   /* Length of a token prefix */
72717  int nToken;              /* Length of the parameter token */
72718  int i;                   /* Loop counter */
72719  Mem *pVar;               /* Value of a host parameter */
72720  StrAccum out;            /* Accumulate the output here */
72721  char zBase[100];         /* Initial working space */
72722
72723  db = p->db;
72724  sqlite3StrAccumInit(&out, db, zBase, sizeof(zBase),
72725                      db->aLimit[SQLITE_LIMIT_LENGTH]);
72726  if( db->nVdbeExec>1 ){
72727    while( *zRawSql ){
72728      const char *zStart = zRawSql;
72729      while( *(zRawSql++)!='\n' && *zRawSql );
72730      sqlite3StrAccumAppend(&out, "-- ", 3);
72731      assert( (zRawSql - zStart) > 0 );
72732      sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
72733    }
72734  }else if( p->nVar==0 ){
72735    sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
72736  }else{
72737    while( zRawSql[0] ){
72738      n = findNextHostParameter(zRawSql, &nToken);
72739      assert( n>0 );
72740      sqlite3StrAccumAppend(&out, zRawSql, n);
72741      zRawSql += n;
72742      assert( zRawSql[0] || nToken==0 );
72743      if( nToken==0 ) break;
72744      if( zRawSql[0]=='?' ){
72745        if( nToken>1 ){
72746          assert( sqlite3Isdigit(zRawSql[1]) );
72747          sqlite3GetInt32(&zRawSql[1], &idx);
72748        }else{
72749          idx = nextIndex;
72750        }
72751      }else{
72752        assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
72753                zRawSql[0]=='@' || zRawSql[0]=='#' );
72754        testcase( zRawSql[0]==':' );
72755        testcase( zRawSql[0]=='$' );
72756        testcase( zRawSql[0]=='@' );
72757        testcase( zRawSql[0]=='#' );
72758        idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
72759        assert( idx>0 );
72760      }
72761      zRawSql += nToken;
72762      nextIndex = idx + 1;
72763      assert( idx>0 && idx<=p->nVar );
72764      pVar = &p->aVar[idx-1];
72765      if( pVar->flags & MEM_Null ){
72766        sqlite3StrAccumAppend(&out, "NULL", 4);
72767      }else if( pVar->flags & MEM_Int ){
72768        sqlite3XPrintf(&out, 0, "%lld", pVar->u.i);
72769      }else if( pVar->flags & MEM_Real ){
72770        sqlite3XPrintf(&out, 0, "%!.15g", pVar->u.r);
72771      }else if( pVar->flags & MEM_Str ){
72772        int nOut;  /* Number of bytes of the string text to include in output */
72773#ifndef SQLITE_OMIT_UTF16
72774        u8 enc = ENC(db);
72775        Mem utf8;
72776        if( enc!=SQLITE_UTF8 ){
72777          memset(&utf8, 0, sizeof(utf8));
72778          utf8.db = db;
72779          sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
72780          sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
72781          pVar = &utf8;
72782        }
72783#endif
72784        nOut = pVar->n;
72785#ifdef SQLITE_TRACE_SIZE_LIMIT
72786        if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
72787          nOut = SQLITE_TRACE_SIZE_LIMIT;
72788          while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
72789        }
72790#endif
72791        sqlite3XPrintf(&out, 0, "'%.*q'", nOut, pVar->z);
72792#ifdef SQLITE_TRACE_SIZE_LIMIT
72793        if( nOut<pVar->n ){
72794          sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
72795        }
72796#endif
72797#ifndef SQLITE_OMIT_UTF16
72798        if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
72799#endif
72800      }else if( pVar->flags & MEM_Zero ){
72801        sqlite3XPrintf(&out, 0, "zeroblob(%d)", pVar->u.nZero);
72802      }else{
72803        int nOut;  /* Number of bytes of the blob to include in output */
72804        assert( pVar->flags & MEM_Blob );
72805        sqlite3StrAccumAppend(&out, "x'", 2);
72806        nOut = pVar->n;
72807#ifdef SQLITE_TRACE_SIZE_LIMIT
72808        if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
72809#endif
72810        for(i=0; i<nOut; i++){
72811          sqlite3XPrintf(&out, 0, "%02x", pVar->z[i]&0xff);
72812        }
72813        sqlite3StrAccumAppend(&out, "'", 1);
72814#ifdef SQLITE_TRACE_SIZE_LIMIT
72815        if( nOut<pVar->n ){
72816          sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
72817        }
72818#endif
72819      }
72820    }
72821  }
72822  return sqlite3StrAccumFinish(&out);
72823}
72824
72825#endif /* #ifndef SQLITE_OMIT_TRACE */
72826
72827/************** End of vdbetrace.c *******************************************/
72828/************** Begin file vdbe.c ********************************************/
72829/*
72830** 2001 September 15
72831**
72832** The author disclaims copyright to this source code.  In place of
72833** a legal notice, here is a blessing:
72834**
72835**    May you do good and not evil.
72836**    May you find forgiveness for yourself and forgive others.
72837**    May you share freely, never taking more than you give.
72838**
72839*************************************************************************
72840** The code in this file implements the function that runs the
72841** bytecode of a prepared statement.
72842**
72843** Various scripts scan this source file in order to generate HTML
72844** documentation, headers files, or other derived files.  The formatting
72845** of the code in this file is, therefore, important.  See other comments
72846** in this file for details.  If in doubt, do not deviate from existing
72847** commenting and indentation practices when changing or adding code.
72848*/
72849/* #include "sqliteInt.h" */
72850/* #include "vdbeInt.h" */
72851
72852/*
72853** Invoke this macro on memory cells just prior to changing the
72854** value of the cell.  This macro verifies that shallow copies are
72855** not misused.  A shallow copy of a string or blob just copies a
72856** pointer to the string or blob, not the content.  If the original
72857** is changed while the copy is still in use, the string or blob might
72858** be changed out from under the copy.  This macro verifies that nothing
72859** like that ever happens.
72860*/
72861#ifdef SQLITE_DEBUG
72862# define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
72863#else
72864# define memAboutToChange(P,M)
72865#endif
72866
72867/*
72868** The following global variable is incremented every time a cursor
72869** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
72870** procedures use this information to make sure that indices are
72871** working correctly.  This variable has no function other than to
72872** help verify the correct operation of the library.
72873*/
72874#ifdef SQLITE_TEST
72875SQLITE_API int sqlite3_search_count = 0;
72876#endif
72877
72878/*
72879** When this global variable is positive, it gets decremented once before
72880** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
72881** field of the sqlite3 structure is set in order to simulate an interrupt.
72882**
72883** This facility is used for testing purposes only.  It does not function
72884** in an ordinary build.
72885*/
72886#ifdef SQLITE_TEST
72887SQLITE_API int sqlite3_interrupt_count = 0;
72888#endif
72889
72890/*
72891** The next global variable is incremented each type the OP_Sort opcode
72892** is executed.  The test procedures use this information to make sure that
72893** sorting is occurring or not occurring at appropriate times.   This variable
72894** has no function other than to help verify the correct operation of the
72895** library.
72896*/
72897#ifdef SQLITE_TEST
72898SQLITE_API int sqlite3_sort_count = 0;
72899#endif
72900
72901/*
72902** The next global variable records the size of the largest MEM_Blob
72903** or MEM_Str that has been used by a VDBE opcode.  The test procedures
72904** use this information to make sure that the zero-blob functionality
72905** is working correctly.   This variable has no function other than to
72906** help verify the correct operation of the library.
72907*/
72908#ifdef SQLITE_TEST
72909SQLITE_API int sqlite3_max_blobsize = 0;
72910static void updateMaxBlobsize(Mem *p){
72911  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
72912    sqlite3_max_blobsize = p->n;
72913  }
72914}
72915#endif
72916
72917/*
72918** The next global variable is incremented each time the OP_Found opcode
72919** is executed. This is used to test whether or not the foreign key
72920** operation implemented using OP_FkIsZero is working. This variable
72921** has no function other than to help verify the correct operation of the
72922** library.
72923*/
72924#ifdef SQLITE_TEST
72925SQLITE_API int sqlite3_found_count = 0;
72926#endif
72927
72928/*
72929** Test a register to see if it exceeds the current maximum blob size.
72930** If it does, record the new maximum blob size.
72931*/
72932#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
72933# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
72934#else
72935# define UPDATE_MAX_BLOBSIZE(P)
72936#endif
72937
72938/*
72939** Invoke the VDBE coverage callback, if that callback is defined.  This
72940** feature is used for test suite validation only and does not appear an
72941** production builds.
72942**
72943** M is an integer, 2 or 3, that indices how many different ways the
72944** branch can go.  It is usually 2.  "I" is the direction the branch
72945** goes.  0 means falls through.  1 means branch is taken.  2 means the
72946** second alternative branch is taken.
72947**
72948** iSrcLine is the source code line (from the __LINE__ macro) that
72949** generated the VDBE instruction.  This instrumentation assumes that all
72950** source code is in a single file (the amalgamation).  Special values 1
72951** and 2 for the iSrcLine parameter mean that this particular branch is
72952** always taken or never taken, respectively.
72953*/
72954#if !defined(SQLITE_VDBE_COVERAGE)
72955# define VdbeBranchTaken(I,M)
72956#else
72957# define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
72958  static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
72959    if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
72960      M = iSrcLine;
72961      /* Assert the truth of VdbeCoverageAlwaysTaken() and
72962      ** VdbeCoverageNeverTaken() */
72963      assert( (M & I)==I );
72964    }else{
72965      if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/
72966      sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
72967                                      iSrcLine,I,M);
72968    }
72969  }
72970#endif
72971
72972/*
72973** Convert the given register into a string if it isn't one
72974** already. Return non-zero if a malloc() fails.
72975*/
72976#define Stringify(P, enc) \
72977   if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
72978     { goto no_mem; }
72979
72980/*
72981** An ephemeral string value (signified by the MEM_Ephem flag) contains
72982** a pointer to a dynamically allocated string where some other entity
72983** is responsible for deallocating that string.  Because the register
72984** does not control the string, it might be deleted without the register
72985** knowing it.
72986**
72987** This routine converts an ephemeral string into a dynamically allocated
72988** string that the register itself controls.  In other words, it
72989** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
72990*/
72991#define Deephemeralize(P) \
72992   if( ((P)->flags&MEM_Ephem)!=0 \
72993       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
72994
72995/* Return true if the cursor was opened using the OP_OpenSorter opcode. */
72996#define isSorter(x) ((x)->pSorter!=0)
72997
72998/*
72999** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
73000** if we run out of memory.
73001*/
73002static VdbeCursor *allocateCursor(
73003  Vdbe *p,              /* The virtual machine */
73004  int iCur,             /* Index of the new VdbeCursor */
73005  int nField,           /* Number of fields in the table or index */
73006  int iDb,              /* Database the cursor belongs to, or -1 */
73007  int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
73008){
73009  /* Find the memory cell that will be used to store the blob of memory
73010  ** required for this VdbeCursor structure. It is convenient to use a
73011  ** vdbe memory cell to manage the memory allocation required for a
73012  ** VdbeCursor structure for the following reasons:
73013  **
73014  **   * Sometimes cursor numbers are used for a couple of different
73015  **     purposes in a vdbe program. The different uses might require
73016  **     different sized allocations. Memory cells provide growable
73017  **     allocations.
73018  **
73019  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
73020  **     be freed lazily via the sqlite3_release_memory() API. This
73021  **     minimizes the number of malloc calls made by the system.
73022  **
73023  ** Memory cells for cursors are allocated at the top of the address
73024  ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
73025  ** cursor 1 is managed by memory cell (p->nMem-1), etc.
73026  */
73027  Mem *pMem = &p->aMem[p->nMem-iCur];
73028
73029  int nByte;
73030  VdbeCursor *pCx = 0;
73031  nByte =
73032      ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
73033      (isBtreeCursor?sqlite3BtreeCursorSize():0);
73034
73035  assert( iCur<p->nCursor );
73036  if( p->apCsr[iCur] ){
73037    sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
73038    p->apCsr[iCur] = 0;
73039  }
73040  if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
73041    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
73042    memset(pCx, 0, sizeof(VdbeCursor));
73043    pCx->iDb = iDb;
73044    pCx->nField = nField;
73045    pCx->aOffset = &pCx->aType[nField];
73046    if( isBtreeCursor ){
73047      pCx->pCursor = (BtCursor*)
73048          &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
73049      sqlite3BtreeCursorZero(pCx->pCursor);
73050    }
73051  }
73052  return pCx;
73053}
73054
73055/*
73056** Try to convert a value into a numeric representation if we can
73057** do so without loss of information.  In other words, if the string
73058** looks like a number, convert it into a number.  If it does not
73059** look like a number, leave it alone.
73060**
73061** If the bTryForInt flag is true, then extra effort is made to give
73062** an integer representation.  Strings that look like floating point
73063** values but which have no fractional component (example: '48.00')
73064** will have a MEM_Int representation when bTryForInt is true.
73065**
73066** If bTryForInt is false, then if the input string contains a decimal
73067** point or exponential notation, the result is only MEM_Real, even
73068** if there is an exact integer representation of the quantity.
73069*/
73070static void applyNumericAffinity(Mem *pRec, int bTryForInt){
73071  double rValue;
73072  i64 iValue;
73073  u8 enc = pRec->enc;
73074  assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
73075  if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
73076  if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
73077    pRec->u.i = iValue;
73078    pRec->flags |= MEM_Int;
73079  }else{
73080    pRec->u.r = rValue;
73081    pRec->flags |= MEM_Real;
73082    if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
73083  }
73084}
73085
73086/*
73087** Processing is determine by the affinity parameter:
73088**
73089** SQLITE_AFF_INTEGER:
73090** SQLITE_AFF_REAL:
73091** SQLITE_AFF_NUMERIC:
73092**    Try to convert pRec to an integer representation or a
73093**    floating-point representation if an integer representation
73094**    is not possible.  Note that the integer representation is
73095**    always preferred, even if the affinity is REAL, because
73096**    an integer representation is more space efficient on disk.
73097**
73098** SQLITE_AFF_TEXT:
73099**    Convert pRec to a text representation.
73100**
73101** SQLITE_AFF_BLOB:
73102**    No-op.  pRec is unchanged.
73103*/
73104static void applyAffinity(
73105  Mem *pRec,          /* The value to apply affinity to */
73106  char affinity,      /* The affinity to be applied */
73107  u8 enc              /* Use this text encoding */
73108){
73109  if( affinity>=SQLITE_AFF_NUMERIC ){
73110    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
73111             || affinity==SQLITE_AFF_NUMERIC );
73112    if( (pRec->flags & MEM_Int)==0 ){
73113      if( (pRec->flags & MEM_Real)==0 ){
73114        if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
73115      }else{
73116        sqlite3VdbeIntegerAffinity(pRec);
73117      }
73118    }
73119  }else if( affinity==SQLITE_AFF_TEXT ){
73120    /* Only attempt the conversion to TEXT if there is an integer or real
73121    ** representation (blob and NULL do not get converted) but no string
73122    ** representation.
73123    */
73124    if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
73125      sqlite3VdbeMemStringify(pRec, enc, 1);
73126    }
73127    pRec->flags &= ~(MEM_Real|MEM_Int);
73128  }
73129}
73130
73131/*
73132** Try to convert the type of a function argument or a result column
73133** into a numeric representation.  Use either INTEGER or REAL whichever
73134** is appropriate.  But only do the conversion if it is possible without
73135** loss of information and return the revised type of the argument.
73136*/
73137SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value *pVal){
73138  int eType = sqlite3_value_type(pVal);
73139  if( eType==SQLITE_TEXT ){
73140    Mem *pMem = (Mem*)pVal;
73141    applyNumericAffinity(pMem, 0);
73142    eType = sqlite3_value_type(pVal);
73143  }
73144  return eType;
73145}
73146
73147/*
73148** Exported version of applyAffinity(). This one works on sqlite3_value*,
73149** not the internal Mem* type.
73150*/
73151SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
73152  sqlite3_value *pVal,
73153  u8 affinity,
73154  u8 enc
73155){
73156  applyAffinity((Mem *)pVal, affinity, enc);
73157}
73158
73159/*
73160** pMem currently only holds a string type (or maybe a BLOB that we can
73161** interpret as a string if we want to).  Compute its corresponding
73162** numeric type, if has one.  Set the pMem->u.r and pMem->u.i fields
73163** accordingly.
73164*/
73165static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
73166  assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
73167  assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
73168  if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
73169    return 0;
73170  }
73171  if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
73172    return MEM_Int;
73173  }
73174  return MEM_Real;
73175}
73176
73177/*
73178** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
73179** none.
73180**
73181** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
73182** But it does set pMem->u.r and pMem->u.i appropriately.
73183*/
73184static u16 numericType(Mem *pMem){
73185  if( pMem->flags & (MEM_Int|MEM_Real) ){
73186    return pMem->flags & (MEM_Int|MEM_Real);
73187  }
73188  if( pMem->flags & (MEM_Str|MEM_Blob) ){
73189    return computeNumericType(pMem);
73190  }
73191  return 0;
73192}
73193
73194#ifdef SQLITE_DEBUG
73195/*
73196** Write a nice string representation of the contents of cell pMem
73197** into buffer zBuf, length nBuf.
73198*/
73199SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
73200  char *zCsr = zBuf;
73201  int f = pMem->flags;
73202
73203  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
73204
73205  if( f&MEM_Blob ){
73206    int i;
73207    char c;
73208    if( f & MEM_Dyn ){
73209      c = 'z';
73210      assert( (f & (MEM_Static|MEM_Ephem))==0 );
73211    }else if( f & MEM_Static ){
73212      c = 't';
73213      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
73214    }else if( f & MEM_Ephem ){
73215      c = 'e';
73216      assert( (f & (MEM_Static|MEM_Dyn))==0 );
73217    }else{
73218      c = 's';
73219    }
73220
73221    sqlite3_snprintf(100, zCsr, "%c", c);
73222    zCsr += sqlite3Strlen30(zCsr);
73223    sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
73224    zCsr += sqlite3Strlen30(zCsr);
73225    for(i=0; i<16 && i<pMem->n; i++){
73226      sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
73227      zCsr += sqlite3Strlen30(zCsr);
73228    }
73229    for(i=0; i<16 && i<pMem->n; i++){
73230      char z = pMem->z[i];
73231      if( z<32 || z>126 ) *zCsr++ = '.';
73232      else *zCsr++ = z;
73233    }
73234
73235    sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
73236    zCsr += sqlite3Strlen30(zCsr);
73237    if( f & MEM_Zero ){
73238      sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
73239      zCsr += sqlite3Strlen30(zCsr);
73240    }
73241    *zCsr = '\0';
73242  }else if( f & MEM_Str ){
73243    int j, k;
73244    zBuf[0] = ' ';
73245    if( f & MEM_Dyn ){
73246      zBuf[1] = 'z';
73247      assert( (f & (MEM_Static|MEM_Ephem))==0 );
73248    }else if( f & MEM_Static ){
73249      zBuf[1] = 't';
73250      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
73251    }else if( f & MEM_Ephem ){
73252      zBuf[1] = 'e';
73253      assert( (f & (MEM_Static|MEM_Dyn))==0 );
73254    }else{
73255      zBuf[1] = 's';
73256    }
73257    k = 2;
73258    sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
73259    k += sqlite3Strlen30(&zBuf[k]);
73260    zBuf[k++] = '[';
73261    for(j=0; j<15 && j<pMem->n; j++){
73262      u8 c = pMem->z[j];
73263      if( c>=0x20 && c<0x7f ){
73264        zBuf[k++] = c;
73265      }else{
73266        zBuf[k++] = '.';
73267      }
73268    }
73269    zBuf[k++] = ']';
73270    sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
73271    k += sqlite3Strlen30(&zBuf[k]);
73272    zBuf[k++] = 0;
73273  }
73274}
73275#endif
73276
73277#ifdef SQLITE_DEBUG
73278/*
73279** Print the value of a register for tracing purposes:
73280*/
73281static void memTracePrint(Mem *p){
73282  if( p->flags & MEM_Undefined ){
73283    printf(" undefined");
73284  }else if( p->flags & MEM_Null ){
73285    printf(" NULL");
73286  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
73287    printf(" si:%lld", p->u.i);
73288  }else if( p->flags & MEM_Int ){
73289    printf(" i:%lld", p->u.i);
73290#ifndef SQLITE_OMIT_FLOATING_POINT
73291  }else if( p->flags & MEM_Real ){
73292    printf(" r:%g", p->u.r);
73293#endif
73294  }else if( p->flags & MEM_RowSet ){
73295    printf(" (rowset)");
73296  }else{
73297    char zBuf[200];
73298    sqlite3VdbeMemPrettyPrint(p, zBuf);
73299    printf(" %s", zBuf);
73300  }
73301}
73302static void registerTrace(int iReg, Mem *p){
73303  printf("REG[%d] = ", iReg);
73304  memTracePrint(p);
73305  printf("\n");
73306}
73307#endif
73308
73309#ifdef SQLITE_DEBUG
73310#  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
73311#else
73312#  define REGISTER_TRACE(R,M)
73313#endif
73314
73315
73316#ifdef VDBE_PROFILE
73317
73318/*
73319** hwtime.h contains inline assembler code for implementing
73320** high-performance timing routines.
73321*/
73322/************** Include hwtime.h in the middle of vdbe.c *********************/
73323/************** Begin file hwtime.h ******************************************/
73324/*
73325** 2008 May 27
73326**
73327** The author disclaims copyright to this source code.  In place of
73328** a legal notice, here is a blessing:
73329**
73330**    May you do good and not evil.
73331**    May you find forgiveness for yourself and forgive others.
73332**    May you share freely, never taking more than you give.
73333**
73334******************************************************************************
73335**
73336** This file contains inline asm code for retrieving "high-performance"
73337** counters for x86 class CPUs.
73338*/
73339#ifndef _HWTIME_H_
73340#define _HWTIME_H_
73341
73342/*
73343** The following routine only works on pentium-class (or newer) processors.
73344** It uses the RDTSC opcode to read the cycle count value out of the
73345** processor and returns that value.  This can be used for high-res
73346** profiling.
73347*/
73348#if (defined(__GNUC__) || defined(_MSC_VER)) && \
73349      (defined(i386) || defined(__i386__) || defined(_M_IX86))
73350
73351  #if defined(__GNUC__)
73352
73353  __inline__ sqlite_uint64 sqlite3Hwtime(void){
73354     unsigned int lo, hi;
73355     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
73356     return (sqlite_uint64)hi << 32 | lo;
73357  }
73358
73359  #elif defined(_MSC_VER)
73360
73361  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
73362     __asm {
73363        rdtsc
73364        ret       ; return value at EDX:EAX
73365     }
73366  }
73367
73368  #endif
73369
73370#elif (defined(__GNUC__) && defined(__x86_64__))
73371
73372  __inline__ sqlite_uint64 sqlite3Hwtime(void){
73373      unsigned long val;
73374      __asm__ __volatile__ ("rdtsc" : "=A" (val));
73375      return val;
73376  }
73377
73378#elif (defined(__GNUC__) && defined(__ppc__))
73379
73380  __inline__ sqlite_uint64 sqlite3Hwtime(void){
73381      unsigned long long retval;
73382      unsigned long junk;
73383      __asm__ __volatile__ ("\n\
73384          1:      mftbu   %1\n\
73385                  mftb    %L0\n\
73386                  mftbu   %0\n\
73387                  cmpw    %0,%1\n\
73388                  bne     1b"
73389                  : "=r" (retval), "=r" (junk));
73390      return retval;
73391  }
73392
73393#else
73394
73395  #error Need implementation of sqlite3Hwtime() for your platform.
73396
73397  /*
73398  ** To compile without implementing sqlite3Hwtime() for your platform,
73399  ** you can remove the above #error and use the following
73400  ** stub function.  You will lose timing support for many
73401  ** of the debugging and testing utilities, but it should at
73402  ** least compile and run.
73403  */
73404SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
73405
73406#endif
73407
73408#endif /* !defined(_HWTIME_H_) */
73409
73410/************** End of hwtime.h **********************************************/
73411/************** Continuing where we left off in vdbe.c ***********************/
73412
73413#endif
73414
73415#ifndef NDEBUG
73416/*
73417** This function is only called from within an assert() expression. It
73418** checks that the sqlite3.nTransaction variable is correctly set to
73419** the number of non-transaction savepoints currently in the
73420** linked list starting at sqlite3.pSavepoint.
73421**
73422** Usage:
73423**
73424**     assert( checkSavepointCount(db) );
73425*/
73426static int checkSavepointCount(sqlite3 *db){
73427  int n = 0;
73428  Savepoint *p;
73429  for(p=db->pSavepoint; p; p=p->pNext) n++;
73430  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
73431  return 1;
73432}
73433#endif
73434
73435/*
73436** Return the register of pOp->p2 after first preparing it to be
73437** overwritten with an integer value.
73438*/
73439static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
73440  Mem *pOut;
73441  assert( pOp->p2>0 );
73442  assert( pOp->p2<=(p->nMem-p->nCursor) );
73443  pOut = &p->aMem[pOp->p2];
73444  memAboutToChange(p, pOut);
73445  if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
73446  pOut->flags = MEM_Int;
73447  return pOut;
73448}
73449
73450
73451/*
73452** Execute as much of a VDBE program as we can.
73453** This is the core of sqlite3_step().
73454*/
73455SQLITE_PRIVATE int sqlite3VdbeExec(
73456  Vdbe *p                    /* The VDBE */
73457){
73458  Op *aOp = p->aOp;          /* Copy of p->aOp */
73459  Op *pOp = aOp;             /* Current operation */
73460#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
73461  Op *pOrigOp;               /* Value of pOp at the top of the loop */
73462#endif
73463  int rc = SQLITE_OK;        /* Value to return */
73464  sqlite3 *db = p->db;       /* The database */
73465  u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
73466  u8 encoding = ENC(db);     /* The database encoding */
73467  int iCompare = 0;          /* Result of last OP_Compare operation */
73468  unsigned nVmStep = 0;      /* Number of virtual machine steps */
73469#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
73470  unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
73471#endif
73472  Mem *aMem = p->aMem;       /* Copy of p->aMem */
73473  Mem *pIn1 = 0;             /* 1st input operand */
73474  Mem *pIn2 = 0;             /* 2nd input operand */
73475  Mem *pIn3 = 0;             /* 3rd input operand */
73476  Mem *pOut = 0;             /* Output operand */
73477  int *aPermute = 0;         /* Permutation of columns for OP_Compare */
73478  i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
73479#ifdef VDBE_PROFILE
73480  u64 start;                 /* CPU clock count at start of opcode */
73481#endif
73482  /*** INSERT STACK UNION HERE ***/
73483
73484  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
73485  sqlite3VdbeEnter(p);
73486  if( p->rc==SQLITE_NOMEM ){
73487    /* This happens if a malloc() inside a call to sqlite3_column_text() or
73488    ** sqlite3_column_text16() failed.  */
73489    goto no_mem;
73490  }
73491  assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
73492  assert( p->bIsReader || p->readOnly!=0 );
73493  p->rc = SQLITE_OK;
73494  p->iCurrentTime = 0;
73495  assert( p->explain==0 );
73496  p->pResultSet = 0;
73497  db->busyHandler.nBusy = 0;
73498  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
73499  sqlite3VdbeIOTraceSql(p);
73500#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
73501  if( db->xProgress ){
73502    u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
73503    assert( 0 < db->nProgressOps );
73504    nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
73505  }
73506#endif
73507#ifdef SQLITE_DEBUG
73508  sqlite3BeginBenignMalloc();
73509  if( p->pc==0
73510   && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
73511  ){
73512    int i;
73513    int once = 1;
73514    sqlite3VdbePrintSql(p);
73515    if( p->db->flags & SQLITE_VdbeListing ){
73516      printf("VDBE Program Listing:\n");
73517      for(i=0; i<p->nOp; i++){
73518        sqlite3VdbePrintOp(stdout, i, &aOp[i]);
73519      }
73520    }
73521    if( p->db->flags & SQLITE_VdbeEQP ){
73522      for(i=0; i<p->nOp; i++){
73523        if( aOp[i].opcode==OP_Explain ){
73524          if( once ) printf("VDBE Query Plan:\n");
73525          printf("%s\n", aOp[i].p4.z);
73526          once = 0;
73527        }
73528      }
73529    }
73530    if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
73531  }
73532  sqlite3EndBenignMalloc();
73533#endif
73534  for(pOp=&aOp[p->pc]; rc==SQLITE_OK; pOp++){
73535    assert( pOp>=aOp && pOp<&aOp[p->nOp]);
73536    if( db->mallocFailed ) goto no_mem;
73537#ifdef VDBE_PROFILE
73538    start = sqlite3Hwtime();
73539#endif
73540    nVmStep++;
73541#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
73542    if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
73543#endif
73544
73545    /* Only allow tracing if SQLITE_DEBUG is defined.
73546    */
73547#ifdef SQLITE_DEBUG
73548    if( db->flags & SQLITE_VdbeTrace ){
73549      sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
73550    }
73551#endif
73552
73553
73554    /* Check to see if we need to simulate an interrupt.  This only happens
73555    ** if we have a special test build.
73556    */
73557#ifdef SQLITE_TEST
73558    if( sqlite3_interrupt_count>0 ){
73559      sqlite3_interrupt_count--;
73560      if( sqlite3_interrupt_count==0 ){
73561        sqlite3_interrupt(db);
73562      }
73563    }
73564#endif
73565
73566    /* Sanity checking on other operands */
73567#ifdef SQLITE_DEBUG
73568    assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
73569    if( (pOp->opflags & OPFLG_IN1)!=0 ){
73570      assert( pOp->p1>0 );
73571      assert( pOp->p1<=(p->nMem-p->nCursor) );
73572      assert( memIsValid(&aMem[pOp->p1]) );
73573      assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
73574      REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
73575    }
73576    if( (pOp->opflags & OPFLG_IN2)!=0 ){
73577      assert( pOp->p2>0 );
73578      assert( pOp->p2<=(p->nMem-p->nCursor) );
73579      assert( memIsValid(&aMem[pOp->p2]) );
73580      assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
73581      REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
73582    }
73583    if( (pOp->opflags & OPFLG_IN3)!=0 ){
73584      assert( pOp->p3>0 );
73585      assert( pOp->p3<=(p->nMem-p->nCursor) );
73586      assert( memIsValid(&aMem[pOp->p3]) );
73587      assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
73588      REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
73589    }
73590    if( (pOp->opflags & OPFLG_OUT2)!=0 ){
73591      assert( pOp->p2>0 );
73592      assert( pOp->p2<=(p->nMem-p->nCursor) );
73593      memAboutToChange(p, &aMem[pOp->p2]);
73594    }
73595    if( (pOp->opflags & OPFLG_OUT3)!=0 ){
73596      assert( pOp->p3>0 );
73597      assert( pOp->p3<=(p->nMem-p->nCursor) );
73598      memAboutToChange(p, &aMem[pOp->p3]);
73599    }
73600#endif
73601#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
73602    pOrigOp = pOp;
73603#endif
73604
73605    switch( pOp->opcode ){
73606
73607/*****************************************************************************
73608** What follows is a massive switch statement where each case implements a
73609** separate instruction in the virtual machine.  If we follow the usual
73610** indentation conventions, each case should be indented by 6 spaces.  But
73611** that is a lot of wasted space on the left margin.  So the code within
73612** the switch statement will break with convention and be flush-left. Another
73613** big comment (similar to this one) will mark the point in the code where
73614** we transition back to normal indentation.
73615**
73616** The formatting of each case is important.  The makefile for SQLite
73617** generates two C files "opcodes.h" and "opcodes.c" by scanning this
73618** file looking for lines that begin with "case OP_".  The opcodes.h files
73619** will be filled with #defines that give unique integer values to each
73620** opcode and the opcodes.c file is filled with an array of strings where
73621** each string is the symbolic name for the corresponding opcode.  If the
73622** case statement is followed by a comment of the form "/# same as ... #/"
73623** that comment is used to determine the particular value of the opcode.
73624**
73625** Other keywords in the comment that follows each case are used to
73626** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
73627** Keywords include: in1, in2, in3, out2, out3.  See
73628** the mkopcodeh.awk script for additional information.
73629**
73630** Documentation about VDBE opcodes is generated by scanning this file
73631** for lines of that contain "Opcode:".  That line and all subsequent
73632** comment lines are used in the generation of the opcode.html documentation
73633** file.
73634**
73635** SUMMARY:
73636**
73637**     Formatting is important to scripts that scan this file.
73638**     Do not deviate from the formatting style currently in use.
73639**
73640*****************************************************************************/
73641
73642/* Opcode:  Goto * P2 * * *
73643**
73644** An unconditional jump to address P2.
73645** The next instruction executed will be
73646** the one at index P2 from the beginning of
73647** the program.
73648**
73649** The P1 parameter is not actually used by this opcode.  However, it
73650** is sometimes set to 1 instead of 0 as a hint to the command-line shell
73651** that this Goto is the bottom of a loop and that the lines from P2 down
73652** to the current line should be indented for EXPLAIN output.
73653*/
73654case OP_Goto: {             /* jump */
73655jump_to_p2_and_check_for_interrupt:
73656  pOp = &aOp[pOp->p2 - 1];
73657
73658  /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
73659  ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
73660  ** completion.  Check to see if sqlite3_interrupt() has been called
73661  ** or if the progress callback needs to be invoked.
73662  **
73663  ** This code uses unstructured "goto" statements and does not look clean.
73664  ** But that is not due to sloppy coding habits. The code is written this
73665  ** way for performance, to avoid having to run the interrupt and progress
73666  ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%
73667  ** faster according to "valgrind --tool=cachegrind" */
73668check_for_interrupt:
73669  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
73670#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
73671  /* Call the progress callback if it is configured and the required number
73672  ** of VDBE ops have been executed (either since this invocation of
73673  ** sqlite3VdbeExec() or since last time the progress callback was called).
73674  ** If the progress callback returns non-zero, exit the virtual machine with
73675  ** a return code SQLITE_ABORT.
73676  */
73677  if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
73678    assert( db->nProgressOps!=0 );
73679    nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
73680    if( db->xProgress(db->pProgressArg) ){
73681      rc = SQLITE_INTERRUPT;
73682      goto vdbe_error_halt;
73683    }
73684  }
73685#endif
73686
73687  break;
73688}
73689
73690/* Opcode:  Gosub P1 P2 * * *
73691**
73692** Write the current address onto register P1
73693** and then jump to address P2.
73694*/
73695case OP_Gosub: {            /* jump */
73696  assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
73697  pIn1 = &aMem[pOp->p1];
73698  assert( VdbeMemDynamic(pIn1)==0 );
73699  memAboutToChange(p, pIn1);
73700  pIn1->flags = MEM_Int;
73701  pIn1->u.i = (int)(pOp-aOp);
73702  REGISTER_TRACE(pOp->p1, pIn1);
73703
73704  /* Most jump operations do a goto to this spot in order to update
73705  ** the pOp pointer. */
73706jump_to_p2:
73707  pOp = &aOp[pOp->p2 - 1];
73708  break;
73709}
73710
73711/* Opcode:  Return P1 * * * *
73712**
73713** Jump to the next instruction after the address in register P1.  After
73714** the jump, register P1 becomes undefined.
73715*/
73716case OP_Return: {           /* in1 */
73717  pIn1 = &aMem[pOp->p1];
73718  assert( pIn1->flags==MEM_Int );
73719  pOp = &aOp[pIn1->u.i];
73720  pIn1->flags = MEM_Undefined;
73721  break;
73722}
73723
73724/* Opcode: InitCoroutine P1 P2 P3 * *
73725**
73726** Set up register P1 so that it will Yield to the coroutine
73727** located at address P3.
73728**
73729** If P2!=0 then the coroutine implementation immediately follows
73730** this opcode.  So jump over the coroutine implementation to
73731** address P2.
73732**
73733** See also: EndCoroutine
73734*/
73735case OP_InitCoroutine: {     /* jump */
73736  assert( pOp->p1>0 &&  pOp->p1<=(p->nMem-p->nCursor) );
73737  assert( pOp->p2>=0 && pOp->p2<p->nOp );
73738  assert( pOp->p3>=0 && pOp->p3<p->nOp );
73739  pOut = &aMem[pOp->p1];
73740  assert( !VdbeMemDynamic(pOut) );
73741  pOut->u.i = pOp->p3 - 1;
73742  pOut->flags = MEM_Int;
73743  if( pOp->p2 ) goto jump_to_p2;
73744  break;
73745}
73746
73747/* Opcode:  EndCoroutine P1 * * * *
73748**
73749** The instruction at the address in register P1 is a Yield.
73750** Jump to the P2 parameter of that Yield.
73751** After the jump, register P1 becomes undefined.
73752**
73753** See also: InitCoroutine
73754*/
73755case OP_EndCoroutine: {           /* in1 */
73756  VdbeOp *pCaller;
73757  pIn1 = &aMem[pOp->p1];
73758  assert( pIn1->flags==MEM_Int );
73759  assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
73760  pCaller = &aOp[pIn1->u.i];
73761  assert( pCaller->opcode==OP_Yield );
73762  assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
73763  pOp = &aOp[pCaller->p2 - 1];
73764  pIn1->flags = MEM_Undefined;
73765  break;
73766}
73767
73768/* Opcode:  Yield P1 P2 * * *
73769**
73770** Swap the program counter with the value in register P1.  This
73771** has the effect of yielding to a coroutine.
73772**
73773** If the coroutine that is launched by this instruction ends with
73774** Yield or Return then continue to the next instruction.  But if
73775** the coroutine launched by this instruction ends with
73776** EndCoroutine, then jump to P2 rather than continuing with the
73777** next instruction.
73778**
73779** See also: InitCoroutine
73780*/
73781case OP_Yield: {            /* in1, jump */
73782  int pcDest;
73783  pIn1 = &aMem[pOp->p1];
73784  assert( VdbeMemDynamic(pIn1)==0 );
73785  pIn1->flags = MEM_Int;
73786  pcDest = (int)pIn1->u.i;
73787  pIn1->u.i = (int)(pOp - aOp);
73788  REGISTER_TRACE(pOp->p1, pIn1);
73789  pOp = &aOp[pcDest];
73790  break;
73791}
73792
73793/* Opcode:  HaltIfNull  P1 P2 P3 P4 P5
73794** Synopsis:  if r[P3]=null halt
73795**
73796** Check the value in register P3.  If it is NULL then Halt using
73797** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
73798** value in register P3 is not NULL, then this routine is a no-op.
73799** The P5 parameter should be 1.
73800*/
73801case OP_HaltIfNull: {      /* in3 */
73802  pIn3 = &aMem[pOp->p3];
73803  if( (pIn3->flags & MEM_Null)==0 ) break;
73804  /* Fall through into OP_Halt */
73805}
73806
73807/* Opcode:  Halt P1 P2 * P4 P5
73808**
73809** Exit immediately.  All open cursors, etc are closed
73810** automatically.
73811**
73812** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
73813** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
73814** For errors, it can be some other value.  If P1!=0 then P2 will determine
73815** whether or not to rollback the current transaction.  Do not rollback
73816** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
73817** then back out all changes that have occurred during this execution of the
73818** VDBE, but do not rollback the transaction.
73819**
73820** If P4 is not null then it is an error message string.
73821**
73822** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
73823**
73824**    0:  (no change)
73825**    1:  NOT NULL contraint failed: P4
73826**    2:  UNIQUE constraint failed: P4
73827**    3:  CHECK constraint failed: P4
73828**    4:  FOREIGN KEY constraint failed: P4
73829**
73830** If P5 is not zero and P4 is NULL, then everything after the ":" is
73831** omitted.
73832**
73833** There is an implied "Halt 0 0 0" instruction inserted at the very end of
73834** every program.  So a jump past the last instruction of the program
73835** is the same as executing Halt.
73836*/
73837case OP_Halt: {
73838  const char *zType;
73839  const char *zLogFmt;
73840  VdbeFrame *pFrame;
73841  int pcx;
73842
73843  pcx = (int)(pOp - aOp);
73844  if( pOp->p1==SQLITE_OK && p->pFrame ){
73845    /* Halt the sub-program. Return control to the parent frame. */
73846    pFrame = p->pFrame;
73847    p->pFrame = pFrame->pParent;
73848    p->nFrame--;
73849    sqlite3VdbeSetChanges(db, p->nChange);
73850    pcx = sqlite3VdbeFrameRestore(pFrame);
73851    lastRowid = db->lastRowid;
73852    if( pOp->p2==OE_Ignore ){
73853      /* Instruction pcx is the OP_Program that invoked the sub-program
73854      ** currently being halted. If the p2 instruction of this OP_Halt
73855      ** instruction is set to OE_Ignore, then the sub-program is throwing
73856      ** an IGNORE exception. In this case jump to the address specified
73857      ** as the p2 of the calling OP_Program.  */
73858      pcx = p->aOp[pcx].p2-1;
73859    }
73860    aOp = p->aOp;
73861    aMem = p->aMem;
73862    pOp = &aOp[pcx];
73863    break;
73864  }
73865  p->rc = pOp->p1;
73866  p->errorAction = (u8)pOp->p2;
73867  p->pc = pcx;
73868  if( p->rc ){
73869    if( pOp->p5 ){
73870      static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
73871                                             "FOREIGN KEY" };
73872      assert( pOp->p5>=1 && pOp->p5<=4 );
73873      testcase( pOp->p5==1 );
73874      testcase( pOp->p5==2 );
73875      testcase( pOp->p5==3 );
73876      testcase( pOp->p5==4 );
73877      zType = azType[pOp->p5-1];
73878    }else{
73879      zType = 0;
73880    }
73881    assert( zType!=0 || pOp->p4.z!=0 );
73882    zLogFmt = "abort at %d in [%s]: %s";
73883    if( zType && pOp->p4.z ){
73884      sqlite3VdbeError(p, "%s constraint failed: %s", zType, pOp->p4.z);
73885    }else if( pOp->p4.z ){
73886      sqlite3VdbeError(p, "%s", pOp->p4.z);
73887    }else{
73888      sqlite3VdbeError(p, "%s constraint failed", zType);
73889    }
73890    sqlite3_log(pOp->p1, zLogFmt, pcx, p->zSql, p->zErrMsg);
73891  }
73892  rc = sqlite3VdbeHalt(p);
73893  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
73894  if( rc==SQLITE_BUSY ){
73895    p->rc = rc = SQLITE_BUSY;
73896  }else{
73897    assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
73898    assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
73899    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
73900  }
73901  goto vdbe_return;
73902}
73903
73904/* Opcode: Integer P1 P2 * * *
73905** Synopsis: r[P2]=P1
73906**
73907** The 32-bit integer value P1 is written into register P2.
73908*/
73909case OP_Integer: {         /* out2 */
73910  pOut = out2Prerelease(p, pOp);
73911  pOut->u.i = pOp->p1;
73912  break;
73913}
73914
73915/* Opcode: Int64 * P2 * P4 *
73916** Synopsis: r[P2]=P4
73917**
73918** P4 is a pointer to a 64-bit integer value.
73919** Write that value into register P2.
73920*/
73921case OP_Int64: {           /* out2 */
73922  pOut = out2Prerelease(p, pOp);
73923  assert( pOp->p4.pI64!=0 );
73924  pOut->u.i = *pOp->p4.pI64;
73925  break;
73926}
73927
73928#ifndef SQLITE_OMIT_FLOATING_POINT
73929/* Opcode: Real * P2 * P4 *
73930** Synopsis: r[P2]=P4
73931**
73932** P4 is a pointer to a 64-bit floating point value.
73933** Write that value into register P2.
73934*/
73935case OP_Real: {            /* same as TK_FLOAT, out2 */
73936  pOut = out2Prerelease(p, pOp);
73937  pOut->flags = MEM_Real;
73938  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
73939  pOut->u.r = *pOp->p4.pReal;
73940  break;
73941}
73942#endif
73943
73944/* Opcode: String8 * P2 * P4 *
73945** Synopsis: r[P2]='P4'
73946**
73947** P4 points to a nul terminated UTF-8 string. This opcode is transformed
73948** into a String opcode before it is executed for the first time.  During
73949** this transformation, the length of string P4 is computed and stored
73950** as the P1 parameter.
73951*/
73952case OP_String8: {         /* same as TK_STRING, out2 */
73953  assert( pOp->p4.z!=0 );
73954  pOut = out2Prerelease(p, pOp);
73955  pOp->opcode = OP_String;
73956  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
73957
73958#ifndef SQLITE_OMIT_UTF16
73959  if( encoding!=SQLITE_UTF8 ){
73960    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
73961    if( rc==SQLITE_TOOBIG ) goto too_big;
73962    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
73963    assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
73964    assert( VdbeMemDynamic(pOut)==0 );
73965    pOut->szMalloc = 0;
73966    pOut->flags |= MEM_Static;
73967    if( pOp->p4type==P4_DYNAMIC ){
73968      sqlite3DbFree(db, pOp->p4.z);
73969    }
73970    pOp->p4type = P4_DYNAMIC;
73971    pOp->p4.z = pOut->z;
73972    pOp->p1 = pOut->n;
73973  }
73974#endif
73975  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
73976    goto too_big;
73977  }
73978  /* Fall through to the next case, OP_String */
73979}
73980
73981/* Opcode: String P1 P2 P3 P4 P5
73982** Synopsis: r[P2]='P4' (len=P1)
73983**
73984** The string value P4 of length P1 (bytes) is stored in register P2.
73985**
73986** If P5!=0 and the content of register P3 is greater than zero, then
73987** the datatype of the register P2 is converted to BLOB.  The content is
73988** the same sequence of bytes, it is merely interpreted as a BLOB instead
73989** of a string, as if it had been CAST.
73990*/
73991case OP_String: {          /* out2 */
73992  assert( pOp->p4.z!=0 );
73993  pOut = out2Prerelease(p, pOp);
73994  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
73995  pOut->z = pOp->p4.z;
73996  pOut->n = pOp->p1;
73997  pOut->enc = encoding;
73998  UPDATE_MAX_BLOBSIZE(pOut);
73999  if( pOp->p5 ){
74000    assert( pOp->p3>0 );
74001    assert( pOp->p3<=(p->nMem-p->nCursor) );
74002    pIn3 = &aMem[pOp->p3];
74003    assert( pIn3->flags & MEM_Int );
74004    if( pIn3->u.i ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
74005  }
74006  break;
74007}
74008
74009/* Opcode: Null P1 P2 P3 * *
74010** Synopsis:  r[P2..P3]=NULL
74011**
74012** Write a NULL into registers P2.  If P3 greater than P2, then also write
74013** NULL into register P3 and every register in between P2 and P3.  If P3
74014** is less than P2 (typically P3 is zero) then only register P2 is
74015** set to NULL.
74016**
74017** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
74018** NULL values will not compare equal even if SQLITE_NULLEQ is set on
74019** OP_Ne or OP_Eq.
74020*/
74021case OP_Null: {           /* out2 */
74022  int cnt;
74023  u16 nullFlag;
74024  pOut = out2Prerelease(p, pOp);
74025  cnt = pOp->p3-pOp->p2;
74026  assert( pOp->p3<=(p->nMem-p->nCursor) );
74027  pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
74028  while( cnt>0 ){
74029    pOut++;
74030    memAboutToChange(p, pOut);
74031    sqlite3VdbeMemSetNull(pOut);
74032    pOut->flags = nullFlag;
74033    cnt--;
74034  }
74035  break;
74036}
74037
74038/* Opcode: SoftNull P1 * * * *
74039** Synopsis:  r[P1]=NULL
74040**
74041** Set register P1 to have the value NULL as seen by the OP_MakeRecord
74042** instruction, but do not free any string or blob memory associated with
74043** the register, so that if the value was a string or blob that was
74044** previously copied using OP_SCopy, the copies will continue to be valid.
74045*/
74046case OP_SoftNull: {
74047  assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
74048  pOut = &aMem[pOp->p1];
74049  pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
74050  break;
74051}
74052
74053/* Opcode: Blob P1 P2 * P4 *
74054** Synopsis: r[P2]=P4 (len=P1)
74055**
74056** P4 points to a blob of data P1 bytes long.  Store this
74057** blob in register P2.
74058*/
74059case OP_Blob: {                /* out2 */
74060  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
74061  pOut = out2Prerelease(p, pOp);
74062  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
74063  pOut->enc = encoding;
74064  UPDATE_MAX_BLOBSIZE(pOut);
74065  break;
74066}
74067
74068/* Opcode: Variable P1 P2 * P4 *
74069** Synopsis: r[P2]=parameter(P1,P4)
74070**
74071** Transfer the values of bound parameter P1 into register P2
74072**
74073** If the parameter is named, then its name appears in P4.
74074** The P4 value is used by sqlite3_bind_parameter_name().
74075*/
74076case OP_Variable: {            /* out2 */
74077  Mem *pVar;       /* Value being transferred */
74078
74079  assert( pOp->p1>0 && pOp->p1<=p->nVar );
74080  assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
74081  pVar = &p->aVar[pOp->p1 - 1];
74082  if( sqlite3VdbeMemTooBig(pVar) ){
74083    goto too_big;
74084  }
74085  pOut = out2Prerelease(p, pOp);
74086  sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
74087  UPDATE_MAX_BLOBSIZE(pOut);
74088  break;
74089}
74090
74091/* Opcode: Move P1 P2 P3 * *
74092** Synopsis:  r[P2@P3]=r[P1@P3]
74093**
74094** Move the P3 values in register P1..P1+P3-1 over into
74095** registers P2..P2+P3-1.  Registers P1..P1+P3-1 are
74096** left holding a NULL.  It is an error for register ranges
74097** P1..P1+P3-1 and P2..P2+P3-1 to overlap.  It is an error
74098** for P3 to be less than 1.
74099*/
74100case OP_Move: {
74101  int n;           /* Number of registers left to copy */
74102  int p1;          /* Register to copy from */
74103  int p2;          /* Register to copy to */
74104
74105  n = pOp->p3;
74106  p1 = pOp->p1;
74107  p2 = pOp->p2;
74108  assert( n>0 && p1>0 && p2>0 );
74109  assert( p1+n<=p2 || p2+n<=p1 );
74110
74111  pIn1 = &aMem[p1];
74112  pOut = &aMem[p2];
74113  do{
74114    assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
74115    assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
74116    assert( memIsValid(pIn1) );
74117    memAboutToChange(p, pOut);
74118    sqlite3VdbeMemMove(pOut, pIn1);
74119#ifdef SQLITE_DEBUG
74120    if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
74121      pOut->pScopyFrom += pOp->p2 - p1;
74122    }
74123#endif
74124    Deephemeralize(pOut);
74125    REGISTER_TRACE(p2++, pOut);
74126    pIn1++;
74127    pOut++;
74128  }while( --n );
74129  break;
74130}
74131
74132/* Opcode: Copy P1 P2 P3 * *
74133** Synopsis: r[P2@P3+1]=r[P1@P3+1]
74134**
74135** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
74136**
74137** This instruction makes a deep copy of the value.  A duplicate
74138** is made of any string or blob constant.  See also OP_SCopy.
74139*/
74140case OP_Copy: {
74141  int n;
74142
74143  n = pOp->p3;
74144  pIn1 = &aMem[pOp->p1];
74145  pOut = &aMem[pOp->p2];
74146  assert( pOut!=pIn1 );
74147  while( 1 ){
74148    sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
74149    Deephemeralize(pOut);
74150#ifdef SQLITE_DEBUG
74151    pOut->pScopyFrom = 0;
74152#endif
74153    REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
74154    if( (n--)==0 ) break;
74155    pOut++;
74156    pIn1++;
74157  }
74158  break;
74159}
74160
74161/* Opcode: SCopy P1 P2 * * *
74162** Synopsis: r[P2]=r[P1]
74163**
74164** Make a shallow copy of register P1 into register P2.
74165**
74166** This instruction makes a shallow copy of the value.  If the value
74167** is a string or blob, then the copy is only a pointer to the
74168** original and hence if the original changes so will the copy.
74169** Worse, if the original is deallocated, the copy becomes invalid.
74170** Thus the program must guarantee that the original will not change
74171** during the lifetime of the copy.  Use OP_Copy to make a complete
74172** copy.
74173*/
74174case OP_SCopy: {            /* out2 */
74175  pIn1 = &aMem[pOp->p1];
74176  pOut = &aMem[pOp->p2];
74177  assert( pOut!=pIn1 );
74178  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
74179#ifdef SQLITE_DEBUG
74180  if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
74181#endif
74182  break;
74183}
74184
74185/* Opcode: ResultRow P1 P2 * * *
74186** Synopsis:  output=r[P1@P2]
74187**
74188** The registers P1 through P1+P2-1 contain a single row of
74189** results. This opcode causes the sqlite3_step() call to terminate
74190** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
74191** structure to provide access to the r(P1)..r(P1+P2-1) values as
74192** the result row.
74193*/
74194case OP_ResultRow: {
74195  Mem *pMem;
74196  int i;
74197  assert( p->nResColumn==pOp->p2 );
74198  assert( pOp->p1>0 );
74199  assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
74200
74201#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
74202  /* Run the progress counter just before returning.
74203  */
74204  if( db->xProgress!=0
74205   && nVmStep>=nProgressLimit
74206   && db->xProgress(db->pProgressArg)!=0
74207  ){
74208    rc = SQLITE_INTERRUPT;
74209    goto vdbe_error_halt;
74210  }
74211#endif
74212
74213  /* If this statement has violated immediate foreign key constraints, do
74214  ** not return the number of rows modified. And do not RELEASE the statement
74215  ** transaction. It needs to be rolled back.  */
74216  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
74217    assert( db->flags&SQLITE_CountRows );
74218    assert( p->usesStmtJournal );
74219    break;
74220  }
74221
74222  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
74223  ** DML statements invoke this opcode to return the number of rows
74224  ** modified to the user. This is the only way that a VM that
74225  ** opens a statement transaction may invoke this opcode.
74226  **
74227  ** In case this is such a statement, close any statement transaction
74228  ** opened by this VM before returning control to the user. This is to
74229  ** ensure that statement-transactions are always nested, not overlapping.
74230  ** If the open statement-transaction is not closed here, then the user
74231  ** may step another VM that opens its own statement transaction. This
74232  ** may lead to overlapping statement transactions.
74233  **
74234  ** The statement transaction is never a top-level transaction.  Hence
74235  ** the RELEASE call below can never fail.
74236  */
74237  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
74238  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
74239  if( NEVER(rc!=SQLITE_OK) ){
74240    break;
74241  }
74242
74243  /* Invalidate all ephemeral cursor row caches */
74244  p->cacheCtr = (p->cacheCtr + 2)|1;
74245
74246  /* Make sure the results of the current row are \000 terminated
74247  ** and have an assigned type.  The results are de-ephemeralized as
74248  ** a side effect.
74249  */
74250  pMem = p->pResultSet = &aMem[pOp->p1];
74251  for(i=0; i<pOp->p2; i++){
74252    assert( memIsValid(&pMem[i]) );
74253    Deephemeralize(&pMem[i]);
74254    assert( (pMem[i].flags & MEM_Ephem)==0
74255            || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
74256    sqlite3VdbeMemNulTerminate(&pMem[i]);
74257    REGISTER_TRACE(pOp->p1+i, &pMem[i]);
74258  }
74259  if( db->mallocFailed ) goto no_mem;
74260
74261  /* Return SQLITE_ROW
74262  */
74263  p->pc = (int)(pOp - aOp) + 1;
74264  rc = SQLITE_ROW;
74265  goto vdbe_return;
74266}
74267
74268/* Opcode: Concat P1 P2 P3 * *
74269** Synopsis: r[P3]=r[P2]+r[P1]
74270**
74271** Add the text in register P1 onto the end of the text in
74272** register P2 and store the result in register P3.
74273** If either the P1 or P2 text are NULL then store NULL in P3.
74274**
74275**   P3 = P2 || P1
74276**
74277** It is illegal for P1 and P3 to be the same register. Sometimes,
74278** if P3 is the same register as P2, the implementation is able
74279** to avoid a memcpy().
74280*/
74281case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
74282  i64 nByte;
74283
74284  pIn1 = &aMem[pOp->p1];
74285  pIn2 = &aMem[pOp->p2];
74286  pOut = &aMem[pOp->p3];
74287  assert( pIn1!=pOut );
74288  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
74289    sqlite3VdbeMemSetNull(pOut);
74290    break;
74291  }
74292  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
74293  Stringify(pIn1, encoding);
74294  Stringify(pIn2, encoding);
74295  nByte = pIn1->n + pIn2->n;
74296  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
74297    goto too_big;
74298  }
74299  if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
74300    goto no_mem;
74301  }
74302  MemSetTypeFlag(pOut, MEM_Str);
74303  if( pOut!=pIn2 ){
74304    memcpy(pOut->z, pIn2->z, pIn2->n);
74305  }
74306  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
74307  pOut->z[nByte]=0;
74308  pOut->z[nByte+1] = 0;
74309  pOut->flags |= MEM_Term;
74310  pOut->n = (int)nByte;
74311  pOut->enc = encoding;
74312  UPDATE_MAX_BLOBSIZE(pOut);
74313  break;
74314}
74315
74316/* Opcode: Add P1 P2 P3 * *
74317** Synopsis:  r[P3]=r[P1]+r[P2]
74318**
74319** Add the value in register P1 to the value in register P2
74320** and store the result in register P3.
74321** If either input is NULL, the result is NULL.
74322*/
74323/* Opcode: Multiply P1 P2 P3 * *
74324** Synopsis:  r[P3]=r[P1]*r[P2]
74325**
74326**
74327** Multiply the value in register P1 by the value in register P2
74328** and store the result in register P3.
74329** If either input is NULL, the result is NULL.
74330*/
74331/* Opcode: Subtract P1 P2 P3 * *
74332** Synopsis:  r[P3]=r[P2]-r[P1]
74333**
74334** Subtract the value in register P1 from the value in register P2
74335** and store the result in register P3.
74336** If either input is NULL, the result is NULL.
74337*/
74338/* Opcode: Divide P1 P2 P3 * *
74339** Synopsis:  r[P3]=r[P2]/r[P1]
74340**
74341** Divide the value in register P1 by the value in register P2
74342** and store the result in register P3 (P3=P2/P1). If the value in
74343** register P1 is zero, then the result is NULL. If either input is
74344** NULL, the result is NULL.
74345*/
74346/* Opcode: Remainder P1 P2 P3 * *
74347** Synopsis:  r[P3]=r[P2]%r[P1]
74348**
74349** Compute the remainder after integer register P2 is divided by
74350** register P1 and store the result in register P3.
74351** If the value in register P1 is zero the result is NULL.
74352** If either operand is NULL, the result is NULL.
74353*/
74354case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
74355case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
74356case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
74357case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
74358case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
74359  char bIntint;   /* Started out as two integer operands */
74360  u16 flags;      /* Combined MEM_* flags from both inputs */
74361  u16 type1;      /* Numeric type of left operand */
74362  u16 type2;      /* Numeric type of right operand */
74363  i64 iA;         /* Integer value of left operand */
74364  i64 iB;         /* Integer value of right operand */
74365  double rA;      /* Real value of left operand */
74366  double rB;      /* Real value of right operand */
74367
74368  pIn1 = &aMem[pOp->p1];
74369  type1 = numericType(pIn1);
74370  pIn2 = &aMem[pOp->p2];
74371  type2 = numericType(pIn2);
74372  pOut = &aMem[pOp->p3];
74373  flags = pIn1->flags | pIn2->flags;
74374  if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
74375  if( (type1 & type2 & MEM_Int)!=0 ){
74376    iA = pIn1->u.i;
74377    iB = pIn2->u.i;
74378    bIntint = 1;
74379    switch( pOp->opcode ){
74380      case OP_Add:       if( sqlite3AddInt64(&iB,iA) ) goto fp_math;  break;
74381      case OP_Subtract:  if( sqlite3SubInt64(&iB,iA) ) goto fp_math;  break;
74382      case OP_Multiply:  if( sqlite3MulInt64(&iB,iA) ) goto fp_math;  break;
74383      case OP_Divide: {
74384        if( iA==0 ) goto arithmetic_result_is_null;
74385        if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
74386        iB /= iA;
74387        break;
74388      }
74389      default: {
74390        if( iA==0 ) goto arithmetic_result_is_null;
74391        if( iA==-1 ) iA = 1;
74392        iB %= iA;
74393        break;
74394      }
74395    }
74396    pOut->u.i = iB;
74397    MemSetTypeFlag(pOut, MEM_Int);
74398  }else{
74399    bIntint = 0;
74400fp_math:
74401    rA = sqlite3VdbeRealValue(pIn1);
74402    rB = sqlite3VdbeRealValue(pIn2);
74403    switch( pOp->opcode ){
74404      case OP_Add:         rB += rA;       break;
74405      case OP_Subtract:    rB -= rA;       break;
74406      case OP_Multiply:    rB *= rA;       break;
74407      case OP_Divide: {
74408        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
74409        if( rA==(double)0 ) goto arithmetic_result_is_null;
74410        rB /= rA;
74411        break;
74412      }
74413      default: {
74414        iA = (i64)rA;
74415        iB = (i64)rB;
74416        if( iA==0 ) goto arithmetic_result_is_null;
74417        if( iA==-1 ) iA = 1;
74418        rB = (double)(iB % iA);
74419        break;
74420      }
74421    }
74422#ifdef SQLITE_OMIT_FLOATING_POINT
74423    pOut->u.i = rB;
74424    MemSetTypeFlag(pOut, MEM_Int);
74425#else
74426    if( sqlite3IsNaN(rB) ){
74427      goto arithmetic_result_is_null;
74428    }
74429    pOut->u.r = rB;
74430    MemSetTypeFlag(pOut, MEM_Real);
74431    if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
74432      sqlite3VdbeIntegerAffinity(pOut);
74433    }
74434#endif
74435  }
74436  break;
74437
74438arithmetic_result_is_null:
74439  sqlite3VdbeMemSetNull(pOut);
74440  break;
74441}
74442
74443/* Opcode: CollSeq P1 * * P4
74444**
74445** P4 is a pointer to a CollSeq struct. If the next call to a user function
74446** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
74447** be returned. This is used by the built-in min(), max() and nullif()
74448** functions.
74449**
74450** If P1 is not zero, then it is a register that a subsequent min() or
74451** max() aggregate will set to 1 if the current row is not the minimum or
74452** maximum.  The P1 register is initialized to 0 by this instruction.
74453**
74454** The interface used by the implementation of the aforementioned functions
74455** to retrieve the collation sequence set by this opcode is not available
74456** publicly.  Only built-in functions have access to this feature.
74457*/
74458case OP_CollSeq: {
74459  assert( pOp->p4type==P4_COLLSEQ );
74460  if( pOp->p1 ){
74461    sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
74462  }
74463  break;
74464}
74465
74466/* Opcode: Function0 P1 P2 P3 P4 P5
74467** Synopsis: r[P3]=func(r[P2@P5])
74468**
74469** Invoke a user function (P4 is a pointer to a FuncDef object that
74470** defines the function) with P5 arguments taken from register P2 and
74471** successors.  The result of the function is stored in register P3.
74472** Register P3 must not be one of the function inputs.
74473**
74474** P1 is a 32-bit bitmask indicating whether or not each argument to the
74475** function was determined to be constant at compile time. If the first
74476** argument was constant then bit 0 of P1 is set. This is used to determine
74477** whether meta data associated with a user function argument using the
74478** sqlite3_set_auxdata() API may be safely retained until the next
74479** invocation of this opcode.
74480**
74481** See also: Function, AggStep, AggFinal
74482*/
74483/* Opcode: Function P1 P2 P3 P4 P5
74484** Synopsis: r[P3]=func(r[P2@P5])
74485**
74486** Invoke a user function (P4 is a pointer to an sqlite3_context object that
74487** contains a pointer to the function to be run) with P5 arguments taken
74488** from register P2 and successors.  The result of the function is stored
74489** in register P3.  Register P3 must not be one of the function inputs.
74490**
74491** P1 is a 32-bit bitmask indicating whether or not each argument to the
74492** function was determined to be constant at compile time. If the first
74493** argument was constant then bit 0 of P1 is set. This is used to determine
74494** whether meta data associated with a user function argument using the
74495** sqlite3_set_auxdata() API may be safely retained until the next
74496** invocation of this opcode.
74497**
74498** SQL functions are initially coded as OP_Function0 with P4 pointing
74499** to a FuncDef object.  But on first evaluation, the P4 operand is
74500** automatically converted into an sqlite3_context object and the operation
74501** changed to this OP_Function opcode.  In this way, the initialization of
74502** the sqlite3_context object occurs only once, rather than once for each
74503** evaluation of the function.
74504**
74505** See also: Function0, AggStep, AggFinal
74506*/
74507case OP_Function0: {
74508  int n;
74509  sqlite3_context *pCtx;
74510
74511  assert( pOp->p4type==P4_FUNCDEF );
74512  n = pOp->p5;
74513  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
74514  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
74515  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
74516  pCtx = sqlite3DbMallocRaw(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
74517  if( pCtx==0 ) goto no_mem;
74518  pCtx->pOut = 0;
74519  pCtx->pFunc = pOp->p4.pFunc;
74520  pCtx->iOp = (int)(pOp - aOp);
74521  pCtx->pVdbe = p;
74522  pCtx->argc = n;
74523  pOp->p4type = P4_FUNCCTX;
74524  pOp->p4.pCtx = pCtx;
74525  pOp->opcode = OP_Function;
74526  /* Fall through into OP_Function */
74527}
74528case OP_Function: {
74529  int i;
74530  sqlite3_context *pCtx;
74531
74532  assert( pOp->p4type==P4_FUNCCTX );
74533  pCtx = pOp->p4.pCtx;
74534
74535  /* If this function is inside of a trigger, the register array in aMem[]
74536  ** might change from one evaluation to the next.  The next block of code
74537  ** checks to see if the register array has changed, and if so it
74538  ** reinitializes the relavant parts of the sqlite3_context object */
74539  pOut = &aMem[pOp->p3];
74540  if( pCtx->pOut != pOut ){
74541    pCtx->pOut = pOut;
74542    for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
74543  }
74544
74545  memAboutToChange(p, pCtx->pOut);
74546#ifdef SQLITE_DEBUG
74547  for(i=0; i<pCtx->argc; i++){
74548    assert( memIsValid(pCtx->argv[i]) );
74549    REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
74550  }
74551#endif
74552  MemSetTypeFlag(pCtx->pOut, MEM_Null);
74553  pCtx->fErrorOrAux = 0;
74554  db->lastRowid = lastRowid;
74555  (*pCtx->pFunc->xFunc)(pCtx, pCtx->argc, pCtx->argv); /* IMP: R-24505-23230 */
74556  lastRowid = db->lastRowid;  /* Remember rowid changes made by xFunc */
74557
74558  /* If the function returned an error, throw an exception */
74559  if( pCtx->fErrorOrAux ){
74560    if( pCtx->isError ){
74561      sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
74562      rc = pCtx->isError;
74563    }
74564    sqlite3VdbeDeleteAuxData(p, pCtx->iOp, pOp->p1);
74565  }
74566
74567  /* Copy the result of the function into register P3 */
74568  if( pOut->flags & (MEM_Str|MEM_Blob) ){
74569    sqlite3VdbeChangeEncoding(pCtx->pOut, encoding);
74570    if( sqlite3VdbeMemTooBig(pCtx->pOut) ) goto too_big;
74571  }
74572
74573  REGISTER_TRACE(pOp->p3, pCtx->pOut);
74574  UPDATE_MAX_BLOBSIZE(pCtx->pOut);
74575  break;
74576}
74577
74578/* Opcode: BitAnd P1 P2 P3 * *
74579** Synopsis:  r[P3]=r[P1]&r[P2]
74580**
74581** Take the bit-wise AND of the values in register P1 and P2 and
74582** store the result in register P3.
74583** If either input is NULL, the result is NULL.
74584*/
74585/* Opcode: BitOr P1 P2 P3 * *
74586** Synopsis:  r[P3]=r[P1]|r[P2]
74587**
74588** Take the bit-wise OR of the values in register P1 and P2 and
74589** store the result in register P3.
74590** If either input is NULL, the result is NULL.
74591*/
74592/* Opcode: ShiftLeft P1 P2 P3 * *
74593** Synopsis:  r[P3]=r[P2]<<r[P1]
74594**
74595** Shift the integer value in register P2 to the left by the
74596** number of bits specified by the integer in register P1.
74597** Store the result in register P3.
74598** If either input is NULL, the result is NULL.
74599*/
74600/* Opcode: ShiftRight P1 P2 P3 * *
74601** Synopsis:  r[P3]=r[P2]>>r[P1]
74602**
74603** Shift the integer value in register P2 to the right by the
74604** number of bits specified by the integer in register P1.
74605** Store the result in register P3.
74606** If either input is NULL, the result is NULL.
74607*/
74608case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
74609case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
74610case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
74611case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
74612  i64 iA;
74613  u64 uA;
74614  i64 iB;
74615  u8 op;
74616
74617  pIn1 = &aMem[pOp->p1];
74618  pIn2 = &aMem[pOp->p2];
74619  pOut = &aMem[pOp->p3];
74620  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
74621    sqlite3VdbeMemSetNull(pOut);
74622    break;
74623  }
74624  iA = sqlite3VdbeIntValue(pIn2);
74625  iB = sqlite3VdbeIntValue(pIn1);
74626  op = pOp->opcode;
74627  if( op==OP_BitAnd ){
74628    iA &= iB;
74629  }else if( op==OP_BitOr ){
74630    iA |= iB;
74631  }else if( iB!=0 ){
74632    assert( op==OP_ShiftRight || op==OP_ShiftLeft );
74633
74634    /* If shifting by a negative amount, shift in the other direction */
74635    if( iB<0 ){
74636      assert( OP_ShiftRight==OP_ShiftLeft+1 );
74637      op = 2*OP_ShiftLeft + 1 - op;
74638      iB = iB>(-64) ? -iB : 64;
74639    }
74640
74641    if( iB>=64 ){
74642      iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
74643    }else{
74644      memcpy(&uA, &iA, sizeof(uA));
74645      if( op==OP_ShiftLeft ){
74646        uA <<= iB;
74647      }else{
74648        uA >>= iB;
74649        /* Sign-extend on a right shift of a negative number */
74650        if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
74651      }
74652      memcpy(&iA, &uA, sizeof(iA));
74653    }
74654  }
74655  pOut->u.i = iA;
74656  MemSetTypeFlag(pOut, MEM_Int);
74657  break;
74658}
74659
74660/* Opcode: AddImm  P1 P2 * * *
74661** Synopsis:  r[P1]=r[P1]+P2
74662**
74663** Add the constant P2 to the value in register P1.
74664** The result is always an integer.
74665**
74666** To force any register to be an integer, just add 0.
74667*/
74668case OP_AddImm: {            /* in1 */
74669  pIn1 = &aMem[pOp->p1];
74670  memAboutToChange(p, pIn1);
74671  sqlite3VdbeMemIntegerify(pIn1);
74672  pIn1->u.i += pOp->p2;
74673  break;
74674}
74675
74676/* Opcode: MustBeInt P1 P2 * * *
74677**
74678** Force the value in register P1 to be an integer.  If the value
74679** in P1 is not an integer and cannot be converted into an integer
74680** without data loss, then jump immediately to P2, or if P2==0
74681** raise an SQLITE_MISMATCH exception.
74682*/
74683case OP_MustBeInt: {            /* jump, in1 */
74684  pIn1 = &aMem[pOp->p1];
74685  if( (pIn1->flags & MEM_Int)==0 ){
74686    applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
74687    VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
74688    if( (pIn1->flags & MEM_Int)==0 ){
74689      if( pOp->p2==0 ){
74690        rc = SQLITE_MISMATCH;
74691        goto abort_due_to_error;
74692      }else{
74693        goto jump_to_p2;
74694      }
74695    }
74696  }
74697  MemSetTypeFlag(pIn1, MEM_Int);
74698  break;
74699}
74700
74701#ifndef SQLITE_OMIT_FLOATING_POINT
74702/* Opcode: RealAffinity P1 * * * *
74703**
74704** If register P1 holds an integer convert it to a real value.
74705**
74706** This opcode is used when extracting information from a column that
74707** has REAL affinity.  Such column values may still be stored as
74708** integers, for space efficiency, but after extraction we want them
74709** to have only a real value.
74710*/
74711case OP_RealAffinity: {                  /* in1 */
74712  pIn1 = &aMem[pOp->p1];
74713  if( pIn1->flags & MEM_Int ){
74714    sqlite3VdbeMemRealify(pIn1);
74715  }
74716  break;
74717}
74718#endif
74719
74720#ifndef SQLITE_OMIT_CAST
74721/* Opcode: Cast P1 P2 * * *
74722** Synopsis: affinity(r[P1])
74723**
74724** Force the value in register P1 to be the type defined by P2.
74725**
74726** <ul>
74727** <li value="97"> TEXT
74728** <li value="98"> BLOB
74729** <li value="99"> NUMERIC
74730** <li value="100"> INTEGER
74731** <li value="101"> REAL
74732** </ul>
74733**
74734** A NULL value is not changed by this routine.  It remains NULL.
74735*/
74736case OP_Cast: {                  /* in1 */
74737  assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
74738  testcase( pOp->p2==SQLITE_AFF_TEXT );
74739  testcase( pOp->p2==SQLITE_AFF_BLOB );
74740  testcase( pOp->p2==SQLITE_AFF_NUMERIC );
74741  testcase( pOp->p2==SQLITE_AFF_INTEGER );
74742  testcase( pOp->p2==SQLITE_AFF_REAL );
74743  pIn1 = &aMem[pOp->p1];
74744  memAboutToChange(p, pIn1);
74745  rc = ExpandBlob(pIn1);
74746  sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
74747  UPDATE_MAX_BLOBSIZE(pIn1);
74748  break;
74749}
74750#endif /* SQLITE_OMIT_CAST */
74751
74752/* Opcode: Lt P1 P2 P3 P4 P5
74753** Synopsis: if r[P1]<r[P3] goto P2
74754**
74755** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
74756** jump to address P2.
74757**
74758** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
74759** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
74760** bit is clear then fall through if either operand is NULL.
74761**
74762** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
74763** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
74764** to coerce both inputs according to this affinity before the
74765** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
74766** affinity is used. Note that the affinity conversions are stored
74767** back into the input registers P1 and P3.  So this opcode can cause
74768** persistent changes to registers P1 and P3.
74769**
74770** Once any conversions have taken place, and neither value is NULL,
74771** the values are compared. If both values are blobs then memcmp() is
74772** used to determine the results of the comparison.  If both values
74773** are text, then the appropriate collating function specified in
74774** P4 is  used to do the comparison.  If P4 is not specified then
74775** memcmp() is used to compare text string.  If both values are
74776** numeric, then a numeric comparison is used. If the two values
74777** are of different types, then numbers are considered less than
74778** strings and strings are considered less than blobs.
74779**
74780** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
74781** store a boolean result (either 0, or 1, or NULL) in register P2.
74782**
74783** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
74784** equal to one another, provided that they do not have their MEM_Cleared
74785** bit set.
74786*/
74787/* Opcode: Ne P1 P2 P3 P4 P5
74788** Synopsis: if r[P1]!=r[P3] goto P2
74789**
74790** This works just like the Lt opcode except that the jump is taken if
74791** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
74792** additional information.
74793**
74794** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
74795** true or false and is never NULL.  If both operands are NULL then the result
74796** of comparison is false.  If either operand is NULL then the result is true.
74797** If neither operand is NULL the result is the same as it would be if
74798** the SQLITE_NULLEQ flag were omitted from P5.
74799*/
74800/* Opcode: Eq P1 P2 P3 P4 P5
74801** Synopsis: if r[P1]==r[P3] goto P2
74802**
74803** This works just like the Lt opcode except that the jump is taken if
74804** the operands in registers P1 and P3 are equal.
74805** See the Lt opcode for additional information.
74806**
74807** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
74808** true or false and is never NULL.  If both operands are NULL then the result
74809** of comparison is true.  If either operand is NULL then the result is false.
74810** If neither operand is NULL the result is the same as it would be if
74811** the SQLITE_NULLEQ flag were omitted from P5.
74812*/
74813/* Opcode: Le P1 P2 P3 P4 P5
74814** Synopsis: if r[P1]<=r[P3] goto P2
74815**
74816** This works just like the Lt opcode except that the jump is taken if
74817** the content of register P3 is less than or equal to the content of
74818** register P1.  See the Lt opcode for additional information.
74819*/
74820/* Opcode: Gt P1 P2 P3 P4 P5
74821** Synopsis: if r[P1]>r[P3] goto P2
74822**
74823** This works just like the Lt opcode except that the jump is taken if
74824** the content of register P3 is greater than the content of
74825** register P1.  See the Lt opcode for additional information.
74826*/
74827/* Opcode: Ge P1 P2 P3 P4 P5
74828** Synopsis: if r[P1]>=r[P3] goto P2
74829**
74830** This works just like the Lt opcode except that the jump is taken if
74831** the content of register P3 is greater than or equal to the content of
74832** register P1.  See the Lt opcode for additional information.
74833*/
74834case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
74835case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
74836case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
74837case OP_Le:               /* same as TK_LE, jump, in1, in3 */
74838case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
74839case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
74840  int res;            /* Result of the comparison of pIn1 against pIn3 */
74841  char affinity;      /* Affinity to use for comparison */
74842  u16 flags1;         /* Copy of initial value of pIn1->flags */
74843  u16 flags3;         /* Copy of initial value of pIn3->flags */
74844
74845  pIn1 = &aMem[pOp->p1];
74846  pIn3 = &aMem[pOp->p3];
74847  flags1 = pIn1->flags;
74848  flags3 = pIn3->flags;
74849  if( (flags1 | flags3)&MEM_Null ){
74850    /* One or both operands are NULL */
74851    if( pOp->p5 & SQLITE_NULLEQ ){
74852      /* If SQLITE_NULLEQ is set (which will only happen if the operator is
74853      ** OP_Eq or OP_Ne) then take the jump or not depending on whether
74854      ** or not both operands are null.
74855      */
74856      assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
74857      assert( (flags1 & MEM_Cleared)==0 );
74858      assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
74859      if( (flags1&MEM_Null)!=0
74860       && (flags3&MEM_Null)!=0
74861       && (flags3&MEM_Cleared)==0
74862      ){
74863        res = 0;  /* Results are equal */
74864      }else{
74865        res = 1;  /* Results are not equal */
74866      }
74867    }else{
74868      /* SQLITE_NULLEQ is clear and at least one operand is NULL,
74869      ** then the result is always NULL.
74870      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
74871      */
74872      if( pOp->p5 & SQLITE_STOREP2 ){
74873        pOut = &aMem[pOp->p2];
74874        MemSetTypeFlag(pOut, MEM_Null);
74875        REGISTER_TRACE(pOp->p2, pOut);
74876      }else{
74877        VdbeBranchTaken(2,3);
74878        if( pOp->p5 & SQLITE_JUMPIFNULL ){
74879          goto jump_to_p2;
74880        }
74881      }
74882      break;
74883    }
74884  }else{
74885    /* Neither operand is NULL.  Do a comparison. */
74886    affinity = pOp->p5 & SQLITE_AFF_MASK;
74887    if( affinity>=SQLITE_AFF_NUMERIC ){
74888      if( (pIn1->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
74889        applyNumericAffinity(pIn1,0);
74890      }
74891      if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
74892        applyNumericAffinity(pIn3,0);
74893      }
74894    }else if( affinity==SQLITE_AFF_TEXT ){
74895      if( (pIn1->flags & MEM_Str)==0 && (pIn1->flags & (MEM_Int|MEM_Real))!=0 ){
74896        testcase( pIn1->flags & MEM_Int );
74897        testcase( pIn1->flags & MEM_Real );
74898        sqlite3VdbeMemStringify(pIn1, encoding, 1);
74899        testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
74900        flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
74901      }
74902      if( (pIn3->flags & MEM_Str)==0 && (pIn3->flags & (MEM_Int|MEM_Real))!=0 ){
74903        testcase( pIn3->flags & MEM_Int );
74904        testcase( pIn3->flags & MEM_Real );
74905        sqlite3VdbeMemStringify(pIn3, encoding, 1);
74906        testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
74907        flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
74908      }
74909    }
74910    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
74911    if( pIn1->flags & MEM_Zero ){
74912      sqlite3VdbeMemExpandBlob(pIn1);
74913      flags1 &= ~MEM_Zero;
74914    }
74915    if( pIn3->flags & MEM_Zero ){
74916      sqlite3VdbeMemExpandBlob(pIn3);
74917      flags3 &= ~MEM_Zero;
74918    }
74919    if( db->mallocFailed ) goto no_mem;
74920    res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
74921  }
74922  switch( pOp->opcode ){
74923    case OP_Eq:    res = res==0;     break;
74924    case OP_Ne:    res = res!=0;     break;
74925    case OP_Lt:    res = res<0;      break;
74926    case OP_Le:    res = res<=0;     break;
74927    case OP_Gt:    res = res>0;      break;
74928    default:       res = res>=0;     break;
74929  }
74930
74931  /* Undo any changes made by applyAffinity() to the input registers. */
74932  assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
74933  pIn1->flags = flags1;
74934  assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
74935  pIn3->flags = flags3;
74936
74937  if( pOp->p5 & SQLITE_STOREP2 ){
74938    pOut = &aMem[pOp->p2];
74939    memAboutToChange(p, pOut);
74940    MemSetTypeFlag(pOut, MEM_Int);
74941    pOut->u.i = res;
74942    REGISTER_TRACE(pOp->p2, pOut);
74943  }else{
74944    VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
74945    if( res ){
74946      goto jump_to_p2;
74947    }
74948  }
74949  break;
74950}
74951
74952/* Opcode: Permutation * * * P4 *
74953**
74954** Set the permutation used by the OP_Compare operator to be the array
74955** of integers in P4.
74956**
74957** The permutation is only valid until the next OP_Compare that has
74958** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
74959** occur immediately prior to the OP_Compare.
74960*/
74961case OP_Permutation: {
74962  assert( pOp->p4type==P4_INTARRAY );
74963  assert( pOp->p4.ai );
74964  aPermute = pOp->p4.ai;
74965  break;
74966}
74967
74968/* Opcode: Compare P1 P2 P3 P4 P5
74969** Synopsis: r[P1@P3] <-> r[P2@P3]
74970**
74971** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
74972** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
74973** the comparison for use by the next OP_Jump instruct.
74974**
74975** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
74976** determined by the most recent OP_Permutation operator.  If the
74977** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
74978** order.
74979**
74980** P4 is a KeyInfo structure that defines collating sequences and sort
74981** orders for the comparison.  The permutation applies to registers
74982** only.  The KeyInfo elements are used sequentially.
74983**
74984** The comparison is a sort comparison, so NULLs compare equal,
74985** NULLs are less than numbers, numbers are less than strings,
74986** and strings are less than blobs.
74987*/
74988case OP_Compare: {
74989  int n;
74990  int i;
74991  int p1;
74992  int p2;
74993  const KeyInfo *pKeyInfo;
74994  int idx;
74995  CollSeq *pColl;    /* Collating sequence to use on this term */
74996  int bRev;          /* True for DESCENDING sort order */
74997
74998  if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
74999  n = pOp->p3;
75000  pKeyInfo = pOp->p4.pKeyInfo;
75001  assert( n>0 );
75002  assert( pKeyInfo!=0 );
75003  p1 = pOp->p1;
75004  p2 = pOp->p2;
75005#if SQLITE_DEBUG
75006  if( aPermute ){
75007    int k, mx = 0;
75008    for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
75009    assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 );
75010    assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 );
75011  }else{
75012    assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 );
75013    assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 );
75014  }
75015#endif /* SQLITE_DEBUG */
75016  for(i=0; i<n; i++){
75017    idx = aPermute ? aPermute[i] : i;
75018    assert( memIsValid(&aMem[p1+idx]) );
75019    assert( memIsValid(&aMem[p2+idx]) );
75020    REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
75021    REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
75022    assert( i<pKeyInfo->nField );
75023    pColl = pKeyInfo->aColl[i];
75024    bRev = pKeyInfo->aSortOrder[i];
75025    iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
75026    if( iCompare ){
75027      if( bRev ) iCompare = -iCompare;
75028      break;
75029    }
75030  }
75031  aPermute = 0;
75032  break;
75033}
75034
75035/* Opcode: Jump P1 P2 P3 * *
75036**
75037** Jump to the instruction at address P1, P2, or P3 depending on whether
75038** in the most recent OP_Compare instruction the P1 vector was less than
75039** equal to, or greater than the P2 vector, respectively.
75040*/
75041case OP_Jump: {             /* jump */
75042  if( iCompare<0 ){
75043    VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
75044  }else if( iCompare==0 ){
75045    VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
75046  }else{
75047    VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
75048  }
75049  break;
75050}
75051
75052/* Opcode: And P1 P2 P3 * *
75053** Synopsis: r[P3]=(r[P1] && r[P2])
75054**
75055** Take the logical AND of the values in registers P1 and P2 and
75056** write the result into register P3.
75057**
75058** If either P1 or P2 is 0 (false) then the result is 0 even if
75059** the other input is NULL.  A NULL and true or two NULLs give
75060** a NULL output.
75061*/
75062/* Opcode: Or P1 P2 P3 * *
75063** Synopsis: r[P3]=(r[P1] || r[P2])
75064**
75065** Take the logical OR of the values in register P1 and P2 and
75066** store the answer in register P3.
75067**
75068** If either P1 or P2 is nonzero (true) then the result is 1 (true)
75069** even if the other input is NULL.  A NULL and false or two NULLs
75070** give a NULL output.
75071*/
75072case OP_And:              /* same as TK_AND, in1, in2, out3 */
75073case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
75074  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
75075  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
75076
75077  pIn1 = &aMem[pOp->p1];
75078  if( pIn1->flags & MEM_Null ){
75079    v1 = 2;
75080  }else{
75081    v1 = sqlite3VdbeIntValue(pIn1)!=0;
75082  }
75083  pIn2 = &aMem[pOp->p2];
75084  if( pIn2->flags & MEM_Null ){
75085    v2 = 2;
75086  }else{
75087    v2 = sqlite3VdbeIntValue(pIn2)!=0;
75088  }
75089  if( pOp->opcode==OP_And ){
75090    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
75091    v1 = and_logic[v1*3+v2];
75092  }else{
75093    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
75094    v1 = or_logic[v1*3+v2];
75095  }
75096  pOut = &aMem[pOp->p3];
75097  if( v1==2 ){
75098    MemSetTypeFlag(pOut, MEM_Null);
75099  }else{
75100    pOut->u.i = v1;
75101    MemSetTypeFlag(pOut, MEM_Int);
75102  }
75103  break;
75104}
75105
75106/* Opcode: Not P1 P2 * * *
75107** Synopsis: r[P2]= !r[P1]
75108**
75109** Interpret the value in register P1 as a boolean value.  Store the
75110** boolean complement in register P2.  If the value in register P1 is
75111** NULL, then a NULL is stored in P2.
75112*/
75113case OP_Not: {                /* same as TK_NOT, 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: BitNot P1 P2 * * *
75125** Synopsis: r[P1]= ~r[P1]
75126**
75127** Interpret the content of register P1 as an integer.  Store the
75128** ones-complement of the P1 value into register P2.  If P1 holds
75129** a NULL then store a NULL in P2.
75130*/
75131case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
75132  pIn1 = &aMem[pOp->p1];
75133  pOut = &aMem[pOp->p2];
75134  sqlite3VdbeMemSetNull(pOut);
75135  if( (pIn1->flags & MEM_Null)==0 ){
75136    pOut->flags = MEM_Int;
75137    pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
75138  }
75139  break;
75140}
75141
75142/* Opcode: Once P1 P2 * * *
75143**
75144** Check the "once" flag number P1. If it is set, jump to instruction P2.
75145** Otherwise, set the flag and fall through to the next instruction.
75146** In other words, this opcode causes all following opcodes up through P2
75147** (but not including P2) to run just once and to be skipped on subsequent
75148** times through the loop.
75149**
75150** All "once" flags are initially cleared whenever a prepared statement
75151** first begins to run.
75152*/
75153case OP_Once: {             /* jump */
75154  assert( pOp->p1<p->nOnceFlag );
75155  VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
75156  if( p->aOnceFlag[pOp->p1] ){
75157    goto jump_to_p2;
75158  }else{
75159    p->aOnceFlag[pOp->p1] = 1;
75160  }
75161  break;
75162}
75163
75164/* Opcode: If P1 P2 P3 * *
75165**
75166** Jump to P2 if the value in register P1 is true.  The value
75167** is considered true if it is numeric and non-zero.  If the value
75168** in P1 is NULL then take the jump if and only if P3 is non-zero.
75169*/
75170/* Opcode: IfNot P1 P2 P3 * *
75171**
75172** Jump to P2 if the value in register P1 is False.  The value
75173** is considered false if it has a numeric value of zero.  If the value
75174** in P1 is NULL then take the jump if and only if P3 is non-zero.
75175*/
75176case OP_If:                 /* jump, in1 */
75177case OP_IfNot: {            /* jump, in1 */
75178  int c;
75179  pIn1 = &aMem[pOp->p1];
75180  if( pIn1->flags & MEM_Null ){
75181    c = pOp->p3;
75182  }else{
75183#ifdef SQLITE_OMIT_FLOATING_POINT
75184    c = sqlite3VdbeIntValue(pIn1)!=0;
75185#else
75186    c = sqlite3VdbeRealValue(pIn1)!=0.0;
75187#endif
75188    if( pOp->opcode==OP_IfNot ) c = !c;
75189  }
75190  VdbeBranchTaken(c!=0, 2);
75191  if( c ){
75192    goto jump_to_p2;
75193  }
75194  break;
75195}
75196
75197/* Opcode: IsNull P1 P2 * * *
75198** Synopsis:  if r[P1]==NULL goto P2
75199**
75200** Jump to P2 if the value in register P1 is NULL.
75201*/
75202case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
75203  pIn1 = &aMem[pOp->p1];
75204  VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
75205  if( (pIn1->flags & MEM_Null)!=0 ){
75206    goto jump_to_p2;
75207  }
75208  break;
75209}
75210
75211/* Opcode: NotNull P1 P2 * * *
75212** Synopsis: if r[P1]!=NULL goto P2
75213**
75214** Jump to P2 if the value in register P1 is not NULL.
75215*/
75216case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
75217  pIn1 = &aMem[pOp->p1];
75218  VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
75219  if( (pIn1->flags & MEM_Null)==0 ){
75220    goto jump_to_p2;
75221  }
75222  break;
75223}
75224
75225/* Opcode: Column P1 P2 P3 P4 P5
75226** Synopsis:  r[P3]=PX
75227**
75228** Interpret the data that cursor P1 points to as a structure built using
75229** the MakeRecord instruction.  (See the MakeRecord opcode for additional
75230** information about the format of the data.)  Extract the P2-th column
75231** from this record.  If there are less that (P2+1)
75232** values in the record, extract a NULL.
75233**
75234** The value extracted is stored in register P3.
75235**
75236** If the column contains fewer than P2 fields, then extract a NULL.  Or,
75237** if the P4 argument is a P4_MEM use the value of the P4 argument as
75238** the result.
75239**
75240** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
75241** then the cache of the cursor is reset prior to extracting the column.
75242** The first OP_Column against a pseudo-table after the value of the content
75243** register has changed should have this bit set.
75244**
75245** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
75246** the result is guaranteed to only be used as the argument of a length()
75247** or typeof() function, respectively.  The loading of large blobs can be
75248** skipped for length() and all content loading can be skipped for typeof().
75249*/
75250case OP_Column: {
75251  i64 payloadSize64; /* Number of bytes in the record */
75252  int p2;            /* column number to retrieve */
75253  VdbeCursor *pC;    /* The VDBE cursor */
75254  BtCursor *pCrsr;   /* The BTree cursor */
75255  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
75256  int len;           /* The length of the serialized data for the column */
75257  int i;             /* Loop counter */
75258  Mem *pDest;        /* Where to write the extracted value */
75259  Mem sMem;          /* For storing the record being decoded */
75260  const u8 *zData;   /* Part of the record being decoded */
75261  const u8 *zHdr;    /* Next unparsed byte of the header */
75262  const u8 *zEndHdr; /* Pointer to first byte after the header */
75263  u32 offset;        /* Offset into the data */
75264  u32 szField;       /* Number of bytes in the content of a field */
75265  u32 avail;         /* Number of bytes of available data */
75266  u32 t;             /* A type code from the record header */
75267  u16 fx;            /* pDest->flags value */
75268  Mem *pReg;         /* PseudoTable input register */
75269
75270  p2 = pOp->p2;
75271  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
75272  pDest = &aMem[pOp->p3];
75273  memAboutToChange(p, pDest);
75274  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75275  pC = p->apCsr[pOp->p1];
75276  assert( pC!=0 );
75277  assert( p2<pC->nField );
75278  aOffset = pC->aOffset;
75279#ifndef SQLITE_OMIT_VIRTUALTABLE
75280  assert( pC->pVtabCursor==0 ); /* OP_Column never called on virtual table */
75281#endif
75282  pCrsr = pC->pCursor;
75283  assert( pCrsr!=0 || pC->pseudoTableReg>0 ); /* pCrsr NULL on PseudoTables */
75284  assert( pCrsr!=0 || pC->nullRow );          /* pC->nullRow on PseudoTables */
75285
75286  /* If the cursor cache is stale, bring it up-to-date */
75287  rc = sqlite3VdbeCursorMoveto(pC);
75288  if( rc ) goto abort_due_to_error;
75289  if( pC->cacheStatus!=p->cacheCtr ){
75290    if( pC->nullRow ){
75291      if( pCrsr==0 ){
75292        assert( pC->pseudoTableReg>0 );
75293        pReg = &aMem[pC->pseudoTableReg];
75294        assert( pReg->flags & MEM_Blob );
75295        assert( memIsValid(pReg) );
75296        pC->payloadSize = pC->szRow = avail = pReg->n;
75297        pC->aRow = (u8*)pReg->z;
75298      }else{
75299        sqlite3VdbeMemSetNull(pDest);
75300        goto op_column_out;
75301      }
75302    }else{
75303      assert( pCrsr );
75304      if( pC->isTable==0 ){
75305        assert( sqlite3BtreeCursorIsValid(pCrsr) );
75306        VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
75307        assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
75308        /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
75309        ** payload size, so it is impossible for payloadSize64 to be
75310        ** larger than 32 bits. */
75311        assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
75312        pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
75313        pC->payloadSize = (u32)payloadSize64;
75314      }else{
75315        assert( sqlite3BtreeCursorIsValid(pCrsr) );
75316        VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
75317        assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
75318        pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
75319      }
75320      assert( avail<=65536 );  /* Maximum page size is 64KiB */
75321      if( pC->payloadSize <= (u32)avail ){
75322        pC->szRow = pC->payloadSize;
75323      }else{
75324        pC->szRow = avail;
75325      }
75326      if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
75327        goto too_big;
75328      }
75329    }
75330    pC->cacheStatus = p->cacheCtr;
75331    pC->iHdrOffset = getVarint32(pC->aRow, offset);
75332    pC->nHdrParsed = 0;
75333    aOffset[0] = offset;
75334
75335    /* Make sure a corrupt database has not given us an oversize header.
75336    ** Do this now to avoid an oversize memory allocation.
75337    **
75338    ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
75339    ** types use so much data space that there can only be 4096 and 32 of
75340    ** them, respectively.  So the maximum header length results from a
75341    ** 3-byte type for each of the maximum of 32768 columns plus three
75342    ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
75343    */
75344    if( offset > 98307 || offset > pC->payloadSize ){
75345      rc = SQLITE_CORRUPT_BKPT;
75346      goto op_column_error;
75347    }
75348
75349    if( avail<offset ){
75350      /* pC->aRow does not have to hold the entire row, but it does at least
75351      ** need to cover the header of the record.  If pC->aRow does not contain
75352      ** the complete header, then set it to zero, forcing the header to be
75353      ** dynamically allocated. */
75354      pC->aRow = 0;
75355      pC->szRow = 0;
75356    }
75357
75358    /* The following goto is an optimization.  It can be omitted and
75359    ** everything will still work.  But OP_Column is measurably faster
75360    ** by skipping the subsequent conditional, which is always true.
75361    */
75362    assert( pC->nHdrParsed<=p2 );         /* Conditional skipped */
75363    goto op_column_read_header;
75364  }
75365
75366  /* Make sure at least the first p2+1 entries of the header have been
75367  ** parsed and valid information is in aOffset[] and pC->aType[].
75368  */
75369  if( pC->nHdrParsed<=p2 ){
75370    /* If there is more header available for parsing in the record, try
75371    ** to extract additional fields up through the p2+1-th field
75372    */
75373    op_column_read_header:
75374    if( pC->iHdrOffset<aOffset[0] ){
75375      /* Make sure zData points to enough of the record to cover the header. */
75376      if( pC->aRow==0 ){
75377        memset(&sMem, 0, sizeof(sMem));
75378        rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0],
75379                                     !pC->isTable, &sMem);
75380        if( rc!=SQLITE_OK ){
75381          goto op_column_error;
75382        }
75383        zData = (u8*)sMem.z;
75384      }else{
75385        zData = pC->aRow;
75386      }
75387
75388      /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
75389      i = pC->nHdrParsed;
75390      offset = aOffset[i];
75391      zHdr = zData + pC->iHdrOffset;
75392      zEndHdr = zData + aOffset[0];
75393      assert( i<=p2 && zHdr<zEndHdr );
75394      do{
75395        if( zHdr[0]<0x80 ){
75396          t = zHdr[0];
75397          zHdr++;
75398        }else{
75399          zHdr += sqlite3GetVarint32(zHdr, &t);
75400        }
75401        pC->aType[i] = t;
75402        szField = sqlite3VdbeSerialTypeLen(t);
75403        offset += szField;
75404        if( offset<szField ){  /* True if offset overflows */
75405          zHdr = &zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
75406          break;
75407        }
75408        i++;
75409        aOffset[i] = offset;
75410      }while( i<=p2 && zHdr<zEndHdr );
75411      pC->nHdrParsed = i;
75412      pC->iHdrOffset = (u32)(zHdr - zData);
75413      if( pC->aRow==0 ){
75414        sqlite3VdbeMemRelease(&sMem);
75415        sMem.flags = MEM_Null;
75416      }
75417
75418      /* The record is corrupt if any of the following are true:
75419      ** (1) the bytes of the header extend past the declared header size
75420      **          (zHdr>zEndHdr)
75421      ** (2) the entire header was used but not all data was used
75422      **          (zHdr==zEndHdr && offset!=pC->payloadSize)
75423      ** (3) the end of the data extends beyond the end of the record.
75424      **          (offset > pC->payloadSize)
75425      */
75426      if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset!=pC->payloadSize))
75427       || (offset > pC->payloadSize)
75428      ){
75429        rc = SQLITE_CORRUPT_BKPT;
75430        goto op_column_error;
75431      }
75432    }
75433
75434    /* If after trying to extract new entries from the header, nHdrParsed is
75435    ** still not up to p2, that means that the record has fewer than p2
75436    ** columns.  So the result will be either the default value or a NULL.
75437    */
75438    if( pC->nHdrParsed<=p2 ){
75439      if( pOp->p4type==P4_MEM ){
75440        sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
75441      }else{
75442        sqlite3VdbeMemSetNull(pDest);
75443      }
75444      goto op_column_out;
75445    }
75446  }
75447
75448  /* Extract the content for the p2+1-th column.  Control can only
75449  ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
75450  ** all valid.
75451  */
75452  assert( p2<pC->nHdrParsed );
75453  assert( rc==SQLITE_OK );
75454  assert( sqlite3VdbeCheckMemInvariants(pDest) );
75455  if( VdbeMemDynamic(pDest) ) sqlite3VdbeMemSetNull(pDest);
75456  t = pC->aType[p2];
75457  if( pC->szRow>=aOffset[p2+1] ){
75458    /* This is the common case where the desired content fits on the original
75459    ** page - where the content is not on an overflow page */
75460    sqlite3VdbeSerialGet(pC->aRow+aOffset[p2], t, pDest);
75461  }else{
75462    /* This branch happens only when content is on overflow pages */
75463    if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
75464          && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
75465     || (len = sqlite3VdbeSerialTypeLen(t))==0
75466    ){
75467      /* Content is irrelevant for
75468      **    1. the typeof() function,
75469      **    2. the length(X) function if X is a blob, and
75470      **    3. if the content length is zero.
75471      ** So we might as well use bogus content rather than reading
75472      ** content from disk.  NULL will work for the value for strings
75473      ** and blobs and whatever is in the payloadSize64 variable
75474      ** will work for everything else. */
75475      sqlite3VdbeSerialGet(t<=13 ? (u8*)&payloadSize64 : 0, t, pDest);
75476    }else{
75477      rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
75478                                   pDest);
75479      if( rc!=SQLITE_OK ){
75480        goto op_column_error;
75481      }
75482      sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
75483      pDest->flags &= ~MEM_Ephem;
75484    }
75485  }
75486  pDest->enc = encoding;
75487
75488op_column_out:
75489  /* If the column value is an ephemeral string, go ahead and persist
75490  ** that string in case the cursor moves before the column value is
75491  ** used.  The following code does the equivalent of Deephemeralize()
75492  ** but does it faster. */
75493  if( (pDest->flags & MEM_Ephem)!=0 && pDest->z ){
75494    fx = pDest->flags & (MEM_Str|MEM_Blob);
75495    assert( fx!=0 );
75496    zData = (const u8*)pDest->z;
75497    len = pDest->n;
75498    if( sqlite3VdbeMemClearAndResize(pDest, len+2) ) goto no_mem;
75499    memcpy(pDest->z, zData, len);
75500    pDest->z[len] = 0;
75501    pDest->z[len+1] = 0;
75502    pDest->flags = fx|MEM_Term;
75503  }
75504op_column_error:
75505  UPDATE_MAX_BLOBSIZE(pDest);
75506  REGISTER_TRACE(pOp->p3, pDest);
75507  break;
75508}
75509
75510/* Opcode: Affinity P1 P2 * P4 *
75511** Synopsis: affinity(r[P1@P2])
75512**
75513** Apply affinities to a range of P2 registers starting with P1.
75514**
75515** P4 is a string that is P2 characters long. The nth character of the
75516** string indicates the column affinity that should be used for the nth
75517** memory cell in the range.
75518*/
75519case OP_Affinity: {
75520  const char *zAffinity;   /* The affinity to be applied */
75521  char cAff;               /* A single character of affinity */
75522
75523  zAffinity = pOp->p4.z;
75524  assert( zAffinity!=0 );
75525  assert( zAffinity[pOp->p2]==0 );
75526  pIn1 = &aMem[pOp->p1];
75527  while( (cAff = *(zAffinity++))!=0 ){
75528    assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
75529    assert( memIsValid(pIn1) );
75530    applyAffinity(pIn1, cAff, encoding);
75531    pIn1++;
75532  }
75533  break;
75534}
75535
75536/* Opcode: MakeRecord P1 P2 P3 P4 *
75537** Synopsis: r[P3]=mkrec(r[P1@P2])
75538**
75539** Convert P2 registers beginning with P1 into the [record format]
75540** use as a data record in a database table or as a key
75541** in an index.  The OP_Column opcode can decode the record later.
75542**
75543** P4 may be a string that is P2 characters long.  The nth character of the
75544** string indicates the column affinity that should be used for the nth
75545** field of the index key.
75546**
75547** The mapping from character to affinity is given by the SQLITE_AFF_
75548** macros defined in sqliteInt.h.
75549**
75550** If P4 is NULL then all index fields have the affinity BLOB.
75551*/
75552case OP_MakeRecord: {
75553  u8 *zNewRecord;        /* A buffer to hold the data for the new record */
75554  Mem *pRec;             /* The new record */
75555  u64 nData;             /* Number of bytes of data space */
75556  int nHdr;              /* Number of bytes of header space */
75557  i64 nByte;             /* Data space required for this record */
75558  i64 nZero;             /* Number of zero bytes at the end of the record */
75559  int nVarint;           /* Number of bytes in a varint */
75560  u32 serial_type;       /* Type field */
75561  Mem *pData0;           /* First field to be combined into the record */
75562  Mem *pLast;            /* Last field of the record */
75563  int nField;            /* Number of fields in the record */
75564  char *zAffinity;       /* The affinity string for the record */
75565  int file_format;       /* File format to use for encoding */
75566  int i;                 /* Space used in zNewRecord[] header */
75567  int j;                 /* Space used in zNewRecord[] content */
75568  int len;               /* Length of a field */
75569
75570  /* Assuming the record contains N fields, the record format looks
75571  ** like this:
75572  **
75573  ** ------------------------------------------------------------------------
75574  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
75575  ** ------------------------------------------------------------------------
75576  **
75577  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
75578  ** and so forth.
75579  **
75580  ** Each type field is a varint representing the serial type of the
75581  ** corresponding data element (see sqlite3VdbeSerialType()). The
75582  ** hdr-size field is also a varint which is the offset from the beginning
75583  ** of the record to data0.
75584  */
75585  nData = 0;         /* Number of bytes of data space */
75586  nHdr = 0;          /* Number of bytes of header space */
75587  nZero = 0;         /* Number of zero bytes at the end of the record */
75588  nField = pOp->p1;
75589  zAffinity = pOp->p4.z;
75590  assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 );
75591  pData0 = &aMem[nField];
75592  nField = pOp->p2;
75593  pLast = &pData0[nField-1];
75594  file_format = p->minWriteFileFormat;
75595
75596  /* Identify the output register */
75597  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
75598  pOut = &aMem[pOp->p3];
75599  memAboutToChange(p, pOut);
75600
75601  /* Apply the requested affinity to all inputs
75602  */
75603  assert( pData0<=pLast );
75604  if( zAffinity ){
75605    pRec = pData0;
75606    do{
75607      applyAffinity(pRec++, *(zAffinity++), encoding);
75608      assert( zAffinity[0]==0 || pRec<=pLast );
75609    }while( zAffinity[0] );
75610  }
75611
75612  /* Loop through the elements that will make up the record to figure
75613  ** out how much space is required for the new record.
75614  */
75615  pRec = pLast;
75616  do{
75617    assert( memIsValid(pRec) );
75618    pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format);
75619    len = sqlite3VdbeSerialTypeLen(serial_type);
75620    if( pRec->flags & MEM_Zero ){
75621      if( nData ){
75622        if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
75623      }else{
75624        nZero += pRec->u.nZero;
75625        len -= pRec->u.nZero;
75626      }
75627    }
75628    nData += len;
75629    testcase( serial_type==127 );
75630    testcase( serial_type==128 );
75631    nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
75632  }while( (--pRec)>=pData0 );
75633
75634  /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
75635  ** which determines the total number of bytes in the header. The varint
75636  ** value is the size of the header in bytes including the size varint
75637  ** itself. */
75638  testcase( nHdr==126 );
75639  testcase( nHdr==127 );
75640  if( nHdr<=126 ){
75641    /* The common case */
75642    nHdr += 1;
75643  }else{
75644    /* Rare case of a really large header */
75645    nVarint = sqlite3VarintLen(nHdr);
75646    nHdr += nVarint;
75647    if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
75648  }
75649  nByte = nHdr+nData;
75650  if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
75651    goto too_big;
75652  }
75653
75654  /* Make sure the output register has a buffer large enough to store
75655  ** the new record. The output register (pOp->p3) is not allowed to
75656  ** be one of the input registers (because the following call to
75657  ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
75658  */
75659  if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
75660    goto no_mem;
75661  }
75662  zNewRecord = (u8 *)pOut->z;
75663
75664  /* Write the record */
75665  i = putVarint32(zNewRecord, nHdr);
75666  j = nHdr;
75667  assert( pData0<=pLast );
75668  pRec = pData0;
75669  do{
75670    serial_type = pRec->uTemp;
75671    /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
75672    ** additional varints, one per column. */
75673    i += putVarint32(&zNewRecord[i], serial_type);            /* serial type */
75674    /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
75675    ** immediately follow the header. */
75676    j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
75677  }while( (++pRec)<=pLast );
75678  assert( i==nHdr );
75679  assert( j==nByte );
75680
75681  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
75682  pOut->n = (int)nByte;
75683  pOut->flags = MEM_Blob;
75684  if( nZero ){
75685    pOut->u.nZero = nZero;
75686    pOut->flags |= MEM_Zero;
75687  }
75688  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
75689  REGISTER_TRACE(pOp->p3, pOut);
75690  UPDATE_MAX_BLOBSIZE(pOut);
75691  break;
75692}
75693
75694/* Opcode: Count P1 P2 * * *
75695** Synopsis: r[P2]=count()
75696**
75697** Store the number of entries (an integer value) in the table or index
75698** opened by cursor P1 in register P2
75699*/
75700#ifndef SQLITE_OMIT_BTREECOUNT
75701case OP_Count: {         /* out2 */
75702  i64 nEntry;
75703  BtCursor *pCrsr;
75704
75705  pCrsr = p->apCsr[pOp->p1]->pCursor;
75706  assert( pCrsr );
75707  nEntry = 0;  /* Not needed.  Only used to silence a warning. */
75708  rc = sqlite3BtreeCount(pCrsr, &nEntry);
75709  pOut = out2Prerelease(p, pOp);
75710  pOut->u.i = nEntry;
75711  break;
75712}
75713#endif
75714
75715/* Opcode: Savepoint P1 * * P4 *
75716**
75717** Open, release or rollback the savepoint named by parameter P4, depending
75718** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
75719** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
75720*/
75721case OP_Savepoint: {
75722  int p1;                         /* Value of P1 operand */
75723  char *zName;                    /* Name of savepoint */
75724  int nName;
75725  Savepoint *pNew;
75726  Savepoint *pSavepoint;
75727  Savepoint *pTmp;
75728  int iSavepoint;
75729  int ii;
75730
75731  p1 = pOp->p1;
75732  zName = pOp->p4.z;
75733
75734  /* Assert that the p1 parameter is valid. Also that if there is no open
75735  ** transaction, then there cannot be any savepoints.
75736  */
75737  assert( db->pSavepoint==0 || db->autoCommit==0 );
75738  assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
75739  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
75740  assert( checkSavepointCount(db) );
75741  assert( p->bIsReader );
75742
75743  if( p1==SAVEPOINT_BEGIN ){
75744    if( db->nVdbeWrite>0 ){
75745      /* A new savepoint cannot be created if there are active write
75746      ** statements (i.e. open read/write incremental blob handles).
75747      */
75748      sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
75749      rc = SQLITE_BUSY;
75750    }else{
75751      nName = sqlite3Strlen30(zName);
75752
75753#ifndef SQLITE_OMIT_VIRTUALTABLE
75754      /* This call is Ok even if this savepoint is actually a transaction
75755      ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
75756      ** If this is a transaction savepoint being opened, it is guaranteed
75757      ** that the db->aVTrans[] array is empty.  */
75758      assert( db->autoCommit==0 || db->nVTrans==0 );
75759      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
75760                                db->nStatement+db->nSavepoint);
75761      if( rc!=SQLITE_OK ) goto abort_due_to_error;
75762#endif
75763
75764      /* Create a new savepoint structure. */
75765      pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
75766      if( pNew ){
75767        pNew->zName = (char *)&pNew[1];
75768        memcpy(pNew->zName, zName, nName+1);
75769
75770        /* If there is no open transaction, then mark this as a special
75771        ** "transaction savepoint". */
75772        if( db->autoCommit ){
75773          db->autoCommit = 0;
75774          db->isTransactionSavepoint = 1;
75775        }else{
75776          db->nSavepoint++;
75777        }
75778
75779        /* Link the new savepoint into the database handle's list. */
75780        pNew->pNext = db->pSavepoint;
75781        db->pSavepoint = pNew;
75782        pNew->nDeferredCons = db->nDeferredCons;
75783        pNew->nDeferredImmCons = db->nDeferredImmCons;
75784      }
75785    }
75786  }else{
75787    iSavepoint = 0;
75788
75789    /* Find the named savepoint. If there is no such savepoint, then an
75790    ** an error is returned to the user.  */
75791    for(
75792      pSavepoint = db->pSavepoint;
75793      pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
75794      pSavepoint = pSavepoint->pNext
75795    ){
75796      iSavepoint++;
75797    }
75798    if( !pSavepoint ){
75799      sqlite3VdbeError(p, "no such savepoint: %s", zName);
75800      rc = SQLITE_ERROR;
75801    }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
75802      /* It is not possible to release (commit) a savepoint if there are
75803      ** active write statements.
75804      */
75805      sqlite3VdbeError(p, "cannot release savepoint - "
75806                          "SQL statements in progress");
75807      rc = SQLITE_BUSY;
75808    }else{
75809
75810      /* Determine whether or not this is a transaction savepoint. If so,
75811      ** and this is a RELEASE command, then the current transaction
75812      ** is committed.
75813      */
75814      int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
75815      if( isTransaction && p1==SAVEPOINT_RELEASE ){
75816        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
75817          goto vdbe_return;
75818        }
75819        db->autoCommit = 1;
75820        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
75821          p->pc = (int)(pOp - aOp);
75822          db->autoCommit = 0;
75823          p->rc = rc = SQLITE_BUSY;
75824          goto vdbe_return;
75825        }
75826        db->isTransactionSavepoint = 0;
75827        rc = p->rc;
75828      }else{
75829        int isSchemaChange;
75830        iSavepoint = db->nSavepoint - iSavepoint - 1;
75831        if( p1==SAVEPOINT_ROLLBACK ){
75832          isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
75833          for(ii=0; ii<db->nDb; ii++){
75834            rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
75835                                       SQLITE_ABORT_ROLLBACK,
75836                                       isSchemaChange==0);
75837            if( rc!=SQLITE_OK ) goto abort_due_to_error;
75838          }
75839        }else{
75840          isSchemaChange = 0;
75841        }
75842        for(ii=0; ii<db->nDb; ii++){
75843          rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
75844          if( rc!=SQLITE_OK ){
75845            goto abort_due_to_error;
75846          }
75847        }
75848        if( isSchemaChange ){
75849          sqlite3ExpirePreparedStatements(db);
75850          sqlite3ResetAllSchemasOfConnection(db);
75851          db->flags = (db->flags | SQLITE_InternChanges);
75852        }
75853      }
75854
75855      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
75856      ** savepoints nested inside of the savepoint being operated on. */
75857      while( db->pSavepoint!=pSavepoint ){
75858        pTmp = db->pSavepoint;
75859        db->pSavepoint = pTmp->pNext;
75860        sqlite3DbFree(db, pTmp);
75861        db->nSavepoint--;
75862      }
75863
75864      /* If it is a RELEASE, then destroy the savepoint being operated on
75865      ** too. If it is a ROLLBACK TO, then set the number of deferred
75866      ** constraint violations present in the database to the value stored
75867      ** when the savepoint was created.  */
75868      if( p1==SAVEPOINT_RELEASE ){
75869        assert( pSavepoint==db->pSavepoint );
75870        db->pSavepoint = pSavepoint->pNext;
75871        sqlite3DbFree(db, pSavepoint);
75872        if( !isTransaction ){
75873          db->nSavepoint--;
75874        }
75875      }else{
75876        db->nDeferredCons = pSavepoint->nDeferredCons;
75877        db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
75878      }
75879
75880      if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
75881        rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
75882        if( rc!=SQLITE_OK ) goto abort_due_to_error;
75883      }
75884    }
75885  }
75886
75887  break;
75888}
75889
75890/* Opcode: AutoCommit P1 P2 * * *
75891**
75892** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
75893** back any currently active btree transactions. If there are any active
75894** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
75895** there are active writing VMs or active VMs that use shared cache.
75896**
75897** This instruction causes the VM to halt.
75898*/
75899case OP_AutoCommit: {
75900  int desiredAutoCommit;
75901  int iRollback;
75902  int turnOnAC;
75903
75904  desiredAutoCommit = pOp->p1;
75905  iRollback = pOp->p2;
75906  turnOnAC = desiredAutoCommit && !db->autoCommit;
75907  assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
75908  assert( desiredAutoCommit==1 || iRollback==0 );
75909  assert( db->nVdbeActive>0 );  /* At least this one VM is active */
75910  assert( p->bIsReader );
75911
75912  if( turnOnAC && !iRollback && db->nVdbeWrite>0 ){
75913    /* If this instruction implements a COMMIT and other VMs are writing
75914    ** return an error indicating that the other VMs must complete first.
75915    */
75916    sqlite3VdbeError(p, "cannot commit transaction - "
75917                        "SQL statements in progress");
75918    rc = SQLITE_BUSY;
75919  }else if( desiredAutoCommit!=db->autoCommit ){
75920    if( iRollback ){
75921      assert( desiredAutoCommit==1 );
75922      sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
75923      db->autoCommit = 1;
75924    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
75925      goto vdbe_return;
75926    }else{
75927      db->autoCommit = (u8)desiredAutoCommit;
75928    }
75929    if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
75930      p->pc = (int)(pOp - aOp);
75931      db->autoCommit = (u8)(1-desiredAutoCommit);
75932      p->rc = rc = SQLITE_BUSY;
75933      goto vdbe_return;
75934    }
75935    assert( db->nStatement==0 );
75936    sqlite3CloseSavepoints(db);
75937    if( p->rc==SQLITE_OK ){
75938      rc = SQLITE_DONE;
75939    }else{
75940      rc = SQLITE_ERROR;
75941    }
75942    goto vdbe_return;
75943  }else{
75944    sqlite3VdbeError(p,
75945        (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
75946        (iRollback)?"cannot rollback - no transaction is active":
75947                   "cannot commit - no transaction is active"));
75948
75949    rc = SQLITE_ERROR;
75950  }
75951  break;
75952}
75953
75954/* Opcode: Transaction P1 P2 P3 P4 P5
75955**
75956** Begin a transaction on database P1 if a transaction is not already
75957** active.
75958** If P2 is non-zero, then a write-transaction is started, or if a
75959** read-transaction is already active, it is upgraded to a write-transaction.
75960** If P2 is zero, then a read-transaction is started.
75961**
75962** P1 is the index of the database file on which the transaction is
75963** started.  Index 0 is the main database file and index 1 is the
75964** file used for temporary tables.  Indices of 2 or more are used for
75965** attached databases.
75966**
75967** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
75968** true (this flag is set if the Vdbe may modify more than one row and may
75969** throw an ABORT exception), a statement transaction may also be opened.
75970** More specifically, a statement transaction is opened iff the database
75971** connection is currently not in autocommit mode, or if there are other
75972** active statements. A statement transaction allows the changes made by this
75973** VDBE to be rolled back after an error without having to roll back the
75974** entire transaction. If no error is encountered, the statement transaction
75975** will automatically commit when the VDBE halts.
75976**
75977** If P5!=0 then this opcode also checks the schema cookie against P3
75978** and the schema generation counter against P4.
75979** The cookie changes its value whenever the database schema changes.
75980** This operation is used to detect when that the cookie has changed
75981** and that the current process needs to reread the schema.  If the schema
75982** cookie in P3 differs from the schema cookie in the database header or
75983** if the schema generation counter in P4 differs from the current
75984** generation counter, then an SQLITE_SCHEMA error is raised and execution
75985** halts.  The sqlite3_step() wrapper function might then reprepare the
75986** statement and rerun it from the beginning.
75987*/
75988case OP_Transaction: {
75989  Btree *pBt;
75990  int iMeta;
75991  int iGen;
75992
75993  assert( p->bIsReader );
75994  assert( p->readOnly==0 || pOp->p2==0 );
75995  assert( pOp->p1>=0 && pOp->p1<db->nDb );
75996  assert( DbMaskTest(p->btreeMask, pOp->p1) );
75997  if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
75998    rc = SQLITE_READONLY;
75999    goto abort_due_to_error;
76000  }
76001  pBt = db->aDb[pOp->p1].pBt;
76002
76003  if( pBt ){
76004    rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
76005    testcase( rc==SQLITE_BUSY_SNAPSHOT );
76006    testcase( rc==SQLITE_BUSY_RECOVERY );
76007    if( (rc&0xff)==SQLITE_BUSY ){
76008      p->pc = (int)(pOp - aOp);
76009      p->rc = rc;
76010      goto vdbe_return;
76011    }
76012    if( rc!=SQLITE_OK ){
76013      goto abort_due_to_error;
76014    }
76015
76016    if( pOp->p2 && p->usesStmtJournal
76017     && (db->autoCommit==0 || db->nVdbeRead>1)
76018    ){
76019      assert( sqlite3BtreeIsInTrans(pBt) );
76020      if( p->iStatement==0 ){
76021        assert( db->nStatement>=0 && db->nSavepoint>=0 );
76022        db->nStatement++;
76023        p->iStatement = db->nSavepoint + db->nStatement;
76024      }
76025
76026      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
76027      if( rc==SQLITE_OK ){
76028        rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
76029      }
76030
76031      /* Store the current value of the database handles deferred constraint
76032      ** counter. If the statement transaction needs to be rolled back,
76033      ** the value of this counter needs to be restored too.  */
76034      p->nStmtDefCons = db->nDeferredCons;
76035      p->nStmtDefImmCons = db->nDeferredImmCons;
76036    }
76037
76038    /* Gather the schema version number for checking:
76039    ** IMPLEMENTATION-OF: R-32195-19465 The schema version is used by SQLite
76040    ** each time a query is executed to ensure that the internal cache of the
76041    ** schema used when compiling the SQL query matches the schema of the
76042    ** database against which the compiled query is actually executed.
76043    */
76044    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
76045    iGen = db->aDb[pOp->p1].pSchema->iGeneration;
76046  }else{
76047    iGen = iMeta = 0;
76048  }
76049  assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
76050  if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
76051    sqlite3DbFree(db, p->zErrMsg);
76052    p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
76053    /* If the schema-cookie from the database file matches the cookie
76054    ** stored with the in-memory representation of the schema, do
76055    ** not reload the schema from the database file.
76056    **
76057    ** If virtual-tables are in use, this is not just an optimization.
76058    ** Often, v-tables store their data in other SQLite tables, which
76059    ** are queried from within xNext() and other v-table methods using
76060    ** prepared queries. If such a query is out-of-date, we do not want to
76061    ** discard the database schema, as the user code implementing the
76062    ** v-table would have to be ready for the sqlite3_vtab structure itself
76063    ** to be invalidated whenever sqlite3_step() is called from within
76064    ** a v-table method.
76065    */
76066    if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
76067      sqlite3ResetOneSchema(db, pOp->p1);
76068    }
76069    p->expired = 1;
76070    rc = SQLITE_SCHEMA;
76071  }
76072  break;
76073}
76074
76075/* Opcode: ReadCookie P1 P2 P3 * *
76076**
76077** Read cookie number P3 from database P1 and write it into register P2.
76078** P3==1 is the schema version.  P3==2 is the database format.
76079** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
76080** the main database file and P1==1 is the database file used to store
76081** temporary tables.
76082**
76083** There must be a read-lock on the database (either a transaction
76084** must be started or there must be an open cursor) before
76085** executing this instruction.
76086*/
76087case OP_ReadCookie: {               /* out2 */
76088  int iMeta;
76089  int iDb;
76090  int iCookie;
76091
76092  assert( p->bIsReader );
76093  iDb = pOp->p1;
76094  iCookie = pOp->p3;
76095  assert( pOp->p3<SQLITE_N_BTREE_META );
76096  assert( iDb>=0 && iDb<db->nDb );
76097  assert( db->aDb[iDb].pBt!=0 );
76098  assert( DbMaskTest(p->btreeMask, iDb) );
76099
76100  sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
76101  pOut = out2Prerelease(p, pOp);
76102  pOut->u.i = iMeta;
76103  break;
76104}
76105
76106/* Opcode: SetCookie P1 P2 P3 * *
76107**
76108** Write the content of register P3 (interpreted as an integer)
76109** into cookie number P2 of database P1.  P2==1 is the schema version.
76110** P2==2 is the database format. P2==3 is the recommended pager cache
76111** size, and so forth.  P1==0 is the main database file and P1==1 is the
76112** database file used to store temporary tables.
76113**
76114** A transaction must be started before executing this opcode.
76115*/
76116case OP_SetCookie: {       /* in3 */
76117  Db *pDb;
76118  assert( pOp->p2<SQLITE_N_BTREE_META );
76119  assert( pOp->p1>=0 && pOp->p1<db->nDb );
76120  assert( DbMaskTest(p->btreeMask, pOp->p1) );
76121  assert( p->readOnly==0 );
76122  pDb = &db->aDb[pOp->p1];
76123  assert( pDb->pBt!=0 );
76124  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
76125  pIn3 = &aMem[pOp->p3];
76126  sqlite3VdbeMemIntegerify(pIn3);
76127  /* See note about index shifting on OP_ReadCookie */
76128  rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i);
76129  if( pOp->p2==BTREE_SCHEMA_VERSION ){
76130    /* When the schema cookie changes, record the new cookie internally */
76131    pDb->pSchema->schema_cookie = (int)pIn3->u.i;
76132    db->flags |= SQLITE_InternChanges;
76133  }else if( pOp->p2==BTREE_FILE_FORMAT ){
76134    /* Record changes in the file format */
76135    pDb->pSchema->file_format = (u8)pIn3->u.i;
76136  }
76137  if( pOp->p1==1 ){
76138    /* Invalidate all prepared statements whenever the TEMP database
76139    ** schema is changed.  Ticket #1644 */
76140    sqlite3ExpirePreparedStatements(db);
76141    p->expired = 0;
76142  }
76143  break;
76144}
76145
76146/* Opcode: OpenRead P1 P2 P3 P4 P5
76147** Synopsis: root=P2 iDb=P3
76148**
76149** Open a read-only cursor for the database table whose root page is
76150** P2 in a database file.  The database file is determined by P3.
76151** P3==0 means the main database, P3==1 means the database used for
76152** temporary tables, and P3>1 means used the corresponding attached
76153** database.  Give the new cursor an identifier of P1.  The P1
76154** values need not be contiguous but all P1 values should be small integers.
76155** It is an error for P1 to be negative.
76156**
76157** If P5!=0 then use the content of register P2 as the root page, not
76158** the value of P2 itself.
76159**
76160** There will be a read lock on the database whenever there is an
76161** open cursor.  If the database was unlocked prior to this instruction
76162** then a read lock is acquired as part of this instruction.  A read
76163** lock allows other processes to read the database but prohibits
76164** any other process from modifying the database.  The read lock is
76165** released when all cursors are closed.  If this instruction attempts
76166** to get a read lock but fails, the script terminates with an
76167** SQLITE_BUSY error code.
76168**
76169** The P4 value may be either an integer (P4_INT32) or a pointer to
76170** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
76171** structure, then said structure defines the content and collating
76172** sequence of the index being opened. Otherwise, if P4 is an integer
76173** value, it is set to the number of columns in the table.
76174**
76175** See also: OpenWrite, ReopenIdx
76176*/
76177/* Opcode: ReopenIdx P1 P2 P3 P4 P5
76178** Synopsis: root=P2 iDb=P3
76179**
76180** The ReopenIdx opcode works exactly like ReadOpen except that it first
76181** checks to see if the cursor on P1 is already open with a root page
76182** number of P2 and if it is this opcode becomes a no-op.  In other words,
76183** if the cursor is already open, do not reopen it.
76184**
76185** The ReopenIdx opcode may only be used with P5==0 and with P4 being
76186** a P4_KEYINFO object.  Furthermore, the P3 value must be the same as
76187** every other ReopenIdx or OpenRead for the same cursor number.
76188**
76189** See the OpenRead opcode documentation for additional information.
76190*/
76191/* Opcode: OpenWrite P1 P2 P3 P4 P5
76192** Synopsis: root=P2 iDb=P3
76193**
76194** Open a read/write cursor named P1 on the table or index whose root
76195** page is P2.  Or if P5!=0 use the content of register P2 to find the
76196** root page.
76197**
76198** The P4 value may be either an integer (P4_INT32) or a pointer to
76199** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
76200** structure, then said structure defines the content and collating
76201** sequence of the index being opened. Otherwise, if P4 is an integer
76202** value, it is set to the number of columns in the table, or to the
76203** largest index of any column of the table that is actually used.
76204**
76205** This instruction works just like OpenRead except that it opens the cursor
76206** in read/write mode.  For a given table, there can be one or more read-only
76207** cursors or a single read/write cursor but not both.
76208**
76209** See also OpenRead.
76210*/
76211case OP_ReopenIdx: {
76212  int nField;
76213  KeyInfo *pKeyInfo;
76214  int p2;
76215  int iDb;
76216  int wrFlag;
76217  Btree *pX;
76218  VdbeCursor *pCur;
76219  Db *pDb;
76220
76221  assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
76222  assert( pOp->p4type==P4_KEYINFO );
76223  pCur = p->apCsr[pOp->p1];
76224  if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
76225    assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
76226    goto open_cursor_set_hints;
76227  }
76228  /* If the cursor is not currently open or is open on a different
76229  ** index, then fall through into OP_OpenRead to force a reopen */
76230case OP_OpenRead:
76231case OP_OpenWrite:
76232
76233  assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR|OPFLAG_SEEKEQ))==pOp->p5 );
76234  assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
76235  assert( p->bIsReader );
76236  assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
76237          || p->readOnly==0 );
76238
76239  if( p->expired ){
76240    rc = SQLITE_ABORT_ROLLBACK;
76241    break;
76242  }
76243
76244  nField = 0;
76245  pKeyInfo = 0;
76246  p2 = pOp->p2;
76247  iDb = pOp->p3;
76248  assert( iDb>=0 && iDb<db->nDb );
76249  assert( DbMaskTest(p->btreeMask, iDb) );
76250  pDb = &db->aDb[iDb];
76251  pX = pDb->pBt;
76252  assert( pX!=0 );
76253  if( pOp->opcode==OP_OpenWrite ){
76254    wrFlag = 1;
76255    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
76256    if( pDb->pSchema->file_format < p->minWriteFileFormat ){
76257      p->minWriteFileFormat = pDb->pSchema->file_format;
76258    }
76259  }else{
76260    wrFlag = 0;
76261  }
76262  if( pOp->p5 & OPFLAG_P2ISREG ){
76263    assert( p2>0 );
76264    assert( p2<=(p->nMem-p->nCursor) );
76265    pIn2 = &aMem[p2];
76266    assert( memIsValid(pIn2) );
76267    assert( (pIn2->flags & MEM_Int)!=0 );
76268    sqlite3VdbeMemIntegerify(pIn2);
76269    p2 = (int)pIn2->u.i;
76270    /* The p2 value always comes from a prior OP_CreateTable opcode and
76271    ** that opcode will always set the p2 value to 2 or more or else fail.
76272    ** If there were a failure, the prepared statement would have halted
76273    ** before reaching this instruction. */
76274    if( NEVER(p2<2) ) {
76275      rc = SQLITE_CORRUPT_BKPT;
76276      goto abort_due_to_error;
76277    }
76278  }
76279  if( pOp->p4type==P4_KEYINFO ){
76280    pKeyInfo = pOp->p4.pKeyInfo;
76281    assert( pKeyInfo->enc==ENC(db) );
76282    assert( pKeyInfo->db==db );
76283    nField = pKeyInfo->nField+pKeyInfo->nXField;
76284  }else if( pOp->p4type==P4_INT32 ){
76285    nField = pOp->p4.i;
76286  }
76287  assert( pOp->p1>=0 );
76288  assert( nField>=0 );
76289  testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
76290  pCur = allocateCursor(p, pOp->p1, nField, iDb, 1);
76291  if( pCur==0 ) goto no_mem;
76292  pCur->nullRow = 1;
76293  pCur->isOrdered = 1;
76294  pCur->pgnoRoot = p2;
76295  rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
76296  pCur->pKeyInfo = pKeyInfo;
76297  /* Set the VdbeCursor.isTable variable. Previous versions of
76298  ** SQLite used to check if the root-page flags were sane at this point
76299  ** and report database corruption if they were not, but this check has
76300  ** since moved into the btree layer.  */
76301  pCur->isTable = pOp->p4type!=P4_KEYINFO;
76302
76303open_cursor_set_hints:
76304  assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
76305  assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
76306  sqlite3BtreeCursorHints(pCur->pCursor,
76307                          (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
76308  break;
76309}
76310
76311/* Opcode: OpenEphemeral P1 P2 * P4 P5
76312** Synopsis: nColumn=P2
76313**
76314** Open a new cursor P1 to a transient table.
76315** The cursor is always opened read/write even if
76316** the main database is read-only.  The ephemeral
76317** table is deleted automatically when the cursor is closed.
76318**
76319** P2 is the number of columns in the ephemeral table.
76320** The cursor points to a BTree table if P4==0 and to a BTree index
76321** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
76322** that defines the format of keys in the index.
76323**
76324** The P5 parameter can be a mask of the BTREE_* flags defined
76325** in btree.h.  These flags control aspects of the operation of
76326** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
76327** added automatically.
76328*/
76329/* Opcode: OpenAutoindex P1 P2 * P4 *
76330** Synopsis: nColumn=P2
76331**
76332** This opcode works the same as OP_OpenEphemeral.  It has a
76333** different name to distinguish its use.  Tables created using
76334** by this opcode will be used for automatically created transient
76335** indices in joins.
76336*/
76337case OP_OpenAutoindex:
76338case OP_OpenEphemeral: {
76339  VdbeCursor *pCx;
76340  KeyInfo *pKeyInfo;
76341
76342  static const int vfsFlags =
76343      SQLITE_OPEN_READWRITE |
76344      SQLITE_OPEN_CREATE |
76345      SQLITE_OPEN_EXCLUSIVE |
76346      SQLITE_OPEN_DELETEONCLOSE |
76347      SQLITE_OPEN_TRANSIENT_DB;
76348  assert( pOp->p1>=0 );
76349  assert( pOp->p2>=0 );
76350  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
76351  if( pCx==0 ) goto no_mem;
76352  pCx->nullRow = 1;
76353  pCx->isEphemeral = 1;
76354  rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
76355                        BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
76356  if( rc==SQLITE_OK ){
76357    rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
76358  }
76359  if( rc==SQLITE_OK ){
76360    /* If a transient index is required, create it by calling
76361    ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
76362    ** opening it. If a transient table is required, just use the
76363    ** automatically created table with root-page 1 (an BLOB_INTKEY table).
76364    */
76365    if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
76366      int pgno;
76367      assert( pOp->p4type==P4_KEYINFO );
76368      rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
76369      if( rc==SQLITE_OK ){
76370        assert( pgno==MASTER_ROOT+1 );
76371        assert( pKeyInfo->db==db );
76372        assert( pKeyInfo->enc==ENC(db) );
76373        pCx->pKeyInfo = pKeyInfo;
76374        rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, pKeyInfo, pCx->pCursor);
76375      }
76376      pCx->isTable = 0;
76377    }else{
76378      rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
76379      pCx->isTable = 1;
76380    }
76381  }
76382  pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
76383  break;
76384}
76385
76386/* Opcode: SorterOpen P1 P2 P3 P4 *
76387**
76388** This opcode works like OP_OpenEphemeral except that it opens
76389** a transient index that is specifically designed to sort large
76390** tables using an external merge-sort algorithm.
76391**
76392** If argument P3 is non-zero, then it indicates that the sorter may
76393** assume that a stable sort considering the first P3 fields of each
76394** key is sufficient to produce the required results.
76395*/
76396case OP_SorterOpen: {
76397  VdbeCursor *pCx;
76398
76399  assert( pOp->p1>=0 );
76400  assert( pOp->p2>=0 );
76401  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
76402  if( pCx==0 ) goto no_mem;
76403  pCx->pKeyInfo = pOp->p4.pKeyInfo;
76404  assert( pCx->pKeyInfo->db==db );
76405  assert( pCx->pKeyInfo->enc==ENC(db) );
76406  rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
76407  break;
76408}
76409
76410/* Opcode: SequenceTest P1 P2 * * *
76411** Synopsis: if( cursor[P1].ctr++ ) pc = P2
76412**
76413** P1 is a sorter cursor. If the sequence counter is currently zero, jump
76414** to P2. Regardless of whether or not the jump is taken, increment the
76415** the sequence value.
76416*/
76417case OP_SequenceTest: {
76418  VdbeCursor *pC;
76419  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
76420  pC = p->apCsr[pOp->p1];
76421  assert( pC->pSorter );
76422  if( (pC->seqCount++)==0 ){
76423    goto jump_to_p2;
76424  }
76425  break;
76426}
76427
76428/* Opcode: OpenPseudo P1 P2 P3 * *
76429** Synopsis: P3 columns in r[P2]
76430**
76431** Open a new cursor that points to a fake table that contains a single
76432** row of data.  The content of that one row is the content of memory
76433** register P2.  In other words, cursor P1 becomes an alias for the
76434** MEM_Blob content contained in register P2.
76435**
76436** A pseudo-table created by this opcode is used to hold a single
76437** row output from the sorter so that the row can be decomposed into
76438** individual columns using the OP_Column opcode.  The OP_Column opcode
76439** is the only cursor opcode that works with a pseudo-table.
76440**
76441** P3 is the number of fields in the records that will be stored by
76442** the pseudo-table.
76443*/
76444case OP_OpenPseudo: {
76445  VdbeCursor *pCx;
76446
76447  assert( pOp->p1>=0 );
76448  assert( pOp->p3>=0 );
76449  pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
76450  if( pCx==0 ) goto no_mem;
76451  pCx->nullRow = 1;
76452  pCx->pseudoTableReg = pOp->p2;
76453  pCx->isTable = 1;
76454  assert( pOp->p5==0 );
76455  break;
76456}
76457
76458/* Opcode: Close P1 * * * *
76459**
76460** Close a cursor previously opened as P1.  If P1 is not
76461** currently open, this instruction is a no-op.
76462*/
76463case OP_Close: {
76464  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
76465  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
76466  p->apCsr[pOp->p1] = 0;
76467  break;
76468}
76469
76470#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
76471/* Opcode: ColumnsUsed P1 * * P4 *
76472**
76473** This opcode (which only exists if SQLite was compiled with
76474** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
76475** table or index for cursor P1 are used.  P4 is a 64-bit integer
76476** (P4_INT64) in which the first 63 bits are one for each of the
76477** first 63 columns of the table or index that are actually used
76478** by the cursor.  The high-order bit is set if any column after
76479** the 64th is used.
76480*/
76481case OP_ColumnsUsed: {
76482  VdbeCursor *pC;
76483  pC = p->apCsr[pOp->p1];
76484  assert( pC->pCursor );
76485  pC->maskUsed = *(u64*)pOp->p4.pI64;
76486  break;
76487}
76488#endif
76489
76490/* Opcode: SeekGE 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 the 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 or equal to the key value. If there are no records
76500** greater than or equal to 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, SeekGt, SeekLe
76507*/
76508/* Opcode: SeekGT 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 smallest entry that
76517** is greater than the key value. If there are no records greater than
76518** the key and P2 is not zero, then jump to P2.
76519**
76520** This opcode leaves the cursor configured to move in forward order,
76521** from the beginning toward the end.  In other words, the cursor is
76522** configured to use Next, not Prev.
76523**
76524** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
76525*/
76526/* Opcode: SeekLT 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 the key value. If there are no records less than
76536** 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, SeekLe
76543*/
76544/* Opcode: SeekLE P1 P2 P3 P4 *
76545** Synopsis: key=r[P3@P4]
76546**
76547** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
76548** use the value in register P3 as a key. If cursor P1 refers
76549** to an SQL index, then P3 is the first in an array of P4 registers
76550** that are used as an unpacked index key.
76551**
76552** Reposition cursor P1 so that it points to the largest entry that
76553** is less than or equal to the key value. If there are no records
76554** less than or equal to the key and P2 is not zero, then jump to P2.
76555**
76556** This opcode leaves the cursor configured to move in reverse order,
76557** from the end toward the beginning.  In other words, the cursor is
76558** configured to use Prev, not Next.
76559**
76560** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
76561*/
76562case OP_SeekLT:         /* jump, in3 */
76563case OP_SeekLE:         /* jump, in3 */
76564case OP_SeekGE:         /* jump, in3 */
76565case OP_SeekGT: {       /* jump, in3 */
76566  int res;
76567  int oc;
76568  VdbeCursor *pC;
76569  UnpackedRecord r;
76570  int nField;
76571  i64 iKey;      /* The rowid we are to seek to */
76572
76573  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
76574  assert( pOp->p2!=0 );
76575  pC = p->apCsr[pOp->p1];
76576  assert( pC!=0 );
76577  assert( pC->pseudoTableReg==0 );
76578  assert( OP_SeekLE == OP_SeekLT+1 );
76579  assert( OP_SeekGE == OP_SeekLT+2 );
76580  assert( OP_SeekGT == OP_SeekLT+3 );
76581  assert( pC->isOrdered );
76582  assert( pC->pCursor!=0 );
76583  oc = pOp->opcode;
76584  pC->nullRow = 0;
76585#ifdef SQLITE_DEBUG
76586  pC->seekOp = pOp->opcode;
76587#endif
76588
76589  /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
76590  ** OP_SeekLE opcodes are allowed, and these must be immediately followed
76591  ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
76592  */
76593#ifdef SQLITE_DEBUG
76594  if( sqlite3BtreeCursorHasHint(pC->pCursor, BTREE_SEEK_EQ) ){
76595    assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
76596    assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
76597    assert( pOp[1].p1==pOp[0].p1 );
76598    assert( pOp[1].p2==pOp[0].p2 );
76599    assert( pOp[1].p3==pOp[0].p3 );
76600    assert( pOp[1].p4.i==pOp[0].p4.i );
76601  }
76602#endif
76603
76604  if( pC->isTable ){
76605    /* The input value in P3 might be of any type: integer, real, string,
76606    ** blob, or NULL.  But it needs to be an integer before we can do
76607    ** the seek, so convert it. */
76608    pIn3 = &aMem[pOp->p3];
76609    if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
76610      applyNumericAffinity(pIn3, 0);
76611    }
76612    iKey = sqlite3VdbeIntValue(pIn3);
76613
76614    /* If the P3 value could not be converted into an integer without
76615    ** loss of information, then special processing is required... */
76616    if( (pIn3->flags & MEM_Int)==0 ){
76617      if( (pIn3->flags & MEM_Real)==0 ){
76618        /* If the P3 value cannot be converted into any kind of a number,
76619        ** then the seek is not possible, so jump to P2 */
76620        VdbeBranchTaken(1,2); goto jump_to_p2;
76621        break;
76622      }
76623
76624      /* If the approximation iKey is larger than the actual real search
76625      ** term, substitute >= for > and < for <=. e.g. if the search term
76626      ** is 4.9 and the integer approximation 5:
76627      **
76628      **        (x >  4.9)    ->     (x >= 5)
76629      **        (x <= 4.9)    ->     (x <  5)
76630      */
76631      if( pIn3->u.r<(double)iKey ){
76632        assert( OP_SeekGE==(OP_SeekGT-1) );
76633        assert( OP_SeekLT==(OP_SeekLE-1) );
76634        assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
76635        if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
76636      }
76637
76638      /* If the approximation iKey is smaller than the actual real search
76639      ** term, substitute <= for < and > for >=.  */
76640      else if( pIn3->u.r>(double)iKey ){
76641        assert( OP_SeekLE==(OP_SeekLT+1) );
76642        assert( OP_SeekGT==(OP_SeekGE+1) );
76643        assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
76644        if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
76645      }
76646    }
76647    rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
76648    pC->movetoTarget = iKey;  /* Used by OP_Delete */
76649    if( rc!=SQLITE_OK ){
76650      goto abort_due_to_error;
76651    }
76652  }else{
76653    nField = pOp->p4.i;
76654    assert( pOp->p4type==P4_INT32 );
76655    assert( nField>0 );
76656    r.pKeyInfo = pC->pKeyInfo;
76657    r.nField = (u16)nField;
76658
76659    /* The next line of code computes as follows, only faster:
76660    **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
76661    **     r.default_rc = -1;
76662    **   }else{
76663    **     r.default_rc = +1;
76664    **   }
76665    */
76666    r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
76667    assert( oc!=OP_SeekGT || r.default_rc==-1 );
76668    assert( oc!=OP_SeekLE || r.default_rc==-1 );
76669    assert( oc!=OP_SeekGE || r.default_rc==+1 );
76670    assert( oc!=OP_SeekLT || r.default_rc==+1 );
76671
76672    r.aMem = &aMem[pOp->p3];
76673#ifdef SQLITE_DEBUG
76674    { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
76675#endif
76676    ExpandBlob(r.aMem);
76677    rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
76678    if( rc!=SQLITE_OK ){
76679      goto abort_due_to_error;
76680    }
76681  }
76682  pC->deferredMoveto = 0;
76683  pC->cacheStatus = CACHE_STALE;
76684#ifdef SQLITE_TEST
76685  sqlite3_search_count++;
76686#endif
76687  if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
76688    if( res<0 || (res==0 && oc==OP_SeekGT) ){
76689      res = 0;
76690      rc = sqlite3BtreeNext(pC->pCursor, &res);
76691      if( rc!=SQLITE_OK ) goto abort_due_to_error;
76692    }else{
76693      res = 0;
76694    }
76695  }else{
76696    assert( oc==OP_SeekLT || oc==OP_SeekLE );
76697    if( res>0 || (res==0 && oc==OP_SeekLT) ){
76698      res = 0;
76699      rc = sqlite3BtreePrevious(pC->pCursor, &res);
76700      if( rc!=SQLITE_OK ) goto abort_due_to_error;
76701    }else{
76702      /* res might be negative because the table is empty.  Check to
76703      ** see if this is the case.
76704      */
76705      res = sqlite3BtreeEof(pC->pCursor);
76706    }
76707  }
76708  assert( pOp->p2>0 );
76709  VdbeBranchTaken(res!=0,2);
76710  if( res ){
76711    goto jump_to_p2;
76712  }
76713  break;
76714}
76715
76716/* Opcode: Seek P1 P2 * * *
76717** Synopsis:  intkey=r[P2]
76718**
76719** P1 is an open table cursor and P2 is a rowid integer.  Arrange
76720** for P1 to move so that it points to the rowid given by P2.
76721**
76722** This is actually a deferred seek.  Nothing actually happens until
76723** the cursor is used to read a record.  That way, if no reads
76724** occur, no unnecessary I/O happens.
76725*/
76726case OP_Seek: {    /* in2 */
76727  VdbeCursor *pC;
76728
76729  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
76730  pC = p->apCsr[pOp->p1];
76731  assert( pC!=0 );
76732  assert( pC->pCursor!=0 );
76733  assert( pC->isTable );
76734  pC->nullRow = 0;
76735  pIn2 = &aMem[pOp->p2];
76736  pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
76737  pC->deferredMoveto = 1;
76738  break;
76739}
76740
76741
76742/* Opcode: Found P1 P2 P3 P4 *
76743** Synopsis: key=r[P3@P4]
76744**
76745** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
76746** P4>0 then register P3 is the first of P4 registers that form an unpacked
76747** record.
76748**
76749** Cursor P1 is on an index btree.  If the record identified by P3 and P4
76750** is a prefix of any entry in P1 then a jump is made to P2 and
76751** P1 is left pointing at the matching entry.
76752**
76753** This operation leaves the cursor in a state where it can be
76754** advanced in the forward direction.  The Next instruction will work,
76755** but not the Prev instruction.
76756**
76757** See also: NotFound, NoConflict, NotExists. SeekGe
76758*/
76759/* Opcode: NotFound P1 P2 P3 P4 *
76760** Synopsis: key=r[P3@P4]
76761**
76762** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
76763** P4>0 then register P3 is the first of P4 registers that form an unpacked
76764** record.
76765**
76766** Cursor P1 is on an index btree.  If the record identified by P3 and P4
76767** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
76768** does contain an entry whose prefix matches the P3/P4 record then control
76769** falls through to the next instruction and P1 is left pointing at the
76770** matching entry.
76771**
76772** This operation leaves the cursor in a state where it cannot be
76773** advanced in either direction.  In other words, the Next and Prev
76774** opcodes do not work after this operation.
76775**
76776** See also: Found, NotExists, NoConflict
76777*/
76778/* Opcode: NoConflict P1 P2 P3 P4 *
76779** Synopsis: key=r[P3@P4]
76780**
76781** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
76782** P4>0 then register P3 is the first of P4 registers that form an unpacked
76783** record.
76784**
76785** Cursor P1 is on an index btree.  If the record identified by P3 and P4
76786** contains any NULL value, jump immediately to P2.  If all terms of the
76787** record are not-NULL then a check is done to determine if any row in the
76788** P1 index btree has a matching key prefix.  If there are no matches, jump
76789** immediately to P2.  If there is a match, fall through and leave the P1
76790** cursor pointing to the matching row.
76791**
76792** This opcode is similar to OP_NotFound with the exceptions that the
76793** branch is always taken if any part of the search key input is NULL.
76794**
76795** This operation leaves the cursor in a state where it cannot be
76796** advanced in either direction.  In other words, the Next and Prev
76797** opcodes do not work after this operation.
76798**
76799** See also: NotFound, Found, NotExists
76800*/
76801case OP_NoConflict:     /* jump, in3 */
76802case OP_NotFound:       /* jump, in3 */
76803case OP_Found: {        /* jump, in3 */
76804  int alreadyExists;
76805  int takeJump;
76806  int ii;
76807  VdbeCursor *pC;
76808  int res;
76809  char *pFree;
76810  UnpackedRecord *pIdxKey;
76811  UnpackedRecord r;
76812  char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
76813
76814#ifdef SQLITE_TEST
76815  if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
76816#endif
76817
76818  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
76819  assert( pOp->p4type==P4_INT32 );
76820  pC = p->apCsr[pOp->p1];
76821  assert( pC!=0 );
76822#ifdef SQLITE_DEBUG
76823  pC->seekOp = pOp->opcode;
76824#endif
76825  pIn3 = &aMem[pOp->p3];
76826  assert( pC->pCursor!=0 );
76827  assert( pC->isTable==0 );
76828  pFree = 0;
76829  if( pOp->p4.i>0 ){
76830    r.pKeyInfo = pC->pKeyInfo;
76831    r.nField = (u16)pOp->p4.i;
76832    r.aMem = pIn3;
76833    for(ii=0; ii<r.nField; ii++){
76834      assert( memIsValid(&r.aMem[ii]) );
76835      ExpandBlob(&r.aMem[ii]);
76836#ifdef SQLITE_DEBUG
76837      if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
76838#endif
76839    }
76840    pIdxKey = &r;
76841  }else{
76842    pIdxKey = sqlite3VdbeAllocUnpackedRecord(
76843        pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
76844    );
76845    if( pIdxKey==0 ) goto no_mem;
76846    assert( pIn3->flags & MEM_Blob );
76847    ExpandBlob(pIn3);
76848    sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
76849  }
76850  pIdxKey->default_rc = 0;
76851  takeJump = 0;
76852  if( pOp->opcode==OP_NoConflict ){
76853    /* For the OP_NoConflict opcode, take the jump if any of the
76854    ** input fields are NULL, since any key with a NULL will not
76855    ** conflict */
76856    for(ii=0; ii<pIdxKey->nField; ii++){
76857      if( pIdxKey->aMem[ii].flags & MEM_Null ){
76858        takeJump = 1;
76859        break;
76860      }
76861    }
76862  }
76863  rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
76864  sqlite3DbFree(db, pFree);
76865  if( rc!=SQLITE_OK ){
76866    break;
76867  }
76868  pC->seekResult = res;
76869  alreadyExists = (res==0);
76870  pC->nullRow = 1-alreadyExists;
76871  pC->deferredMoveto = 0;
76872  pC->cacheStatus = CACHE_STALE;
76873  if( pOp->opcode==OP_Found ){
76874    VdbeBranchTaken(alreadyExists!=0,2);
76875    if( alreadyExists ) goto jump_to_p2;
76876  }else{
76877    VdbeBranchTaken(takeJump||alreadyExists==0,2);
76878    if( takeJump || !alreadyExists ) goto jump_to_p2;
76879  }
76880  break;
76881}
76882
76883/* Opcode: NotExists P1 P2 P3 * *
76884** Synopsis: intkey=r[P3]
76885**
76886** P1 is the index of a cursor open on an SQL table btree (with integer
76887** keys).  P3 is an integer rowid.  If P1 does not contain a record with
76888** rowid P3 then jump immediately to P2.  Or, if P2 is 0, raise an
76889** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
76890** leave the cursor pointing at that record and fall through to the next
76891** instruction.
76892**
76893** The OP_NotFound opcode performs the same operation on index btrees
76894** (with arbitrary multi-value keys).
76895**
76896** This opcode leaves the cursor in a state where it cannot be advanced
76897** in either direction.  In other words, the Next and Prev opcodes will
76898** not work following this opcode.
76899**
76900** See also: Found, NotFound, NoConflict
76901*/
76902case OP_NotExists: {        /* jump, in3 */
76903  VdbeCursor *pC;
76904  BtCursor *pCrsr;
76905  int res;
76906  u64 iKey;
76907
76908  pIn3 = &aMem[pOp->p3];
76909  assert( pIn3->flags & MEM_Int );
76910  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
76911  pC = p->apCsr[pOp->p1];
76912  assert( pC!=0 );
76913#ifdef SQLITE_DEBUG
76914  pC->seekOp = 0;
76915#endif
76916  assert( pC->isTable );
76917  assert( pC->pseudoTableReg==0 );
76918  pCrsr = pC->pCursor;
76919  assert( pCrsr!=0 );
76920  res = 0;
76921  iKey = pIn3->u.i;
76922  rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
76923  assert( rc==SQLITE_OK || res==0 );
76924  pC->movetoTarget = iKey;  /* Used by OP_Delete */
76925  pC->nullRow = 0;
76926  pC->cacheStatus = CACHE_STALE;
76927  pC->deferredMoveto = 0;
76928  VdbeBranchTaken(res!=0,2);
76929  pC->seekResult = res;
76930  if( res!=0 ){
76931    assert( rc==SQLITE_OK );
76932    if( pOp->p2==0 ){
76933      rc = SQLITE_CORRUPT_BKPT;
76934    }else{
76935      goto jump_to_p2;
76936    }
76937  }
76938  break;
76939}
76940
76941/* Opcode: Sequence P1 P2 * * *
76942** Synopsis: r[P2]=cursor[P1].ctr++
76943**
76944** Find the next available sequence number for cursor P1.
76945** Write the sequence number into register P2.
76946** The sequence number on the cursor is incremented after this
76947** instruction.
76948*/
76949case OP_Sequence: {           /* out2 */
76950  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
76951  assert( p->apCsr[pOp->p1]!=0 );
76952  pOut = out2Prerelease(p, pOp);
76953  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
76954  break;
76955}
76956
76957
76958/* Opcode: NewRowid P1 P2 P3 * *
76959** Synopsis: r[P2]=rowid
76960**
76961** Get a new integer record number (a.k.a "rowid") used as the key to a table.
76962** The record number is not previously used as a key in the database
76963** table that cursor P1 points to.  The new record number is written
76964** written to register P2.
76965**
76966** If P3>0 then P3 is a register in the root frame of this VDBE that holds
76967** the largest previously generated record number. No new record numbers are
76968** allowed to be less than this value. When this value reaches its maximum,
76969** an SQLITE_FULL error is generated. The P3 register is updated with the '
76970** generated record number. This P3 mechanism is used to help implement the
76971** AUTOINCREMENT feature.
76972*/
76973case OP_NewRowid: {           /* out2 */
76974  i64 v;                 /* The new rowid */
76975  VdbeCursor *pC;        /* Cursor of table to get the new rowid */
76976  int res;               /* Result of an sqlite3BtreeLast() */
76977  int cnt;               /* Counter to limit the number of searches */
76978  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
76979  VdbeFrame *pFrame;     /* Root frame of VDBE */
76980
76981  v = 0;
76982  res = 0;
76983  pOut = out2Prerelease(p, pOp);
76984  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
76985  pC = p->apCsr[pOp->p1];
76986  assert( pC!=0 );
76987  assert( pC->pCursor!=0 );
76988  {
76989    /* The next rowid or record number (different terms for the same
76990    ** thing) is obtained in a two-step algorithm.
76991    **
76992    ** First we attempt to find the largest existing rowid and add one
76993    ** to that.  But if the largest existing rowid is already the maximum
76994    ** positive integer, we have to fall through to the second
76995    ** probabilistic algorithm
76996    **
76997    ** The second algorithm is to select a rowid at random and see if
76998    ** it already exists in the table.  If it does not exist, we have
76999    ** succeeded.  If the random rowid does exist, we select a new one
77000    ** and try again, up to 100 times.
77001    */
77002    assert( pC->isTable );
77003
77004#ifdef SQLITE_32BIT_ROWID
77005#   define MAX_ROWID 0x7fffffff
77006#else
77007    /* Some compilers complain about constants of the form 0x7fffffffffffffff.
77008    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
77009    ** to provide the constant while making all compilers happy.
77010    */
77011#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
77012#endif
77013
77014    if( !pC->useRandomRowid ){
77015      rc = sqlite3BtreeLast(pC->pCursor, &res);
77016      if( rc!=SQLITE_OK ){
77017        goto abort_due_to_error;
77018      }
77019      if( res ){
77020        v = 1;   /* IMP: R-61914-48074 */
77021      }else{
77022        assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
77023        rc = sqlite3BtreeKeySize(pC->pCursor, &v);
77024        assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
77025        if( v>=MAX_ROWID ){
77026          pC->useRandomRowid = 1;
77027        }else{
77028          v++;   /* IMP: R-29538-34987 */
77029        }
77030      }
77031    }
77032
77033#ifndef SQLITE_OMIT_AUTOINCREMENT
77034    if( pOp->p3 ){
77035      /* Assert that P3 is a valid memory cell. */
77036      assert( pOp->p3>0 );
77037      if( p->pFrame ){
77038        for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
77039        /* Assert that P3 is a valid memory cell. */
77040        assert( pOp->p3<=pFrame->nMem );
77041        pMem = &pFrame->aMem[pOp->p3];
77042      }else{
77043        /* Assert that P3 is a valid memory cell. */
77044        assert( pOp->p3<=(p->nMem-p->nCursor) );
77045        pMem = &aMem[pOp->p3];
77046        memAboutToChange(p, pMem);
77047      }
77048      assert( memIsValid(pMem) );
77049
77050      REGISTER_TRACE(pOp->p3, pMem);
77051      sqlite3VdbeMemIntegerify(pMem);
77052      assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
77053      if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
77054        rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
77055        goto abort_due_to_error;
77056      }
77057      if( v<pMem->u.i+1 ){
77058        v = pMem->u.i + 1;
77059      }
77060      pMem->u.i = v;
77061    }
77062#endif
77063    if( pC->useRandomRowid ){
77064      /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
77065      ** largest possible integer (9223372036854775807) then the database
77066      ** engine starts picking positive candidate ROWIDs at random until
77067      ** it finds one that is not previously used. */
77068      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
77069                             ** an AUTOINCREMENT table. */
77070      cnt = 0;
77071      do{
77072        sqlite3_randomness(sizeof(v), &v);
77073        v &= (MAX_ROWID>>1); v++;  /* Ensure that v is greater than zero */
77074      }while(  ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v,
77075                                                 0, &res))==SQLITE_OK)
77076            && (res==0)
77077            && (++cnt<100));
77078      if( rc==SQLITE_OK && res==0 ){
77079        rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
77080        goto abort_due_to_error;
77081      }
77082      assert( v>0 );  /* EV: R-40812-03570 */
77083    }
77084    pC->deferredMoveto = 0;
77085    pC->cacheStatus = CACHE_STALE;
77086  }
77087  pOut->u.i = v;
77088  break;
77089}
77090
77091/* Opcode: Insert P1 P2 P3 P4 P5
77092** Synopsis: intkey=r[P3] data=r[P2]
77093**
77094** Write an entry into the table of cursor P1.  A new entry is
77095** created if it doesn't already exist or the data for an existing
77096** entry is overwritten.  The data is the value MEM_Blob stored in register
77097** number P2. The key is stored in register P3. The key must
77098** be a MEM_Int.
77099**
77100** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
77101** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
77102** then rowid is stored for subsequent return by the
77103** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
77104**
77105** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
77106** the last seek operation (OP_NotExists) was a success, then this
77107** operation will not attempt to find the appropriate row before doing
77108** the insert but will instead overwrite the row that the cursor is
77109** currently pointing to.  Presumably, the prior OP_NotExists opcode
77110** has already positioned the cursor correctly.  This is an optimization
77111** that boosts performance by avoiding redundant seeks.
77112**
77113** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
77114** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
77115** is part of an INSERT operation.  The difference is only important to
77116** the update hook.
77117**
77118** Parameter P4 may point to a string containing the table-name, or
77119** may be NULL. If it is not NULL, then the update-hook
77120** (sqlite3.xUpdateCallback) is invoked following a successful insert.
77121**
77122** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
77123** allocated, then ownership of P2 is transferred to the pseudo-cursor
77124** and register P2 becomes ephemeral.  If the cursor is changed, the
77125** value of register P2 will then change.  Make sure this does not
77126** cause any problems.)
77127**
77128** This instruction only works on tables.  The equivalent instruction
77129** for indices is OP_IdxInsert.
77130*/
77131/* Opcode: InsertInt P1 P2 P3 P4 P5
77132** Synopsis:  intkey=P3 data=r[P2]
77133**
77134** This works exactly like OP_Insert except that the key is the
77135** integer value P3, not the value of the integer stored in register P3.
77136*/
77137case OP_Insert:
77138case OP_InsertInt: {
77139  Mem *pData;       /* MEM cell holding data for the record to be inserted */
77140  Mem *pKey;        /* MEM cell holding key  for the record */
77141  i64 iKey;         /* The integer ROWID or key for the record to be inserted */
77142  VdbeCursor *pC;   /* Cursor to table into which insert is written */
77143  int nZero;        /* Number of zero-bytes to append */
77144  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
77145  const char *zDb;  /* database name - used by the update hook */
77146  const char *zTbl; /* Table name - used by the opdate hook */
77147  int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
77148
77149  pData = &aMem[pOp->p2];
77150  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77151  assert( memIsValid(pData) );
77152  pC = p->apCsr[pOp->p1];
77153  assert( pC!=0 );
77154  assert( pC->pCursor!=0 );
77155  assert( pC->pseudoTableReg==0 );
77156  assert( pC->isTable );
77157  REGISTER_TRACE(pOp->p2, pData);
77158
77159  if( pOp->opcode==OP_Insert ){
77160    pKey = &aMem[pOp->p3];
77161    assert( pKey->flags & MEM_Int );
77162    assert( memIsValid(pKey) );
77163    REGISTER_TRACE(pOp->p3, pKey);
77164    iKey = pKey->u.i;
77165  }else{
77166    assert( pOp->opcode==OP_InsertInt );
77167    iKey = pOp->p3;
77168  }
77169
77170  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
77171  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
77172  if( pData->flags & MEM_Null ){
77173    pData->z = 0;
77174    pData->n = 0;
77175  }else{
77176    assert( pData->flags & (MEM_Blob|MEM_Str) );
77177  }
77178  seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
77179  if( pData->flags & MEM_Zero ){
77180    nZero = pData->u.nZero;
77181  }else{
77182    nZero = 0;
77183  }
77184  rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
77185                          pData->z, pData->n, nZero,
77186                          (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
77187  );
77188  pC->deferredMoveto = 0;
77189  pC->cacheStatus = CACHE_STALE;
77190
77191  /* Invoke the update-hook if required. */
77192  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
77193    zDb = db->aDb[pC->iDb].zName;
77194    zTbl = pOp->p4.z;
77195    op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
77196    assert( pC->isTable );
77197    db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
77198    assert( pC->iDb>=0 );
77199  }
77200  break;
77201}
77202
77203/* Opcode: Delete P1 P2 * P4 P5
77204**
77205** Delete the record at which the P1 cursor is currently pointing.
77206**
77207** If the P5 parameter is non-zero, the cursor will be left pointing at
77208** either the next or the previous record in the table. If it is left
77209** pointing at the next record, then the next Next instruction will be a
77210** no-op. As a result, in this case it is OK to delete a record from within a
77211** Next loop. If P5 is zero, then the cursor is left in an undefined state.
77212**
77213** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
77214** incremented (otherwise not).
77215**
77216** P1 must not be pseudo-table.  It has to be a real table with
77217** multiple rows.
77218**
77219** If P4 is not NULL, then it is the name of the table that P1 is
77220** pointing to.  The update hook will be invoked, if it exists.
77221** If P4 is not NULL then the P1 cursor must have been positioned
77222** using OP_NotFound prior to invoking this opcode.
77223*/
77224case OP_Delete: {
77225  VdbeCursor *pC;
77226  u8 hasUpdateCallback;
77227
77228  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77229  pC = p->apCsr[pOp->p1];
77230  assert( pC!=0 );
77231  assert( pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
77232  assert( pC->deferredMoveto==0 );
77233
77234  hasUpdateCallback = db->xUpdateCallback && pOp->p4.z && pC->isTable;
77235  if( pOp->p5 && hasUpdateCallback ){
77236    sqlite3BtreeKeySize(pC->pCursor, &pC->movetoTarget);
77237  }
77238
77239#ifdef SQLITE_DEBUG
77240  /* The seek operation that positioned the cursor prior to OP_Delete will
77241  ** have also set the pC->movetoTarget field to the rowid of the row that
77242  ** is being deleted */
77243  if( pOp->p4.z && pC->isTable && pOp->p5==0 ){
77244    i64 iKey = 0;
77245    sqlite3BtreeKeySize(pC->pCursor, &iKey);
77246    assert( pC->movetoTarget==iKey );
77247  }
77248#endif
77249
77250  rc = sqlite3BtreeDelete(pC->pCursor, pOp->p5);
77251  pC->cacheStatus = CACHE_STALE;
77252
77253  /* Invoke the update-hook if required. */
77254  if( rc==SQLITE_OK && hasUpdateCallback ){
77255    db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
77256                        db->aDb[pC->iDb].zName, pOp->p4.z, pC->movetoTarget);
77257    assert( pC->iDb>=0 );
77258  }
77259  if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
77260  break;
77261}
77262/* Opcode: ResetCount * * * * *
77263**
77264** The value of the change counter is copied to the database handle
77265** change counter (returned by subsequent calls to sqlite3_changes()).
77266** Then the VMs internal change counter resets to 0.
77267** This is used by trigger programs.
77268*/
77269case OP_ResetCount: {
77270  sqlite3VdbeSetChanges(db, p->nChange);
77271  p->nChange = 0;
77272  break;
77273}
77274
77275/* Opcode: SorterCompare P1 P2 P3 P4
77276** Synopsis:  if key(P1)!=trim(r[P3],P4) goto P2
77277**
77278** P1 is a sorter cursor. This instruction compares a prefix of the
77279** record blob in register P3 against a prefix of the entry that
77280** the sorter cursor currently points to.  Only the first P4 fields
77281** of r[P3] and the sorter record are compared.
77282**
77283** If either P3 or the sorter contains a NULL in one of their significant
77284** fields (not counting the P4 fields at the end which are ignored) then
77285** the comparison is assumed to be equal.
77286**
77287** Fall through to next instruction if the two records compare equal to
77288** each other.  Jump to P2 if they are different.
77289*/
77290case OP_SorterCompare: {
77291  VdbeCursor *pC;
77292  int res;
77293  int nKeyCol;
77294
77295  pC = p->apCsr[pOp->p1];
77296  assert( isSorter(pC) );
77297  assert( pOp->p4type==P4_INT32 );
77298  pIn3 = &aMem[pOp->p3];
77299  nKeyCol = pOp->p4.i;
77300  res = 0;
77301  rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
77302  VdbeBranchTaken(res!=0,2);
77303  if( res ) goto jump_to_p2;
77304  break;
77305};
77306
77307/* Opcode: SorterData P1 P2 P3 * *
77308** Synopsis: r[P2]=data
77309**
77310** Write into register P2 the current sorter data for sorter cursor P1.
77311** Then clear the column header cache on cursor P3.
77312**
77313** This opcode is normally use to move a record out of the sorter and into
77314** a register that is the source for a pseudo-table cursor created using
77315** OpenPseudo.  That pseudo-table cursor is the one that is identified by
77316** parameter P3.  Clearing the P3 column cache as part of this opcode saves
77317** us from having to issue a separate NullRow instruction to clear that cache.
77318*/
77319case OP_SorterData: {
77320  VdbeCursor *pC;
77321
77322  pOut = &aMem[pOp->p2];
77323  pC = p->apCsr[pOp->p1];
77324  assert( isSorter(pC) );
77325  rc = sqlite3VdbeSorterRowkey(pC, pOut);
77326  assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
77327  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77328  p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
77329  break;
77330}
77331
77332/* Opcode: RowData P1 P2 * * *
77333** Synopsis: r[P2]=data
77334**
77335** Write into register P2 the complete row data for cursor P1.
77336** There is no interpretation of the data.
77337** It is just copied onto the P2 register exactly as
77338** it is found in the database file.
77339**
77340** If the P1 cursor must be pointing to a valid row (not a NULL row)
77341** of a real table, not a pseudo-table.
77342*/
77343/* Opcode: RowKey P1 P2 * * *
77344** Synopsis: r[P2]=key
77345**
77346** Write into register P2 the complete row key for cursor P1.
77347** There is no interpretation of the data.
77348** The key is copied onto the P2 register exactly as
77349** it is found in the database file.
77350**
77351** If the P1 cursor must be pointing to a valid row (not a NULL row)
77352** of a real table, not a pseudo-table.
77353*/
77354case OP_RowKey:
77355case OP_RowData: {
77356  VdbeCursor *pC;
77357  BtCursor *pCrsr;
77358  u32 n;
77359  i64 n64;
77360
77361  pOut = &aMem[pOp->p2];
77362  memAboutToChange(p, pOut);
77363
77364  /* Note that RowKey and RowData are really exactly the same instruction */
77365  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77366  pC = p->apCsr[pOp->p1];
77367  assert( isSorter(pC)==0 );
77368  assert( pC->isTable || pOp->opcode!=OP_RowData );
77369  assert( pC->isTable==0 || pOp->opcode==OP_RowData );
77370  assert( pC!=0 );
77371  assert( pC->nullRow==0 );
77372  assert( pC->pseudoTableReg==0 );
77373  assert( pC->pCursor!=0 );
77374  pCrsr = pC->pCursor;
77375
77376  /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
77377  ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
77378  ** the cursor.  If this where not the case, on of the following assert()s
77379  ** would fail.  Should this ever change (because of changes in the code
77380  ** generator) then the fix would be to insert a call to
77381  ** sqlite3VdbeCursorMoveto().
77382  */
77383  assert( pC->deferredMoveto==0 );
77384  assert( sqlite3BtreeCursorIsValid(pCrsr) );
77385#if 0  /* Not required due to the previous to assert() statements */
77386  rc = sqlite3VdbeCursorMoveto(pC);
77387  if( rc!=SQLITE_OK ) goto abort_due_to_error;
77388#endif
77389
77390  if( pC->isTable==0 ){
77391    assert( !pC->isTable );
77392    VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
77393    assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
77394    if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
77395      goto too_big;
77396    }
77397    n = (u32)n64;
77398  }else{
77399    VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
77400    assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
77401    if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
77402      goto too_big;
77403    }
77404  }
77405  testcase( n==0 );
77406  if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){
77407    goto no_mem;
77408  }
77409  pOut->n = n;
77410  MemSetTypeFlag(pOut, MEM_Blob);
77411  if( pC->isTable==0 ){
77412    rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
77413  }else{
77414    rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
77415  }
77416  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
77417  UPDATE_MAX_BLOBSIZE(pOut);
77418  REGISTER_TRACE(pOp->p2, pOut);
77419  break;
77420}
77421
77422/* Opcode: Rowid P1 P2 * * *
77423** Synopsis: r[P2]=rowid
77424**
77425** Store in register P2 an integer which is the key of the table entry that
77426** P1 is currently point to.
77427**
77428** P1 can be either an ordinary table or a virtual table.  There used to
77429** be a separate OP_VRowid opcode for use with virtual tables, but this
77430** one opcode now works for both table types.
77431*/
77432case OP_Rowid: {                 /* out2 */
77433  VdbeCursor *pC;
77434  i64 v;
77435  sqlite3_vtab *pVtab;
77436  const sqlite3_module *pModule;
77437
77438  pOut = out2Prerelease(p, pOp);
77439  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77440  pC = p->apCsr[pOp->p1];
77441  assert( pC!=0 );
77442  assert( pC->pseudoTableReg==0 || pC->nullRow );
77443  if( pC->nullRow ){
77444    pOut->flags = MEM_Null;
77445    break;
77446  }else if( pC->deferredMoveto ){
77447    v = pC->movetoTarget;
77448#ifndef SQLITE_OMIT_VIRTUALTABLE
77449  }else if( pC->pVtabCursor ){
77450    pVtab = pC->pVtabCursor->pVtab;
77451    pModule = pVtab->pModule;
77452    assert( pModule->xRowid );
77453    rc = pModule->xRowid(pC->pVtabCursor, &v);
77454    sqlite3VtabImportErrmsg(p, pVtab);
77455#endif /* SQLITE_OMIT_VIRTUALTABLE */
77456  }else{
77457    assert( pC->pCursor!=0 );
77458    rc = sqlite3VdbeCursorRestore(pC);
77459    if( rc ) goto abort_due_to_error;
77460    if( pC->nullRow ){
77461      pOut->flags = MEM_Null;
77462      break;
77463    }
77464    rc = sqlite3BtreeKeySize(pC->pCursor, &v);
77465    assert( rc==SQLITE_OK );  /* Always so because of CursorRestore() above */
77466  }
77467  pOut->u.i = v;
77468  break;
77469}
77470
77471/* Opcode: NullRow P1 * * * *
77472**
77473** Move the cursor P1 to a null row.  Any OP_Column operations
77474** that occur while the cursor is on the null row will always
77475** write a NULL.
77476*/
77477case OP_NullRow: {
77478  VdbeCursor *pC;
77479
77480  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77481  pC = p->apCsr[pOp->p1];
77482  assert( pC!=0 );
77483  pC->nullRow = 1;
77484  pC->cacheStatus = CACHE_STALE;
77485  if( pC->pCursor ){
77486    sqlite3BtreeClearCursor(pC->pCursor);
77487  }
77488  break;
77489}
77490
77491/* Opcode: Last P1 P2 P3 * *
77492**
77493** The next use of the Rowid or Column or Prev instruction for P1
77494** will refer to the last entry in the database table or index.
77495** If the table or index is empty and P2>0, then jump immediately to P2.
77496** If P2 is 0 or if the table or index is not empty, fall through
77497** to the following instruction.
77498**
77499** This opcode leaves the cursor configured to move in reverse order,
77500** from the end toward the beginning.  In other words, the cursor is
77501** configured to use Prev, not Next.
77502*/
77503case OP_Last: {        /* jump */
77504  VdbeCursor *pC;
77505  BtCursor *pCrsr;
77506  int res;
77507
77508  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77509  pC = p->apCsr[pOp->p1];
77510  assert( pC!=0 );
77511  pCrsr = pC->pCursor;
77512  res = 0;
77513  assert( pCrsr!=0 );
77514  rc = sqlite3BtreeLast(pCrsr, &res);
77515  pC->nullRow = (u8)res;
77516  pC->deferredMoveto = 0;
77517  pC->cacheStatus = CACHE_STALE;
77518  pC->seekResult = pOp->p3;
77519#ifdef SQLITE_DEBUG
77520  pC->seekOp = OP_Last;
77521#endif
77522  if( pOp->p2>0 ){
77523    VdbeBranchTaken(res!=0,2);
77524    if( res ) goto jump_to_p2;
77525  }
77526  break;
77527}
77528
77529
77530/* Opcode: Sort P1 P2 * * *
77531**
77532** This opcode does exactly the same thing as OP_Rewind except that
77533** it increments an undocumented global variable used for testing.
77534**
77535** Sorting is accomplished by writing records into a sorting index,
77536** then rewinding that index and playing it back from beginning to
77537** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
77538** rewinding so that the global variable will be incremented and
77539** regression tests can determine whether or not the optimizer is
77540** correctly optimizing out sorts.
77541*/
77542case OP_SorterSort:    /* jump */
77543case OP_Sort: {        /* jump */
77544#ifdef SQLITE_TEST
77545  sqlite3_sort_count++;
77546  sqlite3_search_count--;
77547#endif
77548  p->aCounter[SQLITE_STMTSTATUS_SORT]++;
77549  /* Fall through into OP_Rewind */
77550}
77551/* Opcode: Rewind P1 P2 * * *
77552**
77553** The next use of the Rowid or Column or Next instruction for P1
77554** will refer to the first entry in the database table or index.
77555** If the table or index is empty, jump immediately to P2.
77556** If the table or index is not empty, fall through to the following
77557** instruction.
77558**
77559** This opcode leaves the cursor configured to move in forward order,
77560** from the beginning toward the end.  In other words, the cursor is
77561** configured to use Next, not Prev.
77562*/
77563case OP_Rewind: {        /* jump */
77564  VdbeCursor *pC;
77565  BtCursor *pCrsr;
77566  int res;
77567
77568  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77569  pC = p->apCsr[pOp->p1];
77570  assert( pC!=0 );
77571  assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
77572  res = 1;
77573#ifdef SQLITE_DEBUG
77574  pC->seekOp = OP_Rewind;
77575#endif
77576  if( isSorter(pC) ){
77577    rc = sqlite3VdbeSorterRewind(pC, &res);
77578  }else{
77579    pCrsr = pC->pCursor;
77580    assert( pCrsr );
77581    rc = sqlite3BtreeFirst(pCrsr, &res);
77582    pC->deferredMoveto = 0;
77583    pC->cacheStatus = CACHE_STALE;
77584  }
77585  pC->nullRow = (u8)res;
77586  assert( pOp->p2>0 && pOp->p2<p->nOp );
77587  VdbeBranchTaken(res!=0,2);
77588  if( res ) goto jump_to_p2;
77589  break;
77590}
77591
77592/* Opcode: Next P1 P2 P3 P4 P5
77593**
77594** Advance cursor P1 so that it points to the next key/data pair in its
77595** table or index.  If there are no more key/value pairs then fall through
77596** to the following instruction.  But if the cursor advance was successful,
77597** jump immediately to P2.
77598**
77599** The Next opcode is only valid following an SeekGT, SeekGE, or
77600** OP_Rewind opcode used to position the cursor.  Next is not allowed
77601** to follow SeekLT, SeekLE, or OP_Last.
77602**
77603** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
77604** been opened prior to this opcode or the program will segfault.
77605**
77606** The P3 value is a hint to the btree implementation. If P3==1, that
77607** means P1 is an SQL index and that this instruction could have been
77608** omitted if that index had been unique.  P3 is usually 0.  P3 is
77609** always either 0 or 1.
77610**
77611** P4 is always of type P4_ADVANCE. The function pointer points to
77612** sqlite3BtreeNext().
77613**
77614** If P5 is positive and the jump is taken, then event counter
77615** number P5-1 in the prepared statement is incremented.
77616**
77617** See also: Prev, NextIfOpen
77618*/
77619/* Opcode: NextIfOpen P1 P2 P3 P4 P5
77620**
77621** This opcode works just like Next except that if cursor P1 is not
77622** open it behaves a no-op.
77623*/
77624/* Opcode: Prev P1 P2 P3 P4 P5
77625**
77626** Back up cursor P1 so that it points to the previous key/data pair in its
77627** table or index.  If there is no previous key/value pairs then fall through
77628** to the following instruction.  But if the cursor backup was successful,
77629** jump immediately to P2.
77630**
77631**
77632** The Prev opcode is only valid following an SeekLT, SeekLE, or
77633** OP_Last opcode used to position the cursor.  Prev is not allowed
77634** to follow SeekGT, SeekGE, or OP_Rewind.
77635**
77636** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
77637** not open then the behavior is undefined.
77638**
77639** The P3 value is a hint to the btree implementation. If P3==1, that
77640** means P1 is an SQL index and that this instruction could have been
77641** omitted if that index had been unique.  P3 is usually 0.  P3 is
77642** always either 0 or 1.
77643**
77644** P4 is always of type P4_ADVANCE. The function pointer points to
77645** sqlite3BtreePrevious().
77646**
77647** If P5 is positive and the jump is taken, then event counter
77648** number P5-1 in the prepared statement is incremented.
77649*/
77650/* Opcode: PrevIfOpen P1 P2 P3 P4 P5
77651**
77652** This opcode works just like Prev except that if cursor P1 is not
77653** open it behaves a no-op.
77654*/
77655case OP_SorterNext: {  /* jump */
77656  VdbeCursor *pC;
77657  int res;
77658
77659  pC = p->apCsr[pOp->p1];
77660  assert( isSorter(pC) );
77661  res = 0;
77662  rc = sqlite3VdbeSorterNext(db, pC, &res);
77663  goto next_tail;
77664case OP_PrevIfOpen:    /* jump */
77665case OP_NextIfOpen:    /* jump */
77666  if( p->apCsr[pOp->p1]==0 ) break;
77667  /* Fall through */
77668case OP_Prev:          /* jump */
77669case OP_Next:          /* jump */
77670  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77671  assert( pOp->p5<ArraySize(p->aCounter) );
77672  pC = p->apCsr[pOp->p1];
77673  res = pOp->p3;
77674  assert( pC!=0 );
77675  assert( pC->deferredMoveto==0 );
77676  assert( pC->pCursor );
77677  assert( res==0 || (res==1 && pC->isTable==0) );
77678  testcase( res==1 );
77679  assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
77680  assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
77681  assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
77682  assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
77683
77684  /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
77685  ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
77686  assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
77687       || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
77688       || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
77689  assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
77690       || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
77691       || pC->seekOp==OP_Last );
77692
77693  rc = pOp->p4.xAdvance(pC->pCursor, &res);
77694next_tail:
77695  pC->cacheStatus = CACHE_STALE;
77696  VdbeBranchTaken(res==0,2);
77697  if( res==0 ){
77698    pC->nullRow = 0;
77699    p->aCounter[pOp->p5]++;
77700#ifdef SQLITE_TEST
77701    sqlite3_search_count++;
77702#endif
77703    goto jump_to_p2_and_check_for_interrupt;
77704  }else{
77705    pC->nullRow = 1;
77706  }
77707  goto check_for_interrupt;
77708}
77709
77710/* Opcode: IdxInsert P1 P2 P3 * P5
77711** Synopsis: key=r[P2]
77712**
77713** Register P2 holds an SQL index key made using the
77714** MakeRecord instructions.  This opcode writes that key
77715** into the index P1.  Data for the entry is nil.
77716**
77717** P3 is a flag that provides a hint to the b-tree layer that this
77718** insert is likely to be an append.
77719**
77720** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
77721** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
77722** then the change counter is unchanged.
77723**
77724** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
77725** just done a seek to the spot where the new entry is to be inserted.
77726** This flag avoids doing an extra seek.
77727**
77728** This instruction only works for indices.  The equivalent instruction
77729** for tables is OP_Insert.
77730*/
77731case OP_SorterInsert:       /* in2 */
77732case OP_IdxInsert: {        /* in2 */
77733  VdbeCursor *pC;
77734  int nKey;
77735  const char *zKey;
77736
77737  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77738  pC = p->apCsr[pOp->p1];
77739  assert( pC!=0 );
77740  assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
77741  pIn2 = &aMem[pOp->p2];
77742  assert( pIn2->flags & MEM_Blob );
77743  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
77744  assert( pC->pCursor!=0 );
77745  assert( pC->isTable==0 );
77746  rc = ExpandBlob(pIn2);
77747  if( rc==SQLITE_OK ){
77748    if( pOp->opcode==OP_SorterInsert ){
77749      rc = sqlite3VdbeSorterWrite(pC, pIn2);
77750    }else{
77751      nKey = pIn2->n;
77752      zKey = pIn2->z;
77753      rc = sqlite3BtreeInsert(pC->pCursor, zKey, nKey, "", 0, 0, pOp->p3,
77754          ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
77755          );
77756      assert( pC->deferredMoveto==0 );
77757      pC->cacheStatus = CACHE_STALE;
77758    }
77759  }
77760  break;
77761}
77762
77763/* Opcode: IdxDelete P1 P2 P3 * *
77764** Synopsis: key=r[P2@P3]
77765**
77766** The content of P3 registers starting at register P2 form
77767** an unpacked index key. This opcode removes that entry from the
77768** index opened by cursor P1.
77769*/
77770case OP_IdxDelete: {
77771  VdbeCursor *pC;
77772  BtCursor *pCrsr;
77773  int res;
77774  UnpackedRecord r;
77775
77776  assert( pOp->p3>0 );
77777  assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
77778  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77779  pC = p->apCsr[pOp->p1];
77780  assert( pC!=0 );
77781  pCrsr = pC->pCursor;
77782  assert( pCrsr!=0 );
77783  assert( pOp->p5==0 );
77784  r.pKeyInfo = pC->pKeyInfo;
77785  r.nField = (u16)pOp->p3;
77786  r.default_rc = 0;
77787  r.aMem = &aMem[pOp->p2];
77788#ifdef SQLITE_DEBUG
77789  { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
77790#endif
77791  rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
77792  if( rc==SQLITE_OK && res==0 ){
77793    rc = sqlite3BtreeDelete(pCrsr, 0);
77794  }
77795  assert( pC->deferredMoveto==0 );
77796  pC->cacheStatus = CACHE_STALE;
77797  break;
77798}
77799
77800/* Opcode: IdxRowid P1 P2 * * *
77801** Synopsis: r[P2]=rowid
77802**
77803** Write into register P2 an integer which is the last entry in the record at
77804** the end of the index key pointed to by cursor P1.  This integer should be
77805** the rowid of the table entry to which this index entry points.
77806**
77807** See also: Rowid, MakeRecord.
77808*/
77809case OP_IdxRowid: {              /* out2 */
77810  BtCursor *pCrsr;
77811  VdbeCursor *pC;
77812  i64 rowid;
77813
77814  pOut = out2Prerelease(p, pOp);
77815  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77816  pC = p->apCsr[pOp->p1];
77817  assert( pC!=0 );
77818  pCrsr = pC->pCursor;
77819  assert( pCrsr!=0 );
77820  pOut->flags = MEM_Null;
77821  assert( pC->isTable==0 );
77822  assert( pC->deferredMoveto==0 );
77823
77824  /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
77825  ** out from under the cursor.  That will never happend for an IdxRowid
77826  ** opcode, hence the NEVER() arround the check of the return value.
77827  */
77828  rc = sqlite3VdbeCursorRestore(pC);
77829  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
77830
77831  if( !pC->nullRow ){
77832    rowid = 0;  /* Not needed.  Only used to silence a warning. */
77833    rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid);
77834    if( rc!=SQLITE_OK ){
77835      goto abort_due_to_error;
77836    }
77837    pOut->u.i = rowid;
77838    pOut->flags = MEM_Int;
77839  }
77840  break;
77841}
77842
77843/* Opcode: IdxGE P1 P2 P3 P4 P5
77844** Synopsis: key=r[P3@P4]
77845**
77846** The P4 register values beginning with P3 form an unpacked index
77847** key that omits the PRIMARY KEY.  Compare this key value against the index
77848** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
77849** fields at the end.
77850**
77851** If the P1 index entry is greater than or equal to the key value
77852** then jump to P2.  Otherwise fall through to the next instruction.
77853*/
77854/* Opcode: IdxGT P1 P2 P3 P4 P5
77855** Synopsis: key=r[P3@P4]
77856**
77857** The P4 register values beginning with P3 form an unpacked index
77858** key that omits the PRIMARY KEY.  Compare this key value against the index
77859** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
77860** fields at the end.
77861**
77862** If the P1 index entry is greater than the key value
77863** then jump to P2.  Otherwise fall through to the next instruction.
77864*/
77865/* Opcode: IdxLT P1 P2 P3 P4 P5
77866** Synopsis: key=r[P3@P4]
77867**
77868** The P4 register values beginning with P3 form an unpacked index
77869** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
77870** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
77871** ROWID on the P1 index.
77872**
77873** If the P1 index entry is less than the key value then jump to P2.
77874** Otherwise fall through to the next instruction.
77875*/
77876/* Opcode: IdxLE P1 P2 P3 P4 P5
77877** Synopsis: key=r[P3@P4]
77878**
77879** The P4 register values beginning with P3 form an unpacked index
77880** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
77881** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
77882** ROWID on the P1 index.
77883**
77884** If the P1 index entry is less than or equal to the key value then jump
77885** to P2. Otherwise fall through to the next instruction.
77886*/
77887case OP_IdxLE:          /* jump */
77888case OP_IdxGT:          /* jump */
77889case OP_IdxLT:          /* jump */
77890case OP_IdxGE:  {       /* jump */
77891  VdbeCursor *pC;
77892  int res;
77893  UnpackedRecord r;
77894
77895  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
77896  pC = p->apCsr[pOp->p1];
77897  assert( pC!=0 );
77898  assert( pC->isOrdered );
77899  assert( pC->pCursor!=0);
77900  assert( pC->deferredMoveto==0 );
77901  assert( pOp->p5==0 || pOp->p5==1 );
77902  assert( pOp->p4type==P4_INT32 );
77903  r.pKeyInfo = pC->pKeyInfo;
77904  r.nField = (u16)pOp->p4.i;
77905  if( pOp->opcode<OP_IdxLT ){
77906    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
77907    r.default_rc = -1;
77908  }else{
77909    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
77910    r.default_rc = 0;
77911  }
77912  r.aMem = &aMem[pOp->p3];
77913#ifdef SQLITE_DEBUG
77914  { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
77915#endif
77916  res = 0;  /* Not needed.  Only used to silence a warning. */
77917  rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
77918  assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
77919  if( (pOp->opcode&1)==(OP_IdxLT&1) ){
77920    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
77921    res = -res;
77922  }else{
77923    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
77924    res++;
77925  }
77926  VdbeBranchTaken(res>0,2);
77927  if( res>0 ) goto jump_to_p2;
77928  break;
77929}
77930
77931/* Opcode: Destroy P1 P2 P3 * *
77932**
77933** Delete an entire database table or index whose root page in the database
77934** file is given by P1.
77935**
77936** The table being destroyed is in the main database file if P3==0.  If
77937** P3==1 then the table to be clear is in the auxiliary database file
77938** that is used to store tables create using CREATE TEMPORARY TABLE.
77939**
77940** If AUTOVACUUM is enabled then it is possible that another root page
77941** might be moved into the newly deleted root page in order to keep all
77942** root pages contiguous at the beginning of the database.  The former
77943** value of the root page that moved - its value before the move occurred -
77944** is stored in register P2.  If no page
77945** movement was required (because the table being dropped was already
77946** the last one in the database) then a zero is stored in register P2.
77947** If AUTOVACUUM is disabled then a zero is stored in register P2.
77948**
77949** See also: Clear
77950*/
77951case OP_Destroy: {     /* out2 */
77952  int iMoved;
77953  int iDb;
77954
77955  assert( p->readOnly==0 );
77956  pOut = out2Prerelease(p, pOp);
77957  pOut->flags = MEM_Null;
77958  if( db->nVdbeRead > db->nVDestroy+1 ){
77959    rc = SQLITE_LOCKED;
77960    p->errorAction = OE_Abort;
77961  }else{
77962    iDb = pOp->p3;
77963    assert( DbMaskTest(p->btreeMask, iDb) );
77964    iMoved = 0;  /* Not needed.  Only to silence a warning. */
77965    rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
77966    pOut->flags = MEM_Int;
77967    pOut->u.i = iMoved;
77968#ifndef SQLITE_OMIT_AUTOVACUUM
77969    if( rc==SQLITE_OK && iMoved!=0 ){
77970      sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
77971      /* All OP_Destroy operations occur on the same btree */
77972      assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
77973      resetSchemaOnFault = iDb+1;
77974    }
77975#endif
77976  }
77977  break;
77978}
77979
77980/* Opcode: Clear P1 P2 P3
77981**
77982** Delete all contents of the database table or index whose root page
77983** in the database file is given by P1.  But, unlike Destroy, do not
77984** remove the table or index from the database file.
77985**
77986** The table being clear is in the main database file if P2==0.  If
77987** P2==1 then the table to be clear is in the auxiliary database file
77988** that is used to store tables create using CREATE TEMPORARY TABLE.
77989**
77990** If the P3 value is non-zero, then the table referred to must be an
77991** intkey table (an SQL table, not an index). In this case the row change
77992** count is incremented by the number of rows in the table being cleared.
77993** If P3 is greater than zero, then the value stored in register P3 is
77994** also incremented by the number of rows in the table being cleared.
77995**
77996** See also: Destroy
77997*/
77998case OP_Clear: {
77999  int nChange;
78000
78001  nChange = 0;
78002  assert( p->readOnly==0 );
78003  assert( DbMaskTest(p->btreeMask, pOp->p2) );
78004  rc = sqlite3BtreeClearTable(
78005      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
78006  );
78007  if( pOp->p3 ){
78008    p->nChange += nChange;
78009    if( pOp->p3>0 ){
78010      assert( memIsValid(&aMem[pOp->p3]) );
78011      memAboutToChange(p, &aMem[pOp->p3]);
78012      aMem[pOp->p3].u.i += nChange;
78013    }
78014  }
78015  break;
78016}
78017
78018/* Opcode: ResetSorter P1 * * * *
78019**
78020** Delete all contents from the ephemeral table or sorter
78021** that is open on cursor P1.
78022**
78023** This opcode only works for cursors used for sorting and
78024** opened with OP_OpenEphemeral or OP_SorterOpen.
78025*/
78026case OP_ResetSorter: {
78027  VdbeCursor *pC;
78028
78029  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
78030  pC = p->apCsr[pOp->p1];
78031  assert( pC!=0 );
78032  if( pC->pSorter ){
78033    sqlite3VdbeSorterReset(db, pC->pSorter);
78034  }else{
78035    assert( pC->isEphemeral );
78036    rc = sqlite3BtreeClearTableOfCursor(pC->pCursor);
78037  }
78038  break;
78039}
78040
78041/* Opcode: CreateTable P1 P2 * * *
78042** Synopsis: r[P2]=root iDb=P1
78043**
78044** Allocate a new table in the main database file if P1==0 or in the
78045** auxiliary database file if P1==1 or in an attached database if
78046** P1>1.  Write the root page number of the new table into
78047** register P2
78048**
78049** The difference between a table and an index is this:  A table must
78050** have a 4-byte integer key and can have arbitrary data.  An index
78051** has an arbitrary key but no data.
78052**
78053** See also: CreateIndex
78054*/
78055/* Opcode: CreateIndex P1 P2 * * *
78056** Synopsis: r[P2]=root iDb=P1
78057**
78058** Allocate a new index in the main database file if P1==0 or in the
78059** auxiliary database file if P1==1 or in an attached database if
78060** P1>1.  Write the root page number of the new table into
78061** register P2.
78062**
78063** See documentation on OP_CreateTable for additional information.
78064*/
78065case OP_CreateIndex:            /* out2 */
78066case OP_CreateTable: {          /* out2 */
78067  int pgno;
78068  int flags;
78069  Db *pDb;
78070
78071  pOut = out2Prerelease(p, pOp);
78072  pgno = 0;
78073  assert( pOp->p1>=0 && pOp->p1<db->nDb );
78074  assert( DbMaskTest(p->btreeMask, pOp->p1) );
78075  assert( p->readOnly==0 );
78076  pDb = &db->aDb[pOp->p1];
78077  assert( pDb->pBt!=0 );
78078  if( pOp->opcode==OP_CreateTable ){
78079    /* flags = BTREE_INTKEY; */
78080    flags = BTREE_INTKEY;
78081  }else{
78082    flags = BTREE_BLOBKEY;
78083  }
78084  rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
78085  pOut->u.i = pgno;
78086  break;
78087}
78088
78089/* Opcode: ParseSchema P1 * * P4 *
78090**
78091** Read and parse all entries from the SQLITE_MASTER table of database P1
78092** that match the WHERE clause P4.
78093**
78094** This opcode invokes the parser to create a new virtual machine,
78095** then runs the new virtual machine.  It is thus a re-entrant opcode.
78096*/
78097case OP_ParseSchema: {
78098  int iDb;
78099  const char *zMaster;
78100  char *zSql;
78101  InitData initData;
78102
78103  /* Any prepared statement that invokes this opcode will hold mutexes
78104  ** on every btree.  This is a prerequisite for invoking
78105  ** sqlite3InitCallback().
78106  */
78107#ifdef SQLITE_DEBUG
78108  for(iDb=0; iDb<db->nDb; iDb++){
78109    assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
78110  }
78111#endif
78112
78113  iDb = pOp->p1;
78114  assert( iDb>=0 && iDb<db->nDb );
78115  assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
78116  /* Used to be a conditional */ {
78117    zMaster = SCHEMA_TABLE(iDb);
78118    initData.db = db;
78119    initData.iDb = pOp->p1;
78120    initData.pzErrMsg = &p->zErrMsg;
78121    zSql = sqlite3MPrintf(db,
78122       "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
78123       db->aDb[iDb].zName, zMaster, pOp->p4.z);
78124    if( zSql==0 ){
78125      rc = SQLITE_NOMEM;
78126    }else{
78127      assert( db->init.busy==0 );
78128      db->init.busy = 1;
78129      initData.rc = SQLITE_OK;
78130      assert( !db->mallocFailed );
78131      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
78132      if( rc==SQLITE_OK ) rc = initData.rc;
78133      sqlite3DbFree(db, zSql);
78134      db->init.busy = 0;
78135    }
78136  }
78137  if( rc ) sqlite3ResetAllSchemasOfConnection(db);
78138  if( rc==SQLITE_NOMEM ){
78139    goto no_mem;
78140  }
78141  break;
78142}
78143
78144#if !defined(SQLITE_OMIT_ANALYZE)
78145/* Opcode: LoadAnalysis P1 * * * *
78146**
78147** Read the sqlite_stat1 table for database P1 and load the content
78148** of that table into the internal index hash table.  This will cause
78149** the analysis to be used when preparing all subsequent queries.
78150*/
78151case OP_LoadAnalysis: {
78152  assert( pOp->p1>=0 && pOp->p1<db->nDb );
78153  rc = sqlite3AnalysisLoad(db, pOp->p1);
78154  break;
78155}
78156#endif /* !defined(SQLITE_OMIT_ANALYZE) */
78157
78158/* Opcode: DropTable P1 * * P4 *
78159**
78160** Remove the internal (in-memory) data structures that describe
78161** the table named P4 in database P1.  This is called after a table
78162** is dropped from disk (using the Destroy opcode) in order to keep
78163** the internal representation of the
78164** schema consistent with what is on disk.
78165*/
78166case OP_DropTable: {
78167  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
78168  break;
78169}
78170
78171/* Opcode: DropIndex P1 * * P4 *
78172**
78173** Remove the internal (in-memory) data structures that describe
78174** the index named P4 in database P1.  This is called after an index
78175** is dropped from disk (using the Destroy opcode)
78176** in order to keep the internal representation of the
78177** schema consistent with what is on disk.
78178*/
78179case OP_DropIndex: {
78180  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
78181  break;
78182}
78183
78184/* Opcode: DropTrigger P1 * * P4 *
78185**
78186** Remove the internal (in-memory) data structures that describe
78187** the trigger named P4 in database P1.  This is called after a trigger
78188** is dropped from disk (using the Destroy opcode) in order to keep
78189** the internal representation of the
78190** schema consistent with what is on disk.
78191*/
78192case OP_DropTrigger: {
78193  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
78194  break;
78195}
78196
78197
78198#ifndef SQLITE_OMIT_INTEGRITY_CHECK
78199/* Opcode: IntegrityCk P1 P2 P3 * P5
78200**
78201** Do an analysis of the currently open database.  Store in
78202** register P1 the text of an error message describing any problems.
78203** If no problems are found, store a NULL in register P1.
78204**
78205** The register P3 contains the maximum number of allowed errors.
78206** At most reg(P3) errors will be reported.
78207** In other words, the analysis stops as soon as reg(P1) errors are
78208** seen.  Reg(P1) is updated with the number of errors remaining.
78209**
78210** The root page numbers of all tables in the database are integer
78211** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
78212** total.
78213**
78214** If P5 is not zero, the check is done on the auxiliary database
78215** file, not the main database file.
78216**
78217** This opcode is used to implement the integrity_check pragma.
78218*/
78219case OP_IntegrityCk: {
78220  int nRoot;      /* Number of tables to check.  (Number of root pages.) */
78221  int *aRoot;     /* Array of rootpage numbers for tables to be checked */
78222  int j;          /* Loop counter */
78223  int nErr;       /* Number of errors reported */
78224  char *z;        /* Text of the error report */
78225  Mem *pnErr;     /* Register keeping track of errors remaining */
78226
78227  assert( p->bIsReader );
78228  nRoot = pOp->p2;
78229  assert( nRoot>0 );
78230  aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
78231  if( aRoot==0 ) goto no_mem;
78232  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
78233  pnErr = &aMem[pOp->p3];
78234  assert( (pnErr->flags & MEM_Int)!=0 );
78235  assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
78236  pIn1 = &aMem[pOp->p1];
78237  for(j=0; j<nRoot; j++){
78238    aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
78239  }
78240  aRoot[j] = 0;
78241  assert( pOp->p5<db->nDb );
78242  assert( DbMaskTest(p->btreeMask, pOp->p5) );
78243  z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
78244                                 (int)pnErr->u.i, &nErr);
78245  sqlite3DbFree(db, aRoot);
78246  pnErr->u.i -= nErr;
78247  sqlite3VdbeMemSetNull(pIn1);
78248  if( nErr==0 ){
78249    assert( z==0 );
78250  }else if( z==0 ){
78251    goto no_mem;
78252  }else{
78253    sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
78254  }
78255  UPDATE_MAX_BLOBSIZE(pIn1);
78256  sqlite3VdbeChangeEncoding(pIn1, encoding);
78257  break;
78258}
78259#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
78260
78261/* Opcode: RowSetAdd P1 P2 * * *
78262** Synopsis:  rowset(P1)=r[P2]
78263**
78264** Insert the integer value held by register P2 into a boolean index
78265** held in register P1.
78266**
78267** An assertion fails if P2 is not an integer.
78268*/
78269case OP_RowSetAdd: {       /* in1, in2 */
78270  pIn1 = &aMem[pOp->p1];
78271  pIn2 = &aMem[pOp->p2];
78272  assert( (pIn2->flags & MEM_Int)!=0 );
78273  if( (pIn1->flags & MEM_RowSet)==0 ){
78274    sqlite3VdbeMemSetRowSet(pIn1);
78275    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
78276  }
78277  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
78278  break;
78279}
78280
78281/* Opcode: RowSetRead P1 P2 P3 * *
78282** Synopsis:  r[P3]=rowset(P1)
78283**
78284** Extract the smallest value from boolean index P1 and put that value into
78285** register P3.  Or, if boolean index P1 is initially empty, leave P3
78286** unchanged and jump to instruction P2.
78287*/
78288case OP_RowSetRead: {       /* jump, in1, out3 */
78289  i64 val;
78290
78291  pIn1 = &aMem[pOp->p1];
78292  if( (pIn1->flags & MEM_RowSet)==0
78293   || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
78294  ){
78295    /* The boolean index is empty */
78296    sqlite3VdbeMemSetNull(pIn1);
78297    VdbeBranchTaken(1,2);
78298    goto jump_to_p2_and_check_for_interrupt;
78299  }else{
78300    /* A value was pulled from the index */
78301    VdbeBranchTaken(0,2);
78302    sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
78303  }
78304  goto check_for_interrupt;
78305}
78306
78307/* Opcode: RowSetTest P1 P2 P3 P4
78308** Synopsis: if r[P3] in rowset(P1) goto P2
78309**
78310** Register P3 is assumed to hold a 64-bit integer value. If register P1
78311** contains a RowSet object and that RowSet object contains
78312** the value held in P3, jump to register P2. Otherwise, insert the
78313** integer in P3 into the RowSet and continue on to the
78314** next opcode.
78315**
78316** The RowSet object is optimized for the case where successive sets
78317** of integers, where each set contains no duplicates. Each set
78318** of values is identified by a unique P4 value. The first set
78319** must have P4==0, the final set P4=-1.  P4 must be either -1 or
78320** non-negative.  For non-negative values of P4 only the lower 4
78321** bits are significant.
78322**
78323** This allows optimizations: (a) when P4==0 there is no need to test
78324** the rowset object for P3, as it is guaranteed not to contain it,
78325** (b) when P4==-1 there is no need to insert the value, as it will
78326** never be tested for, and (c) when a value that is part of set X is
78327** inserted, there is no need to search to see if the same value was
78328** previously inserted as part of set X (only if it was previously
78329** inserted as part of some other set).
78330*/
78331case OP_RowSetTest: {                     /* jump, in1, in3 */
78332  int iSet;
78333  int exists;
78334
78335  pIn1 = &aMem[pOp->p1];
78336  pIn3 = &aMem[pOp->p3];
78337  iSet = pOp->p4.i;
78338  assert( pIn3->flags&MEM_Int );
78339
78340  /* If there is anything other than a rowset object in memory cell P1,
78341  ** delete it now and initialize P1 with an empty rowset
78342  */
78343  if( (pIn1->flags & MEM_RowSet)==0 ){
78344    sqlite3VdbeMemSetRowSet(pIn1);
78345    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
78346  }
78347
78348  assert( pOp->p4type==P4_INT32 );
78349  assert( iSet==-1 || iSet>=0 );
78350  if( iSet ){
78351    exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
78352    VdbeBranchTaken(exists!=0,2);
78353    if( exists ) goto jump_to_p2;
78354  }
78355  if( iSet>=0 ){
78356    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
78357  }
78358  break;
78359}
78360
78361
78362#ifndef SQLITE_OMIT_TRIGGER
78363
78364/* Opcode: Program P1 P2 P3 P4 P5
78365**
78366** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
78367**
78368** P1 contains the address of the memory cell that contains the first memory
78369** cell in an array of values used as arguments to the sub-program. P2
78370** contains the address to jump to if the sub-program throws an IGNORE
78371** exception using the RAISE() function. Register P3 contains the address
78372** of a memory cell in this (the parent) VM that is used to allocate the
78373** memory required by the sub-vdbe at runtime.
78374**
78375** P4 is a pointer to the VM containing the trigger program.
78376**
78377** If P5 is non-zero, then recursive program invocation is enabled.
78378*/
78379case OP_Program: {        /* jump */
78380  int nMem;               /* Number of memory registers for sub-program */
78381  int nByte;              /* Bytes of runtime space required for sub-program */
78382  Mem *pRt;               /* Register to allocate runtime space */
78383  Mem *pMem;              /* Used to iterate through memory cells */
78384  Mem *pEnd;              /* Last memory cell in new array */
78385  VdbeFrame *pFrame;      /* New vdbe frame to execute in */
78386  SubProgram *pProgram;   /* Sub-program to execute */
78387  void *t;                /* Token identifying trigger */
78388
78389  pProgram = pOp->p4.pProgram;
78390  pRt = &aMem[pOp->p3];
78391  assert( pProgram->nOp>0 );
78392
78393  /* If the p5 flag is clear, then recursive invocation of triggers is
78394  ** disabled for backwards compatibility (p5 is set if this sub-program
78395  ** is really a trigger, not a foreign key action, and the flag set
78396  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
78397  **
78398  ** It is recursive invocation of triggers, at the SQL level, that is
78399  ** disabled. In some cases a single trigger may generate more than one
78400  ** SubProgram (if the trigger may be executed with more than one different
78401  ** ON CONFLICT algorithm). SubProgram structures associated with a
78402  ** single trigger all have the same value for the SubProgram.token
78403  ** variable.  */
78404  if( pOp->p5 ){
78405    t = pProgram->token;
78406    for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
78407    if( pFrame ) break;
78408  }
78409
78410  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
78411    rc = SQLITE_ERROR;
78412    sqlite3VdbeError(p, "too many levels of trigger recursion");
78413    break;
78414  }
78415
78416  /* Register pRt is used to store the memory required to save the state
78417  ** of the current program, and the memory required at runtime to execute
78418  ** the trigger program. If this trigger has been fired before, then pRt
78419  ** is already allocated. Otherwise, it must be initialized.  */
78420  if( (pRt->flags&MEM_Frame)==0 ){
78421    /* SubProgram.nMem is set to the number of memory cells used by the
78422    ** program stored in SubProgram.aOp. As well as these, one memory
78423    ** cell is required for each cursor used by the program. Set local
78424    ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
78425    */
78426    nMem = pProgram->nMem + pProgram->nCsr;
78427    nByte = ROUND8(sizeof(VdbeFrame))
78428              + nMem * sizeof(Mem)
78429              + pProgram->nCsr * sizeof(VdbeCursor *)
78430              + pProgram->nOnce * sizeof(u8);
78431    pFrame = sqlite3DbMallocZero(db, nByte);
78432    if( !pFrame ){
78433      goto no_mem;
78434    }
78435    sqlite3VdbeMemRelease(pRt);
78436    pRt->flags = MEM_Frame;
78437    pRt->u.pFrame = pFrame;
78438
78439    pFrame->v = p;
78440    pFrame->nChildMem = nMem;
78441    pFrame->nChildCsr = pProgram->nCsr;
78442    pFrame->pc = (int)(pOp - aOp);
78443    pFrame->aMem = p->aMem;
78444    pFrame->nMem = p->nMem;
78445    pFrame->apCsr = p->apCsr;
78446    pFrame->nCursor = p->nCursor;
78447    pFrame->aOp = p->aOp;
78448    pFrame->nOp = p->nOp;
78449    pFrame->token = pProgram->token;
78450    pFrame->aOnceFlag = p->aOnceFlag;
78451    pFrame->nOnceFlag = p->nOnceFlag;
78452#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
78453    pFrame->anExec = p->anExec;
78454#endif
78455
78456    pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
78457    for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
78458      pMem->flags = MEM_Undefined;
78459      pMem->db = db;
78460    }
78461  }else{
78462    pFrame = pRt->u.pFrame;
78463    assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
78464    assert( pProgram->nCsr==pFrame->nChildCsr );
78465    assert( (int)(pOp - aOp)==pFrame->pc );
78466  }
78467
78468  p->nFrame++;
78469  pFrame->pParent = p->pFrame;
78470  pFrame->lastRowid = lastRowid;
78471  pFrame->nChange = p->nChange;
78472  pFrame->nDbChange = p->db->nChange;
78473  p->nChange = 0;
78474  p->pFrame = pFrame;
78475  p->aMem = aMem = &VdbeFrameMem(pFrame)[-1];
78476  p->nMem = pFrame->nChildMem;
78477  p->nCursor = (u16)pFrame->nChildCsr;
78478  p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
78479  p->aOp = aOp = pProgram->aOp;
78480  p->nOp = pProgram->nOp;
78481  p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
78482  p->nOnceFlag = pProgram->nOnce;
78483#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
78484  p->anExec = 0;
78485#endif
78486  pOp = &aOp[-1];
78487  memset(p->aOnceFlag, 0, p->nOnceFlag);
78488
78489  break;
78490}
78491
78492/* Opcode: Param P1 P2 * * *
78493**
78494** This opcode is only ever present in sub-programs called via the
78495** OP_Program instruction. Copy a value currently stored in a memory
78496** cell of the calling (parent) frame to cell P2 in the current frames
78497** address space. This is used by trigger programs to access the new.*
78498** and old.* values.
78499**
78500** The address of the cell in the parent frame is determined by adding
78501** the value of the P1 argument to the value of the P1 argument to the
78502** calling OP_Program instruction.
78503*/
78504case OP_Param: {           /* out2 */
78505  VdbeFrame *pFrame;
78506  Mem *pIn;
78507  pOut = out2Prerelease(p, pOp);
78508  pFrame = p->pFrame;
78509  pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
78510  sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
78511  break;
78512}
78513
78514#endif /* #ifndef SQLITE_OMIT_TRIGGER */
78515
78516#ifndef SQLITE_OMIT_FOREIGN_KEY
78517/* Opcode: FkCounter P1 P2 * * *
78518** Synopsis: fkctr[P1]+=P2
78519**
78520** Increment a "constraint counter" by P2 (P2 may be negative or positive).
78521** If P1 is non-zero, the database constraint counter is incremented
78522** (deferred foreign key constraints). Otherwise, if P1 is zero, the
78523** statement counter is incremented (immediate foreign key constraints).
78524*/
78525case OP_FkCounter: {
78526  if( db->flags & SQLITE_DeferFKs ){
78527    db->nDeferredImmCons += pOp->p2;
78528  }else if( pOp->p1 ){
78529    db->nDeferredCons += pOp->p2;
78530  }else{
78531    p->nFkConstraint += pOp->p2;
78532  }
78533  break;
78534}
78535
78536/* Opcode: FkIfZero P1 P2 * * *
78537** Synopsis: if fkctr[P1]==0 goto P2
78538**
78539** This opcode tests if a foreign key constraint-counter is currently zero.
78540** If so, jump to instruction P2. Otherwise, fall through to the next
78541** instruction.
78542**
78543** If P1 is non-zero, then the jump is taken if the database constraint-counter
78544** is zero (the one that counts deferred constraint violations). If P1 is
78545** zero, the jump is taken if the statement constraint-counter is zero
78546** (immediate foreign key constraint violations).
78547*/
78548case OP_FkIfZero: {         /* jump */
78549  if( pOp->p1 ){
78550    VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
78551    if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
78552  }else{
78553    VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
78554    if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
78555  }
78556  break;
78557}
78558#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
78559
78560#ifndef SQLITE_OMIT_AUTOINCREMENT
78561/* Opcode: MemMax P1 P2 * * *
78562** Synopsis: r[P1]=max(r[P1],r[P2])
78563**
78564** P1 is a register in the root frame of this VM (the root frame is
78565** different from the current frame if this instruction is being executed
78566** within a sub-program). Set the value of register P1 to the maximum of
78567** its current value and the value in register P2.
78568**
78569** This instruction throws an error if the memory cell is not initially
78570** an integer.
78571*/
78572case OP_MemMax: {        /* in2 */
78573  VdbeFrame *pFrame;
78574  if( p->pFrame ){
78575    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
78576    pIn1 = &pFrame->aMem[pOp->p1];
78577  }else{
78578    pIn1 = &aMem[pOp->p1];
78579  }
78580  assert( memIsValid(pIn1) );
78581  sqlite3VdbeMemIntegerify(pIn1);
78582  pIn2 = &aMem[pOp->p2];
78583  sqlite3VdbeMemIntegerify(pIn2);
78584  if( pIn1->u.i<pIn2->u.i){
78585    pIn1->u.i = pIn2->u.i;
78586  }
78587  break;
78588}
78589#endif /* SQLITE_OMIT_AUTOINCREMENT */
78590
78591/* Opcode: IfPos P1 P2 P3 * *
78592** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
78593**
78594** Register P1 must contain an integer.
78595** If the value of register P1 is 1 or greater, subtract P3 from the
78596** value in P1 and jump to P2.
78597**
78598** If the initial value of register P1 is less than 1, then the
78599** value is unchanged and control passes through to the next instruction.
78600*/
78601case OP_IfPos: {        /* jump, in1 */
78602  pIn1 = &aMem[pOp->p1];
78603  assert( pIn1->flags&MEM_Int );
78604  VdbeBranchTaken( pIn1->u.i>0, 2);
78605  if( pIn1->u.i>0 ){
78606    pIn1->u.i -= pOp->p3;
78607    goto jump_to_p2;
78608  }
78609  break;
78610}
78611
78612/* Opcode: SetIfNotPos P1 P2 P3 * *
78613** Synopsis: if r[P1]<=0 then r[P2]=P3
78614**
78615** Register P1 must contain an integer.
78616** If the value of register P1 is not positive (if it is less than 1) then
78617** set the value of register P2 to be the integer P3.
78618*/
78619case OP_SetIfNotPos: {        /* in1, in2 */
78620  pIn1 = &aMem[pOp->p1];
78621  assert( pIn1->flags&MEM_Int );
78622  if( pIn1->u.i<=0 ){
78623    pOut = out2Prerelease(p, pOp);
78624    pOut->u.i = pOp->p3;
78625  }
78626  break;
78627}
78628
78629/* Opcode: IfNotZero P1 P2 P3 * *
78630** Synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2
78631**
78632** Register P1 must contain an integer.  If the content of register P1 is
78633** initially nonzero, then subtract P3 from the value in register P1 and
78634** jump to P2.  If register P1 is initially zero, leave it unchanged
78635** and fall through.
78636*/
78637case OP_IfNotZero: {        /* jump, in1 */
78638  pIn1 = &aMem[pOp->p1];
78639  assert( pIn1->flags&MEM_Int );
78640  VdbeBranchTaken(pIn1->u.i<0, 2);
78641  if( pIn1->u.i ){
78642     pIn1->u.i -= pOp->p3;
78643     goto jump_to_p2;
78644  }
78645  break;
78646}
78647
78648/* Opcode: DecrJumpZero P1 P2 * * *
78649** Synopsis: if (--r[P1])==0 goto P2
78650**
78651** Register P1 must hold an integer.  Decrement the value in register P1
78652** then jump to P2 if the new value is exactly zero.
78653*/
78654case OP_DecrJumpZero: {      /* jump, in1 */
78655  pIn1 = &aMem[pOp->p1];
78656  assert( pIn1->flags&MEM_Int );
78657  pIn1->u.i--;
78658  VdbeBranchTaken(pIn1->u.i==0, 2);
78659  if( pIn1->u.i==0 ) goto jump_to_p2;
78660  break;
78661}
78662
78663
78664/* Opcode: JumpZeroIncr P1 P2 * * *
78665** Synopsis: if (r[P1]++)==0 ) goto P2
78666**
78667** The register P1 must contain an integer.  If register P1 is initially
78668** zero, then jump to P2.  Increment register P1 regardless of whether or
78669** not the jump is taken.
78670*/
78671case OP_JumpZeroIncr: {        /* jump, in1 */
78672  pIn1 = &aMem[pOp->p1];
78673  assert( pIn1->flags&MEM_Int );
78674  VdbeBranchTaken(pIn1->u.i==0, 2);
78675  if( (pIn1->u.i++)==0 ) goto jump_to_p2;
78676  break;
78677}
78678
78679/* Opcode: AggStep0 * P2 P3 P4 P5
78680** Synopsis: accum=r[P3] step(r[P2@P5])
78681**
78682** Execute the step function for an aggregate.  The
78683** function has P5 arguments.   P4 is a pointer to the FuncDef
78684** structure that specifies the function.  Register P3 is the
78685** accumulator.
78686**
78687** The P5 arguments are taken from register P2 and its
78688** successors.
78689*/
78690/* Opcode: AggStep * P2 P3 P4 P5
78691** Synopsis: accum=r[P3] step(r[P2@P5])
78692**
78693** Execute the step function for an aggregate.  The
78694** function has P5 arguments.   P4 is a pointer to an sqlite3_context
78695** object that is used to run the function.  Register P3 is
78696** as the accumulator.
78697**
78698** The P5 arguments are taken from register P2 and its
78699** successors.
78700**
78701** This opcode is initially coded as OP_AggStep0.  On first evaluation,
78702** the FuncDef stored in P4 is converted into an sqlite3_context and
78703** the opcode is changed.  In this way, the initialization of the
78704** sqlite3_context only happens once, instead of on each call to the
78705** step function.
78706*/
78707case OP_AggStep0: {
78708  int n;
78709  sqlite3_context *pCtx;
78710
78711  assert( pOp->p4type==P4_FUNCDEF );
78712  n = pOp->p5;
78713  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
78714  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
78715  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
78716  pCtx = sqlite3DbMallocRaw(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
78717  if( pCtx==0 ) goto no_mem;
78718  pCtx->pMem = 0;
78719  pCtx->pFunc = pOp->p4.pFunc;
78720  pCtx->iOp = (int)(pOp - aOp);
78721  pCtx->pVdbe = p;
78722  pCtx->argc = n;
78723  pOp->p4type = P4_FUNCCTX;
78724  pOp->p4.pCtx = pCtx;
78725  pOp->opcode = OP_AggStep;
78726  /* Fall through into OP_AggStep */
78727}
78728case OP_AggStep: {
78729  int i;
78730  sqlite3_context *pCtx;
78731  Mem *pMem;
78732  Mem t;
78733
78734  assert( pOp->p4type==P4_FUNCCTX );
78735  pCtx = pOp->p4.pCtx;
78736  pMem = &aMem[pOp->p3];
78737
78738  /* If this function is inside of a trigger, the register array in aMem[]
78739  ** might change from one evaluation to the next.  The next block of code
78740  ** checks to see if the register array has changed, and if so it
78741  ** reinitializes the relavant parts of the sqlite3_context object */
78742  if( pCtx->pMem != pMem ){
78743    pCtx->pMem = pMem;
78744    for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
78745  }
78746
78747#ifdef SQLITE_DEBUG
78748  for(i=0; i<pCtx->argc; i++){
78749    assert( memIsValid(pCtx->argv[i]) );
78750    REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
78751  }
78752#endif
78753
78754  pMem->n++;
78755  sqlite3VdbeMemInit(&t, db, MEM_Null);
78756  pCtx->pOut = &t;
78757  pCtx->fErrorOrAux = 0;
78758  pCtx->skipFlag = 0;
78759  (pCtx->pFunc->xStep)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
78760  if( pCtx->fErrorOrAux ){
78761    if( pCtx->isError ){
78762      sqlite3VdbeError(p, "%s", sqlite3_value_text(&t));
78763      rc = pCtx->isError;
78764    }
78765    sqlite3VdbeMemRelease(&t);
78766  }else{
78767    assert( t.flags==MEM_Null );
78768  }
78769  if( pCtx->skipFlag ){
78770    assert( pOp[-1].opcode==OP_CollSeq );
78771    i = pOp[-1].p1;
78772    if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
78773  }
78774  break;
78775}
78776
78777/* Opcode: AggFinal P1 P2 * P4 *
78778** Synopsis: accum=r[P1] N=P2
78779**
78780** Execute the finalizer function for an aggregate.  P1 is
78781** the memory location that is the accumulator for the aggregate.
78782**
78783** P2 is the number of arguments that the step function takes and
78784** P4 is a pointer to the FuncDef for this function.  The P2
78785** argument is not used by this opcode.  It is only there to disambiguate
78786** functions that can take varying numbers of arguments.  The
78787** P4 argument is only needed for the degenerate case where
78788** the step function was not previously called.
78789*/
78790case OP_AggFinal: {
78791  Mem *pMem;
78792  assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
78793  pMem = &aMem[pOp->p1];
78794  assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
78795  rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
78796  if( rc ){
78797    sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
78798  }
78799  sqlite3VdbeChangeEncoding(pMem, encoding);
78800  UPDATE_MAX_BLOBSIZE(pMem);
78801  if( sqlite3VdbeMemTooBig(pMem) ){
78802    goto too_big;
78803  }
78804  break;
78805}
78806
78807#ifndef SQLITE_OMIT_WAL
78808/* Opcode: Checkpoint P1 P2 P3 * *
78809**
78810** Checkpoint database P1. This is a no-op if P1 is not currently in
78811** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
78812** RESTART, or TRUNCATE.  Write 1 or 0 into mem[P3] if the checkpoint returns
78813** SQLITE_BUSY or not, respectively.  Write the number of pages in the
78814** WAL after the checkpoint into mem[P3+1] and the number of pages
78815** in the WAL that have been checkpointed after the checkpoint
78816** completes into mem[P3+2].  However on an error, mem[P3+1] and
78817** mem[P3+2] are initialized to -1.
78818*/
78819case OP_Checkpoint: {
78820  int i;                          /* Loop counter */
78821  int aRes[3];                    /* Results */
78822  Mem *pMem;                      /* Write results here */
78823
78824  assert( p->readOnly==0 );
78825  aRes[0] = 0;
78826  aRes[1] = aRes[2] = -1;
78827  assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
78828       || pOp->p2==SQLITE_CHECKPOINT_FULL
78829       || pOp->p2==SQLITE_CHECKPOINT_RESTART
78830       || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
78831  );
78832  rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
78833  if( rc==SQLITE_BUSY ){
78834    rc = SQLITE_OK;
78835    aRes[0] = 1;
78836  }
78837  for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
78838    sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
78839  }
78840  break;
78841};
78842#endif
78843
78844#ifndef SQLITE_OMIT_PRAGMA
78845/* Opcode: JournalMode P1 P2 P3 * *
78846**
78847** Change the journal mode of database P1 to P3. P3 must be one of the
78848** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
78849** modes (delete, truncate, persist, off and memory), this is a simple
78850** operation. No IO is required.
78851**
78852** If changing into or out of WAL mode the procedure is more complicated.
78853**
78854** Write a string containing the final journal-mode to register P2.
78855*/
78856case OP_JournalMode: {    /* out2 */
78857  Btree *pBt;                     /* Btree to change journal mode of */
78858  Pager *pPager;                  /* Pager associated with pBt */
78859  int eNew;                       /* New journal mode */
78860  int eOld;                       /* The old journal mode */
78861#ifndef SQLITE_OMIT_WAL
78862  const char *zFilename;          /* Name of database file for pPager */
78863#endif
78864
78865  pOut = out2Prerelease(p, pOp);
78866  eNew = pOp->p3;
78867  assert( eNew==PAGER_JOURNALMODE_DELETE
78868       || eNew==PAGER_JOURNALMODE_TRUNCATE
78869       || eNew==PAGER_JOURNALMODE_PERSIST
78870       || eNew==PAGER_JOURNALMODE_OFF
78871       || eNew==PAGER_JOURNALMODE_MEMORY
78872       || eNew==PAGER_JOURNALMODE_WAL
78873       || eNew==PAGER_JOURNALMODE_QUERY
78874  );
78875  assert( pOp->p1>=0 && pOp->p1<db->nDb );
78876  assert( p->readOnly==0 );
78877
78878  pBt = db->aDb[pOp->p1].pBt;
78879  pPager = sqlite3BtreePager(pBt);
78880  eOld = sqlite3PagerGetJournalMode(pPager);
78881  if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
78882  if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
78883
78884#ifndef SQLITE_OMIT_WAL
78885  zFilename = sqlite3PagerFilename(pPager, 1);
78886
78887  /* Do not allow a transition to journal_mode=WAL for a database
78888  ** in temporary storage or if the VFS does not support shared memory
78889  */
78890  if( eNew==PAGER_JOURNALMODE_WAL
78891   && (sqlite3Strlen30(zFilename)==0           /* Temp file */
78892       || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
78893  ){
78894    eNew = eOld;
78895  }
78896
78897  if( (eNew!=eOld)
78898   && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
78899  ){
78900    if( !db->autoCommit || db->nVdbeRead>1 ){
78901      rc = SQLITE_ERROR;
78902      sqlite3VdbeError(p,
78903          "cannot change %s wal mode from within a transaction",
78904          (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
78905      );
78906      break;
78907    }else{
78908
78909      if( eOld==PAGER_JOURNALMODE_WAL ){
78910        /* If leaving WAL mode, close the log file. If successful, the call
78911        ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
78912        ** file. An EXCLUSIVE lock may still be held on the database file
78913        ** after a successful return.
78914        */
78915        rc = sqlite3PagerCloseWal(pPager);
78916        if( rc==SQLITE_OK ){
78917          sqlite3PagerSetJournalMode(pPager, eNew);
78918        }
78919      }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
78920        /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
78921        ** as an intermediate */
78922        sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
78923      }
78924
78925      /* Open a transaction on the database file. Regardless of the journal
78926      ** mode, this transaction always uses a rollback journal.
78927      */
78928      assert( sqlite3BtreeIsInTrans(pBt)==0 );
78929      if( rc==SQLITE_OK ){
78930        rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
78931      }
78932    }
78933  }
78934#endif /* ifndef SQLITE_OMIT_WAL */
78935
78936  if( rc ){
78937    eNew = eOld;
78938  }
78939  eNew = sqlite3PagerSetJournalMode(pPager, eNew);
78940
78941  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
78942  pOut->z = (char *)sqlite3JournalModename(eNew);
78943  pOut->n = sqlite3Strlen30(pOut->z);
78944  pOut->enc = SQLITE_UTF8;
78945  sqlite3VdbeChangeEncoding(pOut, encoding);
78946  break;
78947};
78948#endif /* SQLITE_OMIT_PRAGMA */
78949
78950#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
78951/* Opcode: Vacuum * * * * *
78952**
78953** Vacuum the entire database.  This opcode will cause other virtual
78954** machines to be created and run.  It may not be called from within
78955** a transaction.
78956*/
78957case OP_Vacuum: {
78958  assert( p->readOnly==0 );
78959  rc = sqlite3RunVacuum(&p->zErrMsg, db);
78960  break;
78961}
78962#endif
78963
78964#if !defined(SQLITE_OMIT_AUTOVACUUM)
78965/* Opcode: IncrVacuum P1 P2 * * *
78966**
78967** Perform a single step of the incremental vacuum procedure on
78968** the P1 database. If the vacuum has finished, jump to instruction
78969** P2. Otherwise, fall through to the next instruction.
78970*/
78971case OP_IncrVacuum: {        /* jump */
78972  Btree *pBt;
78973
78974  assert( pOp->p1>=0 && pOp->p1<db->nDb );
78975  assert( DbMaskTest(p->btreeMask, pOp->p1) );
78976  assert( p->readOnly==0 );
78977  pBt = db->aDb[pOp->p1].pBt;
78978  rc = sqlite3BtreeIncrVacuum(pBt);
78979  VdbeBranchTaken(rc==SQLITE_DONE,2);
78980  if( rc==SQLITE_DONE ){
78981    rc = SQLITE_OK;
78982    goto jump_to_p2;
78983  }
78984  break;
78985}
78986#endif
78987
78988/* Opcode: Expire P1 * * * *
78989**
78990** Cause precompiled statements to expire.  When an expired statement
78991** is executed using sqlite3_step() it will either automatically
78992** reprepare itself (if it was originally created using sqlite3_prepare_v2())
78993** or it will fail with SQLITE_SCHEMA.
78994**
78995** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
78996** then only the currently executing statement is expired.
78997*/
78998case OP_Expire: {
78999  if( !pOp->p1 ){
79000    sqlite3ExpirePreparedStatements(db);
79001  }else{
79002    p->expired = 1;
79003  }
79004  break;
79005}
79006
79007#ifndef SQLITE_OMIT_SHARED_CACHE
79008/* Opcode: TableLock P1 P2 P3 P4 *
79009** Synopsis: iDb=P1 root=P2 write=P3
79010**
79011** Obtain a lock on a particular table. This instruction is only used when
79012** the shared-cache feature is enabled.
79013**
79014** P1 is the index of the database in sqlite3.aDb[] of the database
79015** on which the lock is acquired.  A readlock is obtained if P3==0 or
79016** a write lock if P3==1.
79017**
79018** P2 contains the root-page of the table to lock.
79019**
79020** P4 contains a pointer to the name of the table being locked. This is only
79021** used to generate an error message if the lock cannot be obtained.
79022*/
79023case OP_TableLock: {
79024  u8 isWriteLock = (u8)pOp->p3;
79025  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
79026    int p1 = pOp->p1;
79027    assert( p1>=0 && p1<db->nDb );
79028    assert( DbMaskTest(p->btreeMask, p1) );
79029    assert( isWriteLock==0 || isWriteLock==1 );
79030    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
79031    if( (rc&0xFF)==SQLITE_LOCKED ){
79032      const char *z = pOp->p4.z;
79033      sqlite3VdbeError(p, "database table is locked: %s", z);
79034    }
79035  }
79036  break;
79037}
79038#endif /* SQLITE_OMIT_SHARED_CACHE */
79039
79040#ifndef SQLITE_OMIT_VIRTUALTABLE
79041/* Opcode: VBegin * * * P4 *
79042**
79043** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
79044** xBegin method for that table.
79045**
79046** Also, whether or not P4 is set, check that this is not being called from
79047** within a callback to a virtual table xSync() method. If it is, the error
79048** code will be set to SQLITE_LOCKED.
79049*/
79050case OP_VBegin: {
79051  VTable *pVTab;
79052  pVTab = pOp->p4.pVtab;
79053  rc = sqlite3VtabBegin(db, pVTab);
79054  if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
79055  break;
79056}
79057#endif /* SQLITE_OMIT_VIRTUALTABLE */
79058
79059#ifndef SQLITE_OMIT_VIRTUALTABLE
79060/* Opcode: VCreate P1 P2 * * *
79061**
79062** P2 is a register that holds the name of a virtual table in database
79063** P1. Call the xCreate method for that table.
79064*/
79065case OP_VCreate: {
79066  Mem sMem;          /* For storing the record being decoded */
79067  const char *zTab;  /* Name of the virtual table */
79068
79069  memset(&sMem, 0, sizeof(sMem));
79070  sMem.db = db;
79071  /* Because P2 is always a static string, it is impossible for the
79072  ** sqlite3VdbeMemCopy() to fail */
79073  assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
79074  assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
79075  rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
79076  assert( rc==SQLITE_OK );
79077  zTab = (const char*)sqlite3_value_text(&sMem);
79078  assert( zTab || db->mallocFailed );
79079  if( zTab ){
79080    rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
79081  }
79082  sqlite3VdbeMemRelease(&sMem);
79083  break;
79084}
79085#endif /* SQLITE_OMIT_VIRTUALTABLE */
79086
79087#ifndef SQLITE_OMIT_VIRTUALTABLE
79088/* Opcode: VDestroy P1 * * P4 *
79089**
79090** P4 is the name of a virtual table in database P1.  Call the xDestroy method
79091** of that table.
79092*/
79093case OP_VDestroy: {
79094  db->nVDestroy++;
79095  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
79096  db->nVDestroy--;
79097  break;
79098}
79099#endif /* SQLITE_OMIT_VIRTUALTABLE */
79100
79101#ifndef SQLITE_OMIT_VIRTUALTABLE
79102/* Opcode: VOpen P1 * * P4 *
79103**
79104** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
79105** P1 is a cursor number.  This opcode opens a cursor to the virtual
79106** table and stores that cursor in P1.
79107*/
79108case OP_VOpen: {
79109  VdbeCursor *pCur;
79110  sqlite3_vtab_cursor *pVtabCursor;
79111  sqlite3_vtab *pVtab;
79112  const sqlite3_module *pModule;
79113
79114  assert( p->bIsReader );
79115  pCur = 0;
79116  pVtabCursor = 0;
79117  pVtab = pOp->p4.pVtab->pVtab;
79118  if( pVtab==0 || NEVER(pVtab->pModule==0) ){
79119    rc = SQLITE_LOCKED;
79120    break;
79121  }
79122  pModule = pVtab->pModule;
79123  rc = pModule->xOpen(pVtab, &pVtabCursor);
79124  sqlite3VtabImportErrmsg(p, pVtab);
79125  if( SQLITE_OK==rc ){
79126    /* Initialize sqlite3_vtab_cursor base class */
79127    pVtabCursor->pVtab = pVtab;
79128
79129    /* Initialize vdbe cursor object */
79130    pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
79131    if( pCur ){
79132      pCur->pVtabCursor = pVtabCursor;
79133      pVtab->nRef++;
79134    }else{
79135      assert( db->mallocFailed );
79136      pModule->xClose(pVtabCursor);
79137      goto no_mem;
79138    }
79139  }
79140  break;
79141}
79142#endif /* SQLITE_OMIT_VIRTUALTABLE */
79143
79144#ifndef SQLITE_OMIT_VIRTUALTABLE
79145/* Opcode: VFilter P1 P2 P3 P4 *
79146** Synopsis: iplan=r[P3] zplan='P4'
79147**
79148** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
79149** the filtered result set is empty.
79150**
79151** P4 is either NULL or a string that was generated by the xBestIndex
79152** method of the module.  The interpretation of the P4 string is left
79153** to the module implementation.
79154**
79155** This opcode invokes the xFilter method on the virtual table specified
79156** by P1.  The integer query plan parameter to xFilter is stored in register
79157** P3. Register P3+1 stores the argc parameter to be passed to the
79158** xFilter method. Registers P3+2..P3+1+argc are the argc
79159** additional parameters which are passed to
79160** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
79161**
79162** A jump is made to P2 if the result set after filtering would be empty.
79163*/
79164case OP_VFilter: {   /* jump */
79165  int nArg;
79166  int iQuery;
79167  const sqlite3_module *pModule;
79168  Mem *pQuery;
79169  Mem *pArgc;
79170  sqlite3_vtab_cursor *pVtabCursor;
79171  sqlite3_vtab *pVtab;
79172  VdbeCursor *pCur;
79173  int res;
79174  int i;
79175  Mem **apArg;
79176
79177  pQuery = &aMem[pOp->p3];
79178  pArgc = &pQuery[1];
79179  pCur = p->apCsr[pOp->p1];
79180  assert( memIsValid(pQuery) );
79181  REGISTER_TRACE(pOp->p3, pQuery);
79182  assert( pCur->pVtabCursor );
79183  pVtabCursor = pCur->pVtabCursor;
79184  pVtab = pVtabCursor->pVtab;
79185  pModule = pVtab->pModule;
79186
79187  /* Grab the index number and argc parameters */
79188  assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
79189  nArg = (int)pArgc->u.i;
79190  iQuery = (int)pQuery->u.i;
79191
79192  /* Invoke the xFilter method */
79193  res = 0;
79194  apArg = p->apArg;
79195  for(i = 0; i<nArg; i++){
79196    apArg[i] = &pArgc[i+1];
79197  }
79198  rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
79199  sqlite3VtabImportErrmsg(p, pVtab);
79200  if( rc==SQLITE_OK ){
79201    res = pModule->xEof(pVtabCursor);
79202  }
79203  pCur->nullRow = 0;
79204  VdbeBranchTaken(res!=0,2);
79205  if( res ) goto jump_to_p2;
79206  break;
79207}
79208#endif /* SQLITE_OMIT_VIRTUALTABLE */
79209
79210#ifndef SQLITE_OMIT_VIRTUALTABLE
79211/* Opcode: VColumn P1 P2 P3 * *
79212** Synopsis: r[P3]=vcolumn(P2)
79213**
79214** Store the value of the P2-th column of
79215** the row of the virtual-table that the
79216** P1 cursor is pointing to into register P3.
79217*/
79218case OP_VColumn: {
79219  sqlite3_vtab *pVtab;
79220  const sqlite3_module *pModule;
79221  Mem *pDest;
79222  sqlite3_context sContext;
79223
79224  VdbeCursor *pCur = p->apCsr[pOp->p1];
79225  assert( pCur->pVtabCursor );
79226  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
79227  pDest = &aMem[pOp->p3];
79228  memAboutToChange(p, pDest);
79229  if( pCur->nullRow ){
79230    sqlite3VdbeMemSetNull(pDest);
79231    break;
79232  }
79233  pVtab = pCur->pVtabCursor->pVtab;
79234  pModule = pVtab->pModule;
79235  assert( pModule->xColumn );
79236  memset(&sContext, 0, sizeof(sContext));
79237  sContext.pOut = pDest;
79238  MemSetTypeFlag(pDest, MEM_Null);
79239  rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
79240  sqlite3VtabImportErrmsg(p, pVtab);
79241  if( sContext.isError ){
79242    rc = sContext.isError;
79243  }
79244  sqlite3VdbeChangeEncoding(pDest, encoding);
79245  REGISTER_TRACE(pOp->p3, pDest);
79246  UPDATE_MAX_BLOBSIZE(pDest);
79247
79248  if( sqlite3VdbeMemTooBig(pDest) ){
79249    goto too_big;
79250  }
79251  break;
79252}
79253#endif /* SQLITE_OMIT_VIRTUALTABLE */
79254
79255#ifndef SQLITE_OMIT_VIRTUALTABLE
79256/* Opcode: VNext P1 P2 * * *
79257**
79258** Advance virtual table P1 to the next row in its result set and
79259** jump to instruction P2.  Or, if the virtual table has reached
79260** the end of its result set, then fall through to the next instruction.
79261*/
79262case OP_VNext: {   /* jump */
79263  sqlite3_vtab *pVtab;
79264  const sqlite3_module *pModule;
79265  int res;
79266  VdbeCursor *pCur;
79267
79268  res = 0;
79269  pCur = p->apCsr[pOp->p1];
79270  assert( pCur->pVtabCursor );
79271  if( pCur->nullRow ){
79272    break;
79273  }
79274  pVtab = pCur->pVtabCursor->pVtab;
79275  pModule = pVtab->pModule;
79276  assert( pModule->xNext );
79277
79278  /* Invoke the xNext() method of the module. There is no way for the
79279  ** underlying implementation to return an error if one occurs during
79280  ** xNext(). Instead, if an error occurs, true is returned (indicating that
79281  ** data is available) and the error code returned when xColumn or
79282  ** some other method is next invoked on the save virtual table cursor.
79283  */
79284  rc = pModule->xNext(pCur->pVtabCursor);
79285  sqlite3VtabImportErrmsg(p, pVtab);
79286  if( rc==SQLITE_OK ){
79287    res = pModule->xEof(pCur->pVtabCursor);
79288  }
79289  VdbeBranchTaken(!res,2);
79290  if( !res ){
79291    /* If there is data, jump to P2 */
79292    goto jump_to_p2_and_check_for_interrupt;
79293  }
79294  goto check_for_interrupt;
79295}
79296#endif /* SQLITE_OMIT_VIRTUALTABLE */
79297
79298#ifndef SQLITE_OMIT_VIRTUALTABLE
79299/* Opcode: VRename P1 * * P4 *
79300**
79301** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
79302** This opcode invokes the corresponding xRename method. The value
79303** in register P1 is passed as the zName argument to the xRename method.
79304*/
79305case OP_VRename: {
79306  sqlite3_vtab *pVtab;
79307  Mem *pName;
79308
79309  pVtab = pOp->p4.pVtab->pVtab;
79310  pName = &aMem[pOp->p1];
79311  assert( pVtab->pModule->xRename );
79312  assert( memIsValid(pName) );
79313  assert( p->readOnly==0 );
79314  REGISTER_TRACE(pOp->p1, pName);
79315  assert( pName->flags & MEM_Str );
79316  testcase( pName->enc==SQLITE_UTF8 );
79317  testcase( pName->enc==SQLITE_UTF16BE );
79318  testcase( pName->enc==SQLITE_UTF16LE );
79319  rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
79320  if( rc==SQLITE_OK ){
79321    rc = pVtab->pModule->xRename(pVtab, pName->z);
79322    sqlite3VtabImportErrmsg(p, pVtab);
79323    p->expired = 0;
79324  }
79325  break;
79326}
79327#endif
79328
79329#ifndef SQLITE_OMIT_VIRTUALTABLE
79330/* Opcode: VUpdate P1 P2 P3 P4 P5
79331** Synopsis: data=r[P3@P2]
79332**
79333** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
79334** This opcode invokes the corresponding xUpdate method. P2 values
79335** are contiguous memory cells starting at P3 to pass to the xUpdate
79336** invocation. The value in register (P3+P2-1) corresponds to the
79337** p2th element of the argv array passed to xUpdate.
79338**
79339** The xUpdate method will do a DELETE or an INSERT or both.
79340** The argv[0] element (which corresponds to memory cell P3)
79341** is the rowid of a row to delete.  If argv[0] is NULL then no
79342** deletion occurs.  The argv[1] element is the rowid of the new
79343** row.  This can be NULL to have the virtual table select the new
79344** rowid for itself.  The subsequent elements in the array are
79345** the values of columns in the new row.
79346**
79347** If P2==1 then no insert is performed.  argv[0] is the rowid of
79348** a row to delete.
79349**
79350** P1 is a boolean flag. If it is set to true and the xUpdate call
79351** is successful, then the value returned by sqlite3_last_insert_rowid()
79352** is set to the value of the rowid for the row just inserted.
79353**
79354** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
79355** apply in the case of a constraint failure on an insert or update.
79356*/
79357case OP_VUpdate: {
79358  sqlite3_vtab *pVtab;
79359  const sqlite3_module *pModule;
79360  int nArg;
79361  int i;
79362  sqlite_int64 rowid;
79363  Mem **apArg;
79364  Mem *pX;
79365
79366  assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
79367       || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
79368  );
79369  assert( p->readOnly==0 );
79370  pVtab = pOp->p4.pVtab->pVtab;
79371  if( pVtab==0 || NEVER(pVtab->pModule==0) ){
79372    rc = SQLITE_LOCKED;
79373    break;
79374  }
79375  pModule = pVtab->pModule;
79376  nArg = pOp->p2;
79377  assert( pOp->p4type==P4_VTAB );
79378  if( ALWAYS(pModule->xUpdate) ){
79379    u8 vtabOnConflict = db->vtabOnConflict;
79380    apArg = p->apArg;
79381    pX = &aMem[pOp->p3];
79382    for(i=0; i<nArg; i++){
79383      assert( memIsValid(pX) );
79384      memAboutToChange(p, pX);
79385      apArg[i] = pX;
79386      pX++;
79387    }
79388    db->vtabOnConflict = pOp->p5;
79389    rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
79390    db->vtabOnConflict = vtabOnConflict;
79391    sqlite3VtabImportErrmsg(p, pVtab);
79392    if( rc==SQLITE_OK && pOp->p1 ){
79393      assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
79394      db->lastRowid = lastRowid = rowid;
79395    }
79396    if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
79397      if( pOp->p5==OE_Ignore ){
79398        rc = SQLITE_OK;
79399      }else{
79400        p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
79401      }
79402    }else{
79403      p->nChange++;
79404    }
79405  }
79406  break;
79407}
79408#endif /* SQLITE_OMIT_VIRTUALTABLE */
79409
79410#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
79411/* Opcode: Pagecount P1 P2 * * *
79412**
79413** Write the current number of pages in database P1 to memory cell P2.
79414*/
79415case OP_Pagecount: {            /* out2 */
79416  pOut = out2Prerelease(p, pOp);
79417  pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
79418  break;
79419}
79420#endif
79421
79422
79423#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
79424/* Opcode: MaxPgcnt P1 P2 P3 * *
79425**
79426** Try to set the maximum page count for database P1 to the value in P3.
79427** Do not let the maximum page count fall below the current page count and
79428** do not change the maximum page count value if P3==0.
79429**
79430** Store the maximum page count after the change in register P2.
79431*/
79432case OP_MaxPgcnt: {            /* out2 */
79433  unsigned int newMax;
79434  Btree *pBt;
79435
79436  pOut = out2Prerelease(p, pOp);
79437  pBt = db->aDb[pOp->p1].pBt;
79438  newMax = 0;
79439  if( pOp->p3 ){
79440    newMax = sqlite3BtreeLastPage(pBt);
79441    if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
79442  }
79443  pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
79444  break;
79445}
79446#endif
79447
79448
79449/* Opcode: Init * P2 * P4 *
79450** Synopsis:  Start at P2
79451**
79452** Programs contain a single instance of this opcode as the very first
79453** opcode.
79454**
79455** If tracing is enabled (by the sqlite3_trace()) interface, then
79456** the UTF-8 string contained in P4 is emitted on the trace callback.
79457** Or if P4 is blank, use the string returned by sqlite3_sql().
79458**
79459** If P2 is not zero, jump to instruction P2.
79460*/
79461case OP_Init: {          /* jump */
79462  char *zTrace;
79463  char *z;
79464
79465#ifndef SQLITE_OMIT_TRACE
79466  if( db->xTrace
79467   && !p->doingRerun
79468   && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
79469  ){
79470    z = sqlite3VdbeExpandSql(p, zTrace);
79471    db->xTrace(db->pTraceArg, z);
79472    sqlite3DbFree(db, z);
79473  }
79474#ifdef SQLITE_USE_FCNTL_TRACE
79475  zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
79476  if( zTrace ){
79477    int i;
79478    for(i=0; i<db->nDb; i++){
79479      if( DbMaskTest(p->btreeMask, i)==0 ) continue;
79480      sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
79481    }
79482  }
79483#endif /* SQLITE_USE_FCNTL_TRACE */
79484#ifdef SQLITE_DEBUG
79485  if( (db->flags & SQLITE_SqlTrace)!=0
79486   && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
79487  ){
79488    sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
79489  }
79490#endif /* SQLITE_DEBUG */
79491#endif /* SQLITE_OMIT_TRACE */
79492  if( pOp->p2 ) goto jump_to_p2;
79493  break;
79494}
79495
79496
79497/* Opcode: Noop * * * * *
79498**
79499** Do nothing.  This instruction is often useful as a jump
79500** destination.
79501*/
79502/*
79503** The magic Explain opcode are only inserted when explain==2 (which
79504** is to say when the EXPLAIN QUERY PLAN syntax is used.)
79505** This opcode records information from the optimizer.  It is the
79506** the same as a no-op.  This opcodesnever appears in a real VM program.
79507*/
79508default: {          /* This is really OP_Noop and OP_Explain */
79509  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
79510  break;
79511}
79512
79513/*****************************************************************************
79514** The cases of the switch statement above this line should all be indented
79515** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
79516** readability.  From this point on down, the normal indentation rules are
79517** restored.
79518*****************************************************************************/
79519    }
79520
79521#ifdef VDBE_PROFILE
79522    {
79523      u64 endTime = sqlite3Hwtime();
79524      if( endTime>start ) pOrigOp->cycles += endTime - start;
79525      pOrigOp->cnt++;
79526    }
79527#endif
79528
79529    /* The following code adds nothing to the actual functionality
79530    ** of the program.  It is only here for testing and debugging.
79531    ** On the other hand, it does burn CPU cycles every time through
79532    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
79533    */
79534#ifndef NDEBUG
79535    assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
79536
79537#ifdef SQLITE_DEBUG
79538    if( db->flags & SQLITE_VdbeTrace ){
79539      if( rc!=0 ) printf("rc=%d\n",rc);
79540      if( pOrigOp->opflags & (OPFLG_OUT2) ){
79541        registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
79542      }
79543      if( pOrigOp->opflags & OPFLG_OUT3 ){
79544        registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
79545      }
79546    }
79547#endif  /* SQLITE_DEBUG */
79548#endif  /* NDEBUG */
79549  }  /* The end of the for(;;) loop the loops through opcodes */
79550
79551  /* If we reach this point, it means that execution is finished with
79552  ** an error of some kind.
79553  */
79554vdbe_error_halt:
79555  assert( rc );
79556  p->rc = rc;
79557  testcase( sqlite3GlobalConfig.xLog!=0 );
79558  sqlite3_log(rc, "statement aborts at %d: [%s] %s",
79559                   (int)(pOp - aOp), p->zSql, p->zErrMsg);
79560  sqlite3VdbeHalt(p);
79561  if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
79562  rc = SQLITE_ERROR;
79563  if( resetSchemaOnFault>0 ){
79564    sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
79565  }
79566
79567  /* This is the only way out of this procedure.  We have to
79568  ** release the mutexes on btrees that were acquired at the
79569  ** top. */
79570vdbe_return:
79571  db->lastRowid = lastRowid;
79572  testcase( nVmStep>0 );
79573  p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
79574  sqlite3VdbeLeave(p);
79575  return rc;
79576
79577  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
79578  ** is encountered.
79579  */
79580too_big:
79581  sqlite3VdbeError(p, "string or blob too big");
79582  rc = SQLITE_TOOBIG;
79583  goto vdbe_error_halt;
79584
79585  /* Jump to here if a malloc() fails.
79586  */
79587no_mem:
79588  db->mallocFailed = 1;
79589  sqlite3VdbeError(p, "out of memory");
79590  rc = SQLITE_NOMEM;
79591  goto vdbe_error_halt;
79592
79593  /* Jump to here for any other kind of fatal error.  The "rc" variable
79594  ** should hold the error number.
79595  */
79596abort_due_to_error:
79597  assert( p->zErrMsg==0 );
79598  if( db->mallocFailed ) rc = SQLITE_NOMEM;
79599  if( rc!=SQLITE_IOERR_NOMEM ){
79600    sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
79601  }
79602  goto vdbe_error_halt;
79603
79604  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
79605  ** flag.
79606  */
79607abort_due_to_interrupt:
79608  assert( db->u1.isInterrupted );
79609  rc = SQLITE_INTERRUPT;
79610  p->rc = rc;
79611  sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
79612  goto vdbe_error_halt;
79613}
79614
79615
79616/************** End of vdbe.c ************************************************/
79617/************** Begin file vdbeblob.c ****************************************/
79618/*
79619** 2007 May 1
79620**
79621** The author disclaims copyright to this source code.  In place of
79622** a legal notice, here is a blessing:
79623**
79624**    May you do good and not evil.
79625**    May you find forgiveness for yourself and forgive others.
79626**    May you share freely, never taking more than you give.
79627**
79628*************************************************************************
79629**
79630** This file contains code used to implement incremental BLOB I/O.
79631*/
79632
79633/* #include "sqliteInt.h" */
79634/* #include "vdbeInt.h" */
79635
79636#ifndef SQLITE_OMIT_INCRBLOB
79637
79638/*
79639** Valid sqlite3_blob* handles point to Incrblob structures.
79640*/
79641typedef struct Incrblob Incrblob;
79642struct Incrblob {
79643  int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
79644  int nByte;              /* Size of open blob, in bytes */
79645  int iOffset;            /* Byte offset of blob in cursor data */
79646  int iCol;               /* Table column this handle is open on */
79647  BtCursor *pCsr;         /* Cursor pointing at blob row */
79648  sqlite3_stmt *pStmt;    /* Statement holding cursor open */
79649  sqlite3 *db;            /* The associated database */
79650};
79651
79652
79653/*
79654** This function is used by both blob_open() and blob_reopen(). It seeks
79655** the b-tree cursor associated with blob handle p to point to row iRow.
79656** If successful, SQLITE_OK is returned and subsequent calls to
79657** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
79658**
79659** If an error occurs, or if the specified row does not exist or does not
79660** contain a value of type TEXT or BLOB in the column nominated when the
79661** blob handle was opened, then an error code is returned and *pzErr may
79662** be set to point to a buffer containing an error message. It is the
79663** responsibility of the caller to free the error message buffer using
79664** sqlite3DbFree().
79665**
79666** If an error does occur, then the b-tree cursor is closed. All subsequent
79667** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
79668** immediately return SQLITE_ABORT.
79669*/
79670static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
79671  int rc;                         /* Error code */
79672  char *zErr = 0;                 /* Error message */
79673  Vdbe *v = (Vdbe *)p->pStmt;
79674
79675  /* Set the value of the SQL statements only variable to integer iRow.
79676  ** This is done directly instead of using sqlite3_bind_int64() to avoid
79677  ** triggering asserts related to mutexes.
79678  */
79679  assert( v->aVar[0].flags&MEM_Int );
79680  v->aVar[0].u.i = iRow;
79681
79682  rc = sqlite3_step(p->pStmt);
79683  if( rc==SQLITE_ROW ){
79684    VdbeCursor *pC = v->apCsr[0];
79685    u32 type = pC->aType[p->iCol];
79686    if( type<12 ){
79687      zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
79688          type==0?"null": type==7?"real": "integer"
79689      );
79690      rc = SQLITE_ERROR;
79691      sqlite3_finalize(p->pStmt);
79692      p->pStmt = 0;
79693    }else{
79694      p->iOffset = pC->aType[p->iCol + pC->nField];
79695      p->nByte = sqlite3VdbeSerialTypeLen(type);
79696      p->pCsr =  pC->pCursor;
79697      sqlite3BtreeIncrblobCursor(p->pCsr);
79698    }
79699  }
79700
79701  if( rc==SQLITE_ROW ){
79702    rc = SQLITE_OK;
79703  }else if( p->pStmt ){
79704    rc = sqlite3_finalize(p->pStmt);
79705    p->pStmt = 0;
79706    if( rc==SQLITE_OK ){
79707      zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
79708      rc = SQLITE_ERROR;
79709    }else{
79710      zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
79711    }
79712  }
79713
79714  assert( rc!=SQLITE_OK || zErr==0 );
79715  assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
79716
79717  *pzErr = zErr;
79718  return rc;
79719}
79720
79721/*
79722** Open a blob handle.
79723*/
79724SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
79725  sqlite3* db,            /* The database connection */
79726  const char *zDb,        /* The attached database containing the blob */
79727  const char *zTable,     /* The table containing the blob */
79728  const char *zColumn,    /* The column containing the blob */
79729  sqlite_int64 iRow,      /* The row containing the glob */
79730  int flags,              /* True -> read/write access, false -> read-only */
79731  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
79732){
79733  int nAttempt = 0;
79734  int iCol;               /* Index of zColumn in row-record */
79735
79736  /* This VDBE program seeks a btree cursor to the identified
79737  ** db/table/row entry. The reason for using a vdbe program instead
79738  ** of writing code to use the b-tree layer directly is that the
79739  ** vdbe program will take advantage of the various transaction,
79740  ** locking and error handling infrastructure built into the vdbe.
79741  **
79742  ** After seeking the cursor, the vdbe executes an OP_ResultRow.
79743  ** Code external to the Vdbe then "borrows" the b-tree cursor and
79744  ** uses it to implement the blob_read(), blob_write() and
79745  ** blob_bytes() functions.
79746  **
79747  ** The sqlite3_blob_close() function finalizes the vdbe program,
79748  ** which closes the b-tree cursor and (possibly) commits the
79749  ** transaction.
79750  */
79751  static const int iLn = VDBE_OFFSET_LINENO(4);
79752  static const VdbeOpList openBlob[] = {
79753    /* {OP_Transaction, 0, 0, 0},  // 0: Inserted separately */
79754    {OP_TableLock, 0, 0, 0},       /* 1: Acquire a read or write lock */
79755    /* One of the following two instructions is replaced by an OP_Noop. */
79756    {OP_OpenRead, 0, 0, 0},        /* 2: Open cursor 0 for reading */
79757    {OP_OpenWrite, 0, 0, 0},       /* 3: Open cursor 0 for read/write */
79758    {OP_Variable, 1, 1, 1},        /* 4: Push the rowid to the stack */
79759    {OP_NotExists, 0, 10, 1},      /* 5: Seek the cursor */
79760    {OP_Column, 0, 0, 1},          /* 6  */
79761    {OP_ResultRow, 1, 0, 0},       /* 7  */
79762    {OP_Goto, 0, 4, 0},            /* 8  */
79763    {OP_Close, 0, 0, 0},           /* 9  */
79764    {OP_Halt, 0, 0, 0},            /* 10 */
79765  };
79766
79767  int rc = SQLITE_OK;
79768  char *zErr = 0;
79769  Table *pTab;
79770  Parse *pParse = 0;
79771  Incrblob *pBlob = 0;
79772
79773#ifdef SQLITE_ENABLE_API_ARMOR
79774  if( ppBlob==0 ){
79775    return SQLITE_MISUSE_BKPT;
79776  }
79777#endif
79778  *ppBlob = 0;
79779#ifdef SQLITE_ENABLE_API_ARMOR
79780  if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
79781    return SQLITE_MISUSE_BKPT;
79782  }
79783#endif
79784  flags = !!flags;                /* flags = (flags ? 1 : 0); */
79785
79786  sqlite3_mutex_enter(db->mutex);
79787
79788  pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
79789  if( !pBlob ) goto blob_open_out;
79790  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
79791  if( !pParse ) goto blob_open_out;
79792
79793  do {
79794    memset(pParse, 0, sizeof(Parse));
79795    pParse->db = db;
79796    sqlite3DbFree(db, zErr);
79797    zErr = 0;
79798
79799    sqlite3BtreeEnterAll(db);
79800    pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
79801    if( pTab && IsVirtual(pTab) ){
79802      pTab = 0;
79803      sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
79804    }
79805    if( pTab && !HasRowid(pTab) ){
79806      pTab = 0;
79807      sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
79808    }
79809#ifndef SQLITE_OMIT_VIEW
79810    if( pTab && pTab->pSelect ){
79811      pTab = 0;
79812      sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
79813    }
79814#endif
79815    if( !pTab ){
79816      if( pParse->zErrMsg ){
79817        sqlite3DbFree(db, zErr);
79818        zErr = pParse->zErrMsg;
79819        pParse->zErrMsg = 0;
79820      }
79821      rc = SQLITE_ERROR;
79822      sqlite3BtreeLeaveAll(db);
79823      goto blob_open_out;
79824    }
79825
79826    /* Now search pTab for the exact column. */
79827    for(iCol=0; iCol<pTab->nCol; iCol++) {
79828      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
79829        break;
79830      }
79831    }
79832    if( iCol==pTab->nCol ){
79833      sqlite3DbFree(db, zErr);
79834      zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
79835      rc = SQLITE_ERROR;
79836      sqlite3BtreeLeaveAll(db);
79837      goto blob_open_out;
79838    }
79839
79840    /* If the value is being opened for writing, check that the
79841    ** column is not indexed, and that it is not part of a foreign key.
79842    ** It is against the rules to open a column to which either of these
79843    ** descriptions applies for writing.  */
79844    if( flags ){
79845      const char *zFault = 0;
79846      Index *pIdx;
79847#ifndef SQLITE_OMIT_FOREIGN_KEY
79848      if( db->flags&SQLITE_ForeignKeys ){
79849        /* Check that the column is not part of an FK child key definition. It
79850        ** is not necessary to check if it is part of a parent key, as parent
79851        ** key columns must be indexed. The check below will pick up this
79852        ** case.  */
79853        FKey *pFKey;
79854        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
79855          int j;
79856          for(j=0; j<pFKey->nCol; j++){
79857            if( pFKey->aCol[j].iFrom==iCol ){
79858              zFault = "foreign key";
79859            }
79860          }
79861        }
79862      }
79863#endif
79864      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79865        int j;
79866        for(j=0; j<pIdx->nKeyCol; j++){
79867          /* FIXME: Be smarter about indexes that use expressions */
79868          if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
79869            zFault = "indexed";
79870          }
79871        }
79872      }
79873      if( zFault ){
79874        sqlite3DbFree(db, zErr);
79875        zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
79876        rc = SQLITE_ERROR;
79877        sqlite3BtreeLeaveAll(db);
79878        goto blob_open_out;
79879      }
79880    }
79881
79882    pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
79883    assert( pBlob->pStmt || db->mallocFailed );
79884    if( pBlob->pStmt ){
79885      Vdbe *v = (Vdbe *)pBlob->pStmt;
79886      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79887
79888
79889      sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags,
79890                           pTab->pSchema->schema_cookie,
79891                           pTab->pSchema->iGeneration);
79892      sqlite3VdbeChangeP5(v, 1);
79893      sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
79894
79895      /* Make sure a mutex is held on the table to be accessed */
79896      sqlite3VdbeUsesBtree(v, iDb);
79897
79898      /* Configure the OP_TableLock instruction */
79899#ifdef SQLITE_OMIT_SHARED_CACHE
79900      sqlite3VdbeChangeToNoop(v, 1);
79901#else
79902      sqlite3VdbeChangeP1(v, 1, iDb);
79903      sqlite3VdbeChangeP2(v, 1, pTab->tnum);
79904      sqlite3VdbeChangeP3(v, 1, flags);
79905      sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
79906#endif
79907
79908      /* Remove either the OP_OpenWrite or OpenRead. Set the P2
79909      ** parameter of the other to pTab->tnum.  */
79910      sqlite3VdbeChangeToNoop(v, 3 - flags);
79911      sqlite3VdbeChangeP2(v, 2 + flags, pTab->tnum);
79912      sqlite3VdbeChangeP3(v, 2 + flags, iDb);
79913
79914      /* Configure the number of columns. Configure the cursor to
79915      ** think that the table has one more column than it really
79916      ** does. An OP_Column to retrieve this imaginary column will
79917      ** always return an SQL NULL. This is useful because it means
79918      ** we can invoke OP_Column to fill in the vdbe cursors type
79919      ** and offset cache without causing any IO.
79920      */
79921      sqlite3VdbeChangeP4(v, 2+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
79922      sqlite3VdbeChangeP2(v, 6, pTab->nCol);
79923      if( !db->mallocFailed ){
79924        pParse->nVar = 1;
79925        pParse->nMem = 1;
79926        pParse->nTab = 1;
79927        sqlite3VdbeMakeReady(v, pParse);
79928      }
79929    }
79930
79931    pBlob->flags = flags;
79932    pBlob->iCol = iCol;
79933    pBlob->db = db;
79934    sqlite3BtreeLeaveAll(db);
79935    if( db->mallocFailed ){
79936      goto blob_open_out;
79937    }
79938    sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
79939    rc = blobSeekToRow(pBlob, iRow, &zErr);
79940  } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
79941
79942blob_open_out:
79943  if( rc==SQLITE_OK && db->mallocFailed==0 ){
79944    *ppBlob = (sqlite3_blob *)pBlob;
79945  }else{
79946    if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
79947    sqlite3DbFree(db, pBlob);
79948  }
79949  sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
79950  sqlite3DbFree(db, zErr);
79951  sqlite3ParserReset(pParse);
79952  sqlite3StackFree(db, pParse);
79953  rc = sqlite3ApiExit(db, rc);
79954  sqlite3_mutex_leave(db->mutex);
79955  return rc;
79956}
79957
79958/*
79959** Close a blob handle that was previously created using
79960** sqlite3_blob_open().
79961*/
79962SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *pBlob){
79963  Incrblob *p = (Incrblob *)pBlob;
79964  int rc;
79965  sqlite3 *db;
79966
79967  if( p ){
79968    db = p->db;
79969    sqlite3_mutex_enter(db->mutex);
79970    rc = sqlite3_finalize(p->pStmt);
79971    sqlite3DbFree(db, p);
79972    sqlite3_mutex_leave(db->mutex);
79973  }else{
79974    rc = SQLITE_OK;
79975  }
79976  return rc;
79977}
79978
79979/*
79980** Perform a read or write operation on a blob
79981*/
79982static int blobReadWrite(
79983  sqlite3_blob *pBlob,
79984  void *z,
79985  int n,
79986  int iOffset,
79987  int (*xCall)(BtCursor*, u32, u32, void*)
79988){
79989  int rc;
79990  Incrblob *p = (Incrblob *)pBlob;
79991  Vdbe *v;
79992  sqlite3 *db;
79993
79994  if( p==0 ) return SQLITE_MISUSE_BKPT;
79995  db = p->db;
79996  sqlite3_mutex_enter(db->mutex);
79997  v = (Vdbe*)p->pStmt;
79998
79999  if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
80000    /* Request is out of range. Return a transient error. */
80001    rc = SQLITE_ERROR;
80002  }else if( v==0 ){
80003    /* If there is no statement handle, then the blob-handle has
80004    ** already been invalidated. Return SQLITE_ABORT in this case.
80005    */
80006    rc = SQLITE_ABORT;
80007  }else{
80008    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
80009    ** returned, clean-up the statement handle.
80010    */
80011    assert( db == v->db );
80012    sqlite3BtreeEnterCursor(p->pCsr);
80013    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
80014    sqlite3BtreeLeaveCursor(p->pCsr);
80015    if( rc==SQLITE_ABORT ){
80016      sqlite3VdbeFinalize(v);
80017      p->pStmt = 0;
80018    }else{
80019      v->rc = rc;
80020    }
80021  }
80022  sqlite3Error(db, rc);
80023  rc = sqlite3ApiExit(db, rc);
80024  sqlite3_mutex_leave(db->mutex);
80025  return rc;
80026}
80027
80028/*
80029** Read data from a blob handle.
80030*/
80031SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
80032  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
80033}
80034
80035/*
80036** Write data to a blob handle.
80037*/
80038SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
80039  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
80040}
80041
80042/*
80043** Query a blob handle for the size of the data.
80044**
80045** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
80046** so no mutex is required for access.
80047*/
80048SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *pBlob){
80049  Incrblob *p = (Incrblob *)pBlob;
80050  return (p && p->pStmt) ? p->nByte : 0;
80051}
80052
80053/*
80054** Move an existing blob handle to point to a different row of the same
80055** database table.
80056**
80057** If an error occurs, or if the specified row does not exist or does not
80058** contain a blob or text value, then an error code is returned and the
80059** database handle error code and message set. If this happens, then all
80060** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
80061** immediately return SQLITE_ABORT.
80062*/
80063SQLITE_API int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
80064  int rc;
80065  Incrblob *p = (Incrblob *)pBlob;
80066  sqlite3 *db;
80067
80068  if( p==0 ) return SQLITE_MISUSE_BKPT;
80069  db = p->db;
80070  sqlite3_mutex_enter(db->mutex);
80071
80072  if( p->pStmt==0 ){
80073    /* If there is no statement handle, then the blob-handle has
80074    ** already been invalidated. Return SQLITE_ABORT in this case.
80075    */
80076    rc = SQLITE_ABORT;
80077  }else{
80078    char *zErr;
80079    rc = blobSeekToRow(p, iRow, &zErr);
80080    if( rc!=SQLITE_OK ){
80081      sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
80082      sqlite3DbFree(db, zErr);
80083    }
80084    assert( rc!=SQLITE_SCHEMA );
80085  }
80086
80087  rc = sqlite3ApiExit(db, rc);
80088  assert( rc==SQLITE_OK || p->pStmt==0 );
80089  sqlite3_mutex_leave(db->mutex);
80090  return rc;
80091}
80092
80093#endif /* #ifndef SQLITE_OMIT_INCRBLOB */
80094
80095/************** End of vdbeblob.c ********************************************/
80096/************** Begin file vdbesort.c ****************************************/
80097/*
80098** 2011-07-09
80099**
80100** The author disclaims copyright to this source code.  In place of
80101** a legal notice, here is a blessing:
80102**
80103**    May you do good and not evil.
80104**    May you find forgiveness for yourself and forgive others.
80105**    May you share freely, never taking more than you give.
80106**
80107*************************************************************************
80108** This file contains code for the VdbeSorter object, used in concert with
80109** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
80110** or by SELECT statements with ORDER BY clauses that cannot be satisfied
80111** using indexes and without LIMIT clauses.
80112**
80113** The VdbeSorter object implements a multi-threaded external merge sort
80114** algorithm that is efficient even if the number of elements being sorted
80115** exceeds the available memory.
80116**
80117** Here is the (internal, non-API) interface between this module and the
80118** rest of the SQLite system:
80119**
80120**    sqlite3VdbeSorterInit()       Create a new VdbeSorter object.
80121**
80122**    sqlite3VdbeSorterWrite()      Add a single new row to the VdbeSorter
80123**                                  object.  The row is a binary blob in the
80124**                                  OP_MakeRecord format that contains both
80125**                                  the ORDER BY key columns and result columns
80126**                                  in the case of a SELECT w/ ORDER BY, or
80127**                                  the complete record for an index entry
80128**                                  in the case of a CREATE INDEX.
80129**
80130**    sqlite3VdbeSorterRewind()     Sort all content previously added.
80131**                                  Position the read cursor on the
80132**                                  first sorted element.
80133**
80134**    sqlite3VdbeSorterNext()       Advance the read cursor to the next sorted
80135**                                  element.
80136**
80137**    sqlite3VdbeSorterRowkey()     Return the complete binary blob for the
80138**                                  row currently under the read cursor.
80139**
80140**    sqlite3VdbeSorterCompare()    Compare the binary blob for the row
80141**                                  currently under the read cursor against
80142**                                  another binary blob X and report if
80143**                                  X is strictly less than the read cursor.
80144**                                  Used to enforce uniqueness in a
80145**                                  CREATE UNIQUE INDEX statement.
80146**
80147**    sqlite3VdbeSorterClose()      Close the VdbeSorter object and reclaim
80148**                                  all resources.
80149**
80150**    sqlite3VdbeSorterReset()      Refurbish the VdbeSorter for reuse.  This
80151**                                  is like Close() followed by Init() only
80152**                                  much faster.
80153**
80154** The interfaces above must be called in a particular order.  Write() can
80155** only occur in between Init()/Reset() and Rewind().  Next(), Rowkey(), and
80156** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
80157**
80158**   Init()
80159**   for each record: Write()
80160**   Rewind()
80161**     Rowkey()/Compare()
80162**   Next()
80163**   Close()
80164**
80165** Algorithm:
80166**
80167** Records passed to the sorter via calls to Write() are initially held
80168** unsorted in main memory. Assuming the amount of memory used never exceeds
80169** a threshold, when Rewind() is called the set of records is sorted using
80170** an in-memory merge sort. In this case, no temporary files are required
80171** and subsequent calls to Rowkey(), Next() and Compare() read records
80172** directly from main memory.
80173**
80174** If the amount of space used to store records in main memory exceeds the
80175** threshold, then the set of records currently in memory are sorted and
80176** written to a temporary file in "Packed Memory Array" (PMA) format.
80177** A PMA created at this point is known as a "level-0 PMA". Higher levels
80178** of PMAs may be created by merging existing PMAs together - for example
80179** merging two or more level-0 PMAs together creates a level-1 PMA.
80180**
80181** The threshold for the amount of main memory to use before flushing
80182** records to a PMA is roughly the same as the limit configured for the
80183** page-cache of the main database. Specifically, the threshold is set to
80184** the value returned by "PRAGMA main.page_size" multipled by
80185** that returned by "PRAGMA main.cache_size", in bytes.
80186**
80187** If the sorter is running in single-threaded mode, then all PMAs generated
80188** are appended to a single temporary file. Or, if the sorter is running in
80189** multi-threaded mode then up to (N+1) temporary files may be opened, where
80190** N is the configured number of worker threads. In this case, instead of
80191** sorting the records and writing the PMA to a temporary file itself, the
80192** calling thread usually launches a worker thread to do so. Except, if
80193** there are already N worker threads running, the main thread does the work
80194** itself.
80195**
80196** The sorter is running in multi-threaded mode if (a) the library was built
80197** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
80198** than zero, and (b) worker threads have been enabled at runtime by calling
80199** "PRAGMA threads=N" with some value of N greater than 0.
80200**
80201** When Rewind() is called, any data remaining in memory is flushed to a
80202** final PMA. So at this point the data is stored in some number of sorted
80203** PMAs within temporary files on disk.
80204**
80205** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
80206** sorter is running in single-threaded mode, then these PMAs are merged
80207** incrementally as keys are retreived from the sorter by the VDBE.  The
80208** MergeEngine object, described in further detail below, performs this
80209** merge.
80210**
80211** Or, if running in multi-threaded mode, then a background thread is
80212** launched to merge the existing PMAs. Once the background thread has
80213** merged T bytes of data into a single sorted PMA, the main thread
80214** begins reading keys from that PMA while the background thread proceeds
80215** with merging the next T bytes of data. And so on.
80216**
80217** Parameter T is set to half the value of the memory threshold used
80218** by Write() above to determine when to create a new PMA.
80219**
80220** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
80221** Rewind() is called, then a hierarchy of incremental-merges is used.
80222** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
80223** disk are merged together. Then T bytes of data from the second set, and
80224** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
80225** PMAs at a time. This done is to improve locality.
80226**
80227** If running in multi-threaded mode and there are more than
80228** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
80229** than one background thread may be created. Specifically, there may be
80230** one background thread for each temporary file on disk, and one background
80231** thread to merge the output of each of the others to a single PMA for
80232** the main thread to read from.
80233*/
80234/* #include "sqliteInt.h" */
80235/* #include "vdbeInt.h" */
80236
80237/*
80238** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
80239** messages to stderr that may be helpful in understanding the performance
80240** characteristics of the sorter in multi-threaded mode.
80241*/
80242#if 0
80243# define SQLITE_DEBUG_SORTER_THREADS 1
80244#endif
80245
80246/*
80247** Hard-coded maximum amount of data to accumulate in memory before flushing
80248** to a level 0 PMA. The purpose of this limit is to prevent various integer
80249** overflows. 512MiB.
80250*/
80251#define SQLITE_MAX_PMASZ    (1<<29)
80252
80253/*
80254** Private objects used by the sorter
80255*/
80256typedef struct MergeEngine MergeEngine;     /* Merge PMAs together */
80257typedef struct PmaReader PmaReader;         /* Incrementally read one PMA */
80258typedef struct PmaWriter PmaWriter;         /* Incrementally write one PMA */
80259typedef struct SorterRecord SorterRecord;   /* A record being sorted */
80260typedef struct SortSubtask SortSubtask;     /* A sub-task in the sort process */
80261typedef struct SorterFile SorterFile;       /* Temporary file object wrapper */
80262typedef struct SorterList SorterList;       /* In-memory list of records */
80263typedef struct IncrMerger IncrMerger;       /* Read & merge multiple PMAs */
80264
80265/*
80266** A container for a temp file handle and the current amount of data
80267** stored in the file.
80268*/
80269struct SorterFile {
80270  sqlite3_file *pFd;              /* File handle */
80271  i64 iEof;                       /* Bytes of data stored in pFd */
80272};
80273
80274/*
80275** An in-memory list of objects to be sorted.
80276**
80277** If aMemory==0 then each object is allocated separately and the objects
80278** are connected using SorterRecord.u.pNext.  If aMemory!=0 then all objects
80279** are stored in the aMemory[] bulk memory, one right after the other, and
80280** are connected using SorterRecord.u.iNext.
80281*/
80282struct SorterList {
80283  SorterRecord *pList;            /* Linked list of records */
80284  u8 *aMemory;                    /* If non-NULL, bulk memory to hold pList */
80285  int szPMA;                      /* Size of pList as PMA in bytes */
80286};
80287
80288/*
80289** The MergeEngine object is used to combine two or more smaller PMAs into
80290** one big PMA using a merge operation.  Separate PMAs all need to be
80291** combined into one big PMA in order to be able to step through the sorted
80292** records in order.
80293**
80294** The aReadr[] array contains a PmaReader object for each of the PMAs being
80295** merged.  An aReadr[] object either points to a valid key or else is at EOF.
80296** ("EOF" means "End Of File".  When aReadr[] is at EOF there is no more data.)
80297** For the purposes of the paragraphs below, we assume that the array is
80298** actually N elements in size, where N is the smallest power of 2 greater
80299** to or equal to the number of PMAs being merged. The extra aReadr[] elements
80300** are treated as if they are empty (always at EOF).
80301**
80302** The aTree[] array is also N elements in size. The value of N is stored in
80303** the MergeEngine.nTree variable.
80304**
80305** The final (N/2) elements of aTree[] contain the results of comparing
80306** pairs of PMA keys together. Element i contains the result of
80307** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
80308** aTree element is set to the index of it.
80309**
80310** For the purposes of this comparison, EOF is considered greater than any
80311** other key value. If the keys are equal (only possible with two EOF
80312** values), it doesn't matter which index is stored.
80313**
80314** The (N/4) elements of aTree[] that precede the final (N/2) described
80315** above contains the index of the smallest of each block of 4 PmaReaders
80316** And so on. So that aTree[1] contains the index of the PmaReader that
80317** currently points to the smallest key value. aTree[0] is unused.
80318**
80319** Example:
80320**
80321**     aReadr[0] -> Banana
80322**     aReadr[1] -> Feijoa
80323**     aReadr[2] -> Elderberry
80324**     aReadr[3] -> Currant
80325**     aReadr[4] -> Grapefruit
80326**     aReadr[5] -> Apple
80327**     aReadr[6] -> Durian
80328**     aReadr[7] -> EOF
80329**
80330**     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
80331**
80332** The current element is "Apple" (the value of the key indicated by
80333** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
80334** be advanced to the next key in its segment. Say the next key is
80335** "Eggplant":
80336**
80337**     aReadr[5] -> Eggplant
80338**
80339** The contents of aTree[] are updated first by comparing the new PmaReader
80340** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
80341** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
80342** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
80343** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
80344** so the value written into element 1 of the array is 0. As follows:
80345**
80346**     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
80347**
80348** In other words, each time we advance to the next sorter element, log2(N)
80349** key comparison operations are required, where N is the number of segments
80350** being merged (rounded up to the next power of 2).
80351*/
80352struct MergeEngine {
80353  int nTree;                 /* Used size of aTree/aReadr (power of 2) */
80354  SortSubtask *pTask;        /* Used by this thread only */
80355  int *aTree;                /* Current state of incremental merge */
80356  PmaReader *aReadr;         /* Array of PmaReaders to merge data from */
80357};
80358
80359/*
80360** This object represents a single thread of control in a sort operation.
80361** Exactly VdbeSorter.nTask instances of this object are allocated
80362** as part of each VdbeSorter object. Instances are never allocated any
80363** other way. VdbeSorter.nTask is set to the number of worker threads allowed
80364** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread).  Thus for
80365** single-threaded operation, there is exactly one instance of this object
80366** and for multi-threaded operation there are two or more instances.
80367**
80368** Essentially, this structure contains all those fields of the VdbeSorter
80369** structure for which each thread requires a separate instance. For example,
80370** each thread requries its own UnpackedRecord object to unpack records in
80371** as part of comparison operations.
80372**
80373** Before a background thread is launched, variable bDone is set to 0. Then,
80374** right before it exits, the thread itself sets bDone to 1. This is used for
80375** two purposes:
80376**
80377**   1. When flushing the contents of memory to a level-0 PMA on disk, to
80378**      attempt to select a SortSubtask for which there is not already an
80379**      active background thread (since doing so causes the main thread
80380**      to block until it finishes).
80381**
80382**   2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
80383**      to sqlite3ThreadJoin() is likely to block. Cases that are likely to
80384**      block provoke debugging output.
80385**
80386** In both cases, the effects of the main thread seeing (bDone==0) even
80387** after the thread has finished are not dire. So we don't worry about
80388** memory barriers and such here.
80389*/
80390typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
80391struct SortSubtask {
80392  SQLiteThread *pThread;          /* Background thread, if any */
80393  int bDone;                      /* Set if thread is finished but not joined */
80394  VdbeSorter *pSorter;            /* Sorter that owns this sub-task */
80395  UnpackedRecord *pUnpacked;      /* Space to unpack a record */
80396  SorterList list;                /* List for thread to write to a PMA */
80397  int nPMA;                       /* Number of PMAs currently in file */
80398  SorterCompare xCompare;         /* Compare function to use */
80399  SorterFile file;                /* Temp file for level-0 PMAs */
80400  SorterFile file2;               /* Space for other PMAs */
80401};
80402
80403
80404/*
80405** Main sorter structure. A single instance of this is allocated for each
80406** sorter cursor created by the VDBE.
80407**
80408** mxKeysize:
80409**   As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
80410**   this variable is updated so as to be set to the size on disk of the
80411**   largest record in the sorter.
80412*/
80413struct VdbeSorter {
80414  int mnPmaSize;                  /* Minimum PMA size, in bytes */
80415  int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
80416  int mxKeysize;                  /* Largest serialized key seen so far */
80417  int pgsz;                       /* Main database page size */
80418  PmaReader *pReader;             /* Readr data from here after Rewind() */
80419  MergeEngine *pMerger;           /* Or here, if bUseThreads==0 */
80420  sqlite3 *db;                    /* Database connection */
80421  KeyInfo *pKeyInfo;              /* How to compare records */
80422  UnpackedRecord *pUnpacked;      /* Used by VdbeSorterCompare() */
80423  SorterList list;                /* List of in-memory records */
80424  int iMemory;                    /* Offset of free space in list.aMemory */
80425  int nMemory;                    /* Size of list.aMemory allocation in bytes */
80426  u8 bUsePMA;                     /* True if one or more PMAs created */
80427  u8 bUseThreads;                 /* True to use background threads */
80428  u8 iPrev;                       /* Previous thread used to flush PMA */
80429  u8 nTask;                       /* Size of aTask[] array */
80430  u8 typeMask;
80431  SortSubtask aTask[1];           /* One or more subtasks */
80432};
80433
80434#define SORTER_TYPE_INTEGER 0x01
80435#define SORTER_TYPE_TEXT    0x02
80436
80437/*
80438** An instance of the following object is used to read records out of a
80439** PMA, in sorted order.  The next key to be read is cached in nKey/aKey.
80440** aKey might point into aMap or into aBuffer.  If neither of those locations
80441** contain a contiguous representation of the key, then aAlloc is allocated
80442** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
80443**
80444** pFd==0 at EOF.
80445*/
80446struct PmaReader {
80447  i64 iReadOff;               /* Current read offset */
80448  i64 iEof;                   /* 1 byte past EOF for this PmaReader */
80449  int nAlloc;                 /* Bytes of space at aAlloc */
80450  int nKey;                   /* Number of bytes in key */
80451  sqlite3_file *pFd;          /* File handle we are reading from */
80452  u8 *aAlloc;                 /* Space for aKey if aBuffer and pMap wont work */
80453  u8 *aKey;                   /* Pointer to current key */
80454  u8 *aBuffer;                /* Current read buffer */
80455  int nBuffer;                /* Size of read buffer in bytes */
80456  u8 *aMap;                   /* Pointer to mapping of entire file */
80457  IncrMerger *pIncr;          /* Incremental merger */
80458};
80459
80460/*
80461** Normally, a PmaReader object iterates through an existing PMA stored
80462** within a temp file. However, if the PmaReader.pIncr variable points to
80463** an object of the following type, it may be used to iterate/merge through
80464** multiple PMAs simultaneously.
80465**
80466** There are two types of IncrMerger object - single (bUseThread==0) and
80467** multi-threaded (bUseThread==1).
80468**
80469** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
80470** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
80471** size. When the IncrMerger is initialized, it reads enough data from
80472** pMerger to populate aFile[0]. It then sets variables within the
80473** corresponding PmaReader object to read from that file and kicks off
80474** a background thread to populate aFile[1] with the next mxSz bytes of
80475** sorted record data from pMerger.
80476**
80477** When the PmaReader reaches the end of aFile[0], it blocks until the
80478** background thread has finished populating aFile[1]. It then exchanges
80479** the contents of the aFile[0] and aFile[1] variables within this structure,
80480** sets the PmaReader fields to read from the new aFile[0] and kicks off
80481** another background thread to populate the new aFile[1]. And so on, until
80482** the contents of pMerger are exhausted.
80483**
80484** A single-threaded IncrMerger does not open any temporary files of its
80485** own. Instead, it has exclusive access to mxSz bytes of space beginning
80486** at offset iStartOff of file pTask->file2. And instead of using a
80487** background thread to prepare data for the PmaReader, with a single
80488** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
80489** keys from pMerger by the calling thread whenever the PmaReader runs out
80490** of data.
80491*/
80492struct IncrMerger {
80493  SortSubtask *pTask;             /* Task that owns this merger */
80494  MergeEngine *pMerger;           /* Merge engine thread reads data from */
80495  i64 iStartOff;                  /* Offset to start writing file at */
80496  int mxSz;                       /* Maximum bytes of data to store */
80497  int bEof;                       /* Set to true when merge is finished */
80498  int bUseThread;                 /* True to use a bg thread for this object */
80499  SorterFile aFile[2];            /* aFile[0] for reading, [1] for writing */
80500};
80501
80502/*
80503** An instance of this object is used for writing a PMA.
80504**
80505** The PMA is written one record at a time.  Each record is of an arbitrary
80506** size.  But I/O is more efficient if it occurs in page-sized blocks where
80507** each block is aligned on a page boundary.  This object caches writes to
80508** the PMA so that aligned, page-size blocks are written.
80509*/
80510struct PmaWriter {
80511  int eFWErr;                     /* Non-zero if in an error state */
80512  u8 *aBuffer;                    /* Pointer to write buffer */
80513  int nBuffer;                    /* Size of write buffer in bytes */
80514  int iBufStart;                  /* First byte of buffer to write */
80515  int iBufEnd;                    /* Last byte of buffer to write */
80516  i64 iWriteOff;                  /* Offset of start of buffer in file */
80517  sqlite3_file *pFd;              /* File handle to write to */
80518};
80519
80520/*
80521** This object is the header on a single record while that record is being
80522** held in memory and prior to being written out as part of a PMA.
80523**
80524** How the linked list is connected depends on how memory is being managed
80525** by this module. If using a separate allocation for each in-memory record
80526** (VdbeSorter.list.aMemory==0), then the list is always connected using the
80527** SorterRecord.u.pNext pointers.
80528**
80529** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
80530** then while records are being accumulated the list is linked using the
80531** SorterRecord.u.iNext offset. This is because the aMemory[] array may
80532** be sqlite3Realloc()ed while records are being accumulated. Once the VM
80533** has finished passing records to the sorter, or when the in-memory buffer
80534** is full, the list is sorted. As part of the sorting process, it is
80535** converted to use the SorterRecord.u.pNext pointers. See function
80536** vdbeSorterSort() for details.
80537*/
80538struct SorterRecord {
80539  int nVal;                       /* Size of the record in bytes */
80540  union {
80541    SorterRecord *pNext;          /* Pointer to next record in list */
80542    int iNext;                    /* Offset within aMemory of next record */
80543  } u;
80544  /* The data for the record immediately follows this header */
80545};
80546
80547/* Return a pointer to the buffer containing the record data for SorterRecord
80548** object p. Should be used as if:
80549**
80550**   void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
80551*/
80552#define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
80553
80554
80555/* Maximum number of PMAs that a single MergeEngine can merge */
80556#define SORTER_MAX_MERGE_COUNT 16
80557
80558static int vdbeIncrSwap(IncrMerger*);
80559static void vdbeIncrFree(IncrMerger *);
80560
80561/*
80562** Free all memory belonging to the PmaReader object passed as the
80563** argument. All structure fields are set to zero before returning.
80564*/
80565static void vdbePmaReaderClear(PmaReader *pReadr){
80566  sqlite3_free(pReadr->aAlloc);
80567  sqlite3_free(pReadr->aBuffer);
80568  if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
80569  vdbeIncrFree(pReadr->pIncr);
80570  memset(pReadr, 0, sizeof(PmaReader));
80571}
80572
80573/*
80574** Read the next nByte bytes of data from the PMA p.
80575** If successful, set *ppOut to point to a buffer containing the data
80576** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
80577** error code.
80578**
80579** The buffer returned in *ppOut is only valid until the
80580** next call to this function.
80581*/
80582static int vdbePmaReadBlob(
80583  PmaReader *p,                   /* PmaReader from which to take the blob */
80584  int nByte,                      /* Bytes of data to read */
80585  u8 **ppOut                      /* OUT: Pointer to buffer containing data */
80586){
80587  int iBuf;                       /* Offset within buffer to read from */
80588  int nAvail;                     /* Bytes of data available in buffer */
80589
80590  if( p->aMap ){
80591    *ppOut = &p->aMap[p->iReadOff];
80592    p->iReadOff += nByte;
80593    return SQLITE_OK;
80594  }
80595
80596  assert( p->aBuffer );
80597
80598  /* If there is no more data to be read from the buffer, read the next
80599  ** p->nBuffer bytes of data from the file into it. Or, if there are less
80600  ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
80601  iBuf = p->iReadOff % p->nBuffer;
80602  if( iBuf==0 ){
80603    int nRead;                    /* Bytes to read from disk */
80604    int rc;                       /* sqlite3OsRead() return code */
80605
80606    /* Determine how many bytes of data to read. */
80607    if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
80608      nRead = p->nBuffer;
80609    }else{
80610      nRead = (int)(p->iEof - p->iReadOff);
80611    }
80612    assert( nRead>0 );
80613
80614    /* Readr data from the file. Return early if an error occurs. */
80615    rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
80616    assert( rc!=SQLITE_IOERR_SHORT_READ );
80617    if( rc!=SQLITE_OK ) return rc;
80618  }
80619  nAvail = p->nBuffer - iBuf;
80620
80621  if( nByte<=nAvail ){
80622    /* The requested data is available in the in-memory buffer. In this
80623    ** case there is no need to make a copy of the data, just return a
80624    ** pointer into the buffer to the caller.  */
80625    *ppOut = &p->aBuffer[iBuf];
80626    p->iReadOff += nByte;
80627  }else{
80628    /* The requested data is not all available in the in-memory buffer.
80629    ** In this case, allocate space at p->aAlloc[] to copy the requested
80630    ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
80631    int nRem;                     /* Bytes remaining to copy */
80632
80633    /* Extend the p->aAlloc[] allocation if required. */
80634    if( p->nAlloc<nByte ){
80635      u8 *aNew;
80636      int nNew = MAX(128, p->nAlloc*2);
80637      while( nByte>nNew ) nNew = nNew*2;
80638      aNew = sqlite3Realloc(p->aAlloc, nNew);
80639      if( !aNew ) return SQLITE_NOMEM;
80640      p->nAlloc = nNew;
80641      p->aAlloc = aNew;
80642    }
80643
80644    /* Copy as much data as is available in the buffer into the start of
80645    ** p->aAlloc[].  */
80646    memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
80647    p->iReadOff += nAvail;
80648    nRem = nByte - nAvail;
80649
80650    /* The following loop copies up to p->nBuffer bytes per iteration into
80651    ** the p->aAlloc[] buffer.  */
80652    while( nRem>0 ){
80653      int rc;                     /* vdbePmaReadBlob() return code */
80654      int nCopy;                  /* Number of bytes to copy */
80655      u8 *aNext;                  /* Pointer to buffer to copy data from */
80656
80657      nCopy = nRem;
80658      if( nRem>p->nBuffer ) nCopy = p->nBuffer;
80659      rc = vdbePmaReadBlob(p, nCopy, &aNext);
80660      if( rc!=SQLITE_OK ) return rc;
80661      assert( aNext!=p->aAlloc );
80662      memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
80663      nRem -= nCopy;
80664    }
80665
80666    *ppOut = p->aAlloc;
80667  }
80668
80669  return SQLITE_OK;
80670}
80671
80672/*
80673** Read a varint from the stream of data accessed by p. Set *pnOut to
80674** the value read.
80675*/
80676static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
80677  int iBuf;
80678
80679  if( p->aMap ){
80680    p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
80681  }else{
80682    iBuf = p->iReadOff % p->nBuffer;
80683    if( iBuf && (p->nBuffer-iBuf)>=9 ){
80684      p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
80685    }else{
80686      u8 aVarint[16], *a;
80687      int i = 0, rc;
80688      do{
80689        rc = vdbePmaReadBlob(p, 1, &a);
80690        if( rc ) return rc;
80691        aVarint[(i++)&0xf] = a[0];
80692      }while( (a[0]&0x80)!=0 );
80693      sqlite3GetVarint(aVarint, pnOut);
80694    }
80695  }
80696
80697  return SQLITE_OK;
80698}
80699
80700/*
80701** Attempt to memory map file pFile. If successful, set *pp to point to the
80702** new mapping and return SQLITE_OK. If the mapping is not attempted
80703** (because the file is too large or the VFS layer is configured not to use
80704** mmap), return SQLITE_OK and set *pp to NULL.
80705**
80706** Or, if an error occurs, return an SQLite error code. The final value of
80707** *pp is undefined in this case.
80708*/
80709static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
80710  int rc = SQLITE_OK;
80711  if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
80712    sqlite3_file *pFd = pFile->pFd;
80713    if( pFd->pMethods->iVersion>=3 ){
80714      rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
80715      testcase( rc!=SQLITE_OK );
80716    }
80717  }
80718  return rc;
80719}
80720
80721/*
80722** Attach PmaReader pReadr to file pFile (if it is not already attached to
80723** that file) and seek it to offset iOff within the file.  Return SQLITE_OK
80724** if successful, or an SQLite error code if an error occurs.
80725*/
80726static int vdbePmaReaderSeek(
80727  SortSubtask *pTask,             /* Task context */
80728  PmaReader *pReadr,              /* Reader whose cursor is to be moved */
80729  SorterFile *pFile,              /* Sorter file to read from */
80730  i64 iOff                        /* Offset in pFile */
80731){
80732  int rc = SQLITE_OK;
80733
80734  assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
80735
80736  if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
80737  if( pReadr->aMap ){
80738    sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
80739    pReadr->aMap = 0;
80740  }
80741  pReadr->iReadOff = iOff;
80742  pReadr->iEof = pFile->iEof;
80743  pReadr->pFd = pFile->pFd;
80744
80745  rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
80746  if( rc==SQLITE_OK && pReadr->aMap==0 ){
80747    int pgsz = pTask->pSorter->pgsz;
80748    int iBuf = pReadr->iReadOff % pgsz;
80749    if( pReadr->aBuffer==0 ){
80750      pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
80751      if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM;
80752      pReadr->nBuffer = pgsz;
80753    }
80754    if( rc==SQLITE_OK && iBuf ){
80755      int nRead = pgsz - iBuf;
80756      if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
80757        nRead = (int)(pReadr->iEof - pReadr->iReadOff);
80758      }
80759      rc = sqlite3OsRead(
80760          pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
80761      );
80762      testcase( rc!=SQLITE_OK );
80763    }
80764  }
80765
80766  return rc;
80767}
80768
80769/*
80770** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
80771** no error occurs, or an SQLite error code if one does.
80772*/
80773static int vdbePmaReaderNext(PmaReader *pReadr){
80774  int rc = SQLITE_OK;             /* Return Code */
80775  u64 nRec = 0;                   /* Size of record in bytes */
80776
80777
80778  if( pReadr->iReadOff>=pReadr->iEof ){
80779    IncrMerger *pIncr = pReadr->pIncr;
80780    int bEof = 1;
80781    if( pIncr ){
80782      rc = vdbeIncrSwap(pIncr);
80783      if( rc==SQLITE_OK && pIncr->bEof==0 ){
80784        rc = vdbePmaReaderSeek(
80785            pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
80786        );
80787        bEof = 0;
80788      }
80789    }
80790
80791    if( bEof ){
80792      /* This is an EOF condition */
80793      vdbePmaReaderClear(pReadr);
80794      testcase( rc!=SQLITE_OK );
80795      return rc;
80796    }
80797  }
80798
80799  if( rc==SQLITE_OK ){
80800    rc = vdbePmaReadVarint(pReadr, &nRec);
80801  }
80802  if( rc==SQLITE_OK ){
80803    pReadr->nKey = (int)nRec;
80804    rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
80805    testcase( rc!=SQLITE_OK );
80806  }
80807
80808  return rc;
80809}
80810
80811/*
80812** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
80813** starting at offset iStart and ending at offset iEof-1. This function
80814** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
80815** PMA is empty).
80816**
80817** If the pnByte parameter is NULL, then it is assumed that the file
80818** contains a single PMA, and that that PMA omits the initial length varint.
80819*/
80820static int vdbePmaReaderInit(
80821  SortSubtask *pTask,             /* Task context */
80822  SorterFile *pFile,              /* Sorter file to read from */
80823  i64 iStart,                     /* Start offset in pFile */
80824  PmaReader *pReadr,              /* PmaReader to populate */
80825  i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
80826){
80827  int rc;
80828
80829  assert( pFile->iEof>iStart );
80830  assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
80831  assert( pReadr->aBuffer==0 );
80832  assert( pReadr->aMap==0 );
80833
80834  rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
80835  if( rc==SQLITE_OK ){
80836    u64 nByte;                    /* Size of PMA in bytes */
80837    rc = vdbePmaReadVarint(pReadr, &nByte);
80838    pReadr->iEof = pReadr->iReadOff + nByte;
80839    *pnByte += nByte;
80840  }
80841
80842  if( rc==SQLITE_OK ){
80843    rc = vdbePmaReaderNext(pReadr);
80844  }
80845  return rc;
80846}
80847
80848/*
80849** A version of vdbeSorterCompare() that assumes that it has already been
80850** determined that the first field of key1 is equal to the first field of
80851** key2.
80852*/
80853static int vdbeSorterCompareTail(
80854  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
80855  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
80856  const void *pKey1, int nKey1,   /* Left side of comparison */
80857  const void *pKey2, int nKey2    /* Right side of comparison */
80858){
80859  UnpackedRecord *r2 = pTask->pUnpacked;
80860  if( *pbKey2Cached==0 ){
80861    sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
80862    *pbKey2Cached = 1;
80863  }
80864  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
80865}
80866
80867/*
80868** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
80869** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
80870** used by the comparison. Return the result of the comparison.
80871**
80872** If IN/OUT parameter *pbKey2Cached is true when this function is called,
80873** it is assumed that (pTask->pUnpacked) contains the unpacked version
80874** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
80875** version of key2 and *pbKey2Cached set to true before returning.
80876**
80877** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
80878** to SQLITE_NOMEM.
80879*/
80880static int vdbeSorterCompare(
80881  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
80882  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
80883  const void *pKey1, int nKey1,   /* Left side of comparison */
80884  const void *pKey2, int nKey2    /* Right side of comparison */
80885){
80886  UnpackedRecord *r2 = pTask->pUnpacked;
80887  if( !*pbKey2Cached ){
80888    sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
80889    *pbKey2Cached = 1;
80890  }
80891  return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
80892}
80893
80894/*
80895** A specially optimized version of vdbeSorterCompare() that assumes that
80896** the first field of each key is a TEXT value and that the collation
80897** sequence to compare them with is BINARY.
80898*/
80899static int vdbeSorterCompareText(
80900  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
80901  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
80902  const void *pKey1, int nKey1,   /* Left side of comparison */
80903  const void *pKey2, int nKey2    /* Right side of comparison */
80904){
80905  const u8 * const p1 = (const u8 * const)pKey1;
80906  const u8 * const p2 = (const u8 * const)pKey2;
80907  const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
80908  const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
80909
80910  int n1;
80911  int n2;
80912  int res;
80913
80914  getVarint32(&p1[1], n1); n1 = (n1 - 13) / 2;
80915  getVarint32(&p2[1], n2); n2 = (n2 - 13) / 2;
80916  res = memcmp(v1, v2, MIN(n1, n2));
80917  if( res==0 ){
80918    res = n1 - n2;
80919  }
80920
80921  if( res==0 ){
80922    if( pTask->pSorter->pKeyInfo->nField>1 ){
80923      res = vdbeSorterCompareTail(
80924          pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
80925      );
80926    }
80927  }else{
80928    if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
80929      res = res * -1;
80930    }
80931  }
80932
80933  return res;
80934}
80935
80936/*
80937** A specially optimized version of vdbeSorterCompare() that assumes that
80938** the first field of each key is an INTEGER value.
80939*/
80940static int vdbeSorterCompareInt(
80941  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
80942  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
80943  const void *pKey1, int nKey1,   /* Left side of comparison */
80944  const void *pKey2, int nKey2    /* Right side of comparison */
80945){
80946  const u8 * const p1 = (const u8 * const)pKey1;
80947  const u8 * const p2 = (const u8 * const)pKey2;
80948  const int s1 = p1[1];                 /* Left hand serial type */
80949  const int s2 = p2[1];                 /* Right hand serial type */
80950  const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
80951  const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
80952  int res;                              /* Return value */
80953
80954  assert( (s1>0 && s1<7) || s1==8 || s1==9 );
80955  assert( (s2>0 && s2<7) || s2==8 || s2==9 );
80956
80957  if( s1>7 && s2>7 ){
80958    res = s1 - s2;
80959  }else{
80960    if( s1==s2 ){
80961      if( (*v1 ^ *v2) & 0x80 ){
80962        /* The two values have different signs */
80963        res = (*v1 & 0x80) ? -1 : +1;
80964      }else{
80965        /* The two values have the same sign. Compare using memcmp(). */
80966        static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8 };
80967        int i;
80968        res = 0;
80969        for(i=0; i<aLen[s1]; i++){
80970          if( (res = v1[i] - v2[i]) ) break;
80971        }
80972      }
80973    }else{
80974      if( s2>7 ){
80975        res = +1;
80976      }else if( s1>7 ){
80977        res = -1;
80978      }else{
80979        res = s1 - s2;
80980      }
80981      assert( res!=0 );
80982
80983      if( res>0 ){
80984        if( *v1 & 0x80 ) res = -1;
80985      }else{
80986        if( *v2 & 0x80 ) res = +1;
80987      }
80988    }
80989  }
80990
80991  if( res==0 ){
80992    if( pTask->pSorter->pKeyInfo->nField>1 ){
80993      res = vdbeSorterCompareTail(
80994          pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
80995      );
80996    }
80997  }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
80998    res = res * -1;
80999  }
81000
81001  return res;
81002}
81003
81004/*
81005** Initialize the temporary index cursor just opened as a sorter cursor.
81006**
81007** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
81008** to determine the number of fields that should be compared from the
81009** records being sorted. However, if the value passed as argument nField
81010** is non-zero and the sorter is able to guarantee a stable sort, nField
81011** is used instead. This is used when sorting records for a CREATE INDEX
81012** statement. In this case, keys are always delivered to the sorter in
81013** order of the primary key, which happens to be make up the final part
81014** of the records being sorted. So if the sort is stable, there is never
81015** any reason to compare PK fields and they can be ignored for a small
81016** performance boost.
81017**
81018** The sorter can guarantee a stable sort when running in single-threaded
81019** mode, but not in multi-threaded mode.
81020**
81021** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
81022*/
81023SQLITE_PRIVATE int sqlite3VdbeSorterInit(
81024  sqlite3 *db,                    /* Database connection (for malloc()) */
81025  int nField,                     /* Number of key fields in each record */
81026  VdbeCursor *pCsr                /* Cursor that holds the new sorter */
81027){
81028  int pgsz;                       /* Page size of main database */
81029  int i;                          /* Used to iterate through aTask[] */
81030  int mxCache;                    /* Cache size */
81031  VdbeSorter *pSorter;            /* The new sorter */
81032  KeyInfo *pKeyInfo;              /* Copy of pCsr->pKeyInfo with db==0 */
81033  int szKeyInfo;                  /* Size of pCsr->pKeyInfo in bytes */
81034  int sz;                         /* Size of pSorter in bytes */
81035  int rc = SQLITE_OK;
81036#if SQLITE_MAX_WORKER_THREADS==0
81037# define nWorker 0
81038#else
81039  int nWorker;
81040#endif
81041
81042  /* Initialize the upper limit on the number of worker threads */
81043#if SQLITE_MAX_WORKER_THREADS>0
81044  if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
81045    nWorker = 0;
81046  }else{
81047    nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
81048  }
81049#endif
81050
81051  /* Do not allow the total number of threads (main thread + all workers)
81052  ** to exceed the maximum merge count */
81053#if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
81054  if( nWorker>=SORTER_MAX_MERGE_COUNT ){
81055    nWorker = SORTER_MAX_MERGE_COUNT-1;
81056  }
81057#endif
81058
81059  assert( pCsr->pKeyInfo && pCsr->pBt==0 );
81060  szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
81061  sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
81062
81063  pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
81064  pCsr->pSorter = pSorter;
81065  if( pSorter==0 ){
81066    rc = SQLITE_NOMEM;
81067  }else{
81068    pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
81069    memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
81070    pKeyInfo->db = 0;
81071    if( nField && nWorker==0 ){
81072      pKeyInfo->nXField += (pKeyInfo->nField - nField);
81073      pKeyInfo->nField = nField;
81074    }
81075    pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
81076    pSorter->nTask = nWorker + 1;
81077    pSorter->iPrev = nWorker-1;
81078    pSorter->bUseThreads = (pSorter->nTask>1);
81079    pSorter->db = db;
81080    for(i=0; i<pSorter->nTask; i++){
81081      SortSubtask *pTask = &pSorter->aTask[i];
81082      pTask->pSorter = pSorter;
81083    }
81084
81085    if( !sqlite3TempInMemory(db) ){
81086      u32 szPma = sqlite3GlobalConfig.szPma;
81087      pSorter->mnPmaSize = szPma * pgsz;
81088      mxCache = db->aDb[0].pSchema->cache_size;
81089      if( mxCache<(int)szPma ) mxCache = (int)szPma;
81090      pSorter->mxPmaSize = MIN((i64)mxCache*pgsz, SQLITE_MAX_PMASZ);
81091
81092      /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
81093      ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
81094      ** large heap allocations.
81095      */
81096      if( sqlite3GlobalConfig.pScratch==0 ){
81097        assert( pSorter->iMemory==0 );
81098        pSorter->nMemory = pgsz;
81099        pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
81100        if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM;
81101      }
81102    }
81103
81104    if( (pKeyInfo->nField+pKeyInfo->nXField)<13
81105     && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
81106    ){
81107      pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
81108    }
81109  }
81110
81111  return rc;
81112}
81113#undef nWorker   /* Defined at the top of this function */
81114
81115/*
81116** Free the list of sorted records starting at pRecord.
81117*/
81118static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
81119  SorterRecord *p;
81120  SorterRecord *pNext;
81121  for(p=pRecord; p; p=pNext){
81122    pNext = p->u.pNext;
81123    sqlite3DbFree(db, p);
81124  }
81125}
81126
81127/*
81128** Free all resources owned by the object indicated by argument pTask. All
81129** fields of *pTask are zeroed before returning.
81130*/
81131static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
81132  sqlite3DbFree(db, pTask->pUnpacked);
81133#if SQLITE_MAX_WORKER_THREADS>0
81134  /* pTask->list.aMemory can only be non-zero if it was handed memory
81135  ** from the main thread.  That only occurs SQLITE_MAX_WORKER_THREADS>0 */
81136  if( pTask->list.aMemory ){
81137    sqlite3_free(pTask->list.aMemory);
81138  }else
81139#endif
81140  {
81141    assert( pTask->list.aMemory==0 );
81142    vdbeSorterRecordFree(0, pTask->list.pList);
81143  }
81144  if( pTask->file.pFd ){
81145    sqlite3OsCloseFree(pTask->file.pFd);
81146  }
81147  if( pTask->file2.pFd ){
81148    sqlite3OsCloseFree(pTask->file2.pFd);
81149  }
81150  memset(pTask, 0, sizeof(SortSubtask));
81151}
81152
81153#ifdef SQLITE_DEBUG_SORTER_THREADS
81154static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
81155  i64 t;
81156  int iTask = (pTask - pTask->pSorter->aTask);
81157  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
81158  fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
81159}
81160static void vdbeSorterRewindDebug(const char *zEvent){
81161  i64 t;
81162  sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
81163  fprintf(stderr, "%lld:X %s\n", t, zEvent);
81164}
81165static void vdbeSorterPopulateDebug(
81166  SortSubtask *pTask,
81167  const char *zEvent
81168){
81169  i64 t;
81170  int iTask = (pTask - pTask->pSorter->aTask);
81171  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
81172  fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
81173}
81174static void vdbeSorterBlockDebug(
81175  SortSubtask *pTask,
81176  int bBlocked,
81177  const char *zEvent
81178){
81179  if( bBlocked ){
81180    i64 t;
81181    sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
81182    fprintf(stderr, "%lld:main %s\n", t, zEvent);
81183  }
81184}
81185#else
81186# define vdbeSorterWorkDebug(x,y)
81187# define vdbeSorterRewindDebug(y)
81188# define vdbeSorterPopulateDebug(x,y)
81189# define vdbeSorterBlockDebug(x,y,z)
81190#endif
81191
81192#if SQLITE_MAX_WORKER_THREADS>0
81193/*
81194** Join thread pTask->thread.
81195*/
81196static int vdbeSorterJoinThread(SortSubtask *pTask){
81197  int rc = SQLITE_OK;
81198  if( pTask->pThread ){
81199#ifdef SQLITE_DEBUG_SORTER_THREADS
81200    int bDone = pTask->bDone;
81201#endif
81202    void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
81203    vdbeSorterBlockDebug(pTask, !bDone, "enter");
81204    (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
81205    vdbeSorterBlockDebug(pTask, !bDone, "exit");
81206    rc = SQLITE_PTR_TO_INT(pRet);
81207    assert( pTask->bDone==1 );
81208    pTask->bDone = 0;
81209    pTask->pThread = 0;
81210  }
81211  return rc;
81212}
81213
81214/*
81215** Launch a background thread to run xTask(pIn).
81216*/
81217static int vdbeSorterCreateThread(
81218  SortSubtask *pTask,             /* Thread will use this task object */
81219  void *(*xTask)(void*),          /* Routine to run in a separate thread */
81220  void *pIn                       /* Argument passed into xTask() */
81221){
81222  assert( pTask->pThread==0 && pTask->bDone==0 );
81223  return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
81224}
81225
81226/*
81227** Join all outstanding threads launched by SorterWrite() to create
81228** level-0 PMAs.
81229*/
81230static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
81231  int rc = rcin;
81232  int i;
81233
81234  /* This function is always called by the main user thread.
81235  **
81236  ** If this function is being called after SorterRewind() has been called,
81237  ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
81238  ** is currently attempt to join one of the other threads. To avoid a race
81239  ** condition where this thread also attempts to join the same object, join
81240  ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
81241  for(i=pSorter->nTask-1; i>=0; i--){
81242    SortSubtask *pTask = &pSorter->aTask[i];
81243    int rc2 = vdbeSorterJoinThread(pTask);
81244    if( rc==SQLITE_OK ) rc = rc2;
81245  }
81246  return rc;
81247}
81248#else
81249# define vdbeSorterJoinAll(x,rcin) (rcin)
81250# define vdbeSorterJoinThread(pTask) SQLITE_OK
81251#endif
81252
81253/*
81254** Allocate a new MergeEngine object capable of handling up to
81255** nReader PmaReader inputs.
81256**
81257** nReader is automatically rounded up to the next power of two.
81258** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
81259*/
81260static MergeEngine *vdbeMergeEngineNew(int nReader){
81261  int N = 2;                      /* Smallest power of two >= nReader */
81262  int nByte;                      /* Total bytes of space to allocate */
81263  MergeEngine *pNew;              /* Pointer to allocated object to return */
81264
81265  assert( nReader<=SORTER_MAX_MERGE_COUNT );
81266
81267  while( N<nReader ) N += N;
81268  nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
81269
81270  pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
81271  if( pNew ){
81272    pNew->nTree = N;
81273    pNew->pTask = 0;
81274    pNew->aReadr = (PmaReader*)&pNew[1];
81275    pNew->aTree = (int*)&pNew->aReadr[N];
81276  }
81277  return pNew;
81278}
81279
81280/*
81281** Free the MergeEngine object passed as the only argument.
81282*/
81283static void vdbeMergeEngineFree(MergeEngine *pMerger){
81284  int i;
81285  if( pMerger ){
81286    for(i=0; i<pMerger->nTree; i++){
81287      vdbePmaReaderClear(&pMerger->aReadr[i]);
81288    }
81289  }
81290  sqlite3_free(pMerger);
81291}
81292
81293/*
81294** Free all resources associated with the IncrMerger object indicated by
81295** the first argument.
81296*/
81297static void vdbeIncrFree(IncrMerger *pIncr){
81298  if( pIncr ){
81299#if SQLITE_MAX_WORKER_THREADS>0
81300    if( pIncr->bUseThread ){
81301      vdbeSorterJoinThread(pIncr->pTask);
81302      if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
81303      if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
81304    }
81305#endif
81306    vdbeMergeEngineFree(pIncr->pMerger);
81307    sqlite3_free(pIncr);
81308  }
81309}
81310
81311/*
81312** Reset a sorting cursor back to its original empty state.
81313*/
81314SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
81315  int i;
81316  (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
81317  assert( pSorter->bUseThreads || pSorter->pReader==0 );
81318#if SQLITE_MAX_WORKER_THREADS>0
81319  if( pSorter->pReader ){
81320    vdbePmaReaderClear(pSorter->pReader);
81321    sqlite3DbFree(db, pSorter->pReader);
81322    pSorter->pReader = 0;
81323  }
81324#endif
81325  vdbeMergeEngineFree(pSorter->pMerger);
81326  pSorter->pMerger = 0;
81327  for(i=0; i<pSorter->nTask; i++){
81328    SortSubtask *pTask = &pSorter->aTask[i];
81329    vdbeSortSubtaskCleanup(db, pTask);
81330    pTask->pSorter = pSorter;
81331  }
81332  if( pSorter->list.aMemory==0 ){
81333    vdbeSorterRecordFree(0, pSorter->list.pList);
81334  }
81335  pSorter->list.pList = 0;
81336  pSorter->list.szPMA = 0;
81337  pSorter->bUsePMA = 0;
81338  pSorter->iMemory = 0;
81339  pSorter->mxKeysize = 0;
81340  sqlite3DbFree(db, pSorter->pUnpacked);
81341  pSorter->pUnpacked = 0;
81342}
81343
81344/*
81345** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
81346*/
81347SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
81348  VdbeSorter *pSorter = pCsr->pSorter;
81349  if( pSorter ){
81350    sqlite3VdbeSorterReset(db, pSorter);
81351    sqlite3_free(pSorter->list.aMemory);
81352    sqlite3DbFree(db, pSorter);
81353    pCsr->pSorter = 0;
81354  }
81355}
81356
81357#if SQLITE_MAX_MMAP_SIZE>0
81358/*
81359** The first argument is a file-handle open on a temporary file. The file
81360** is guaranteed to be nByte bytes or smaller in size. This function
81361** attempts to extend the file to nByte bytes in size and to ensure that
81362** the VFS has memory mapped it.
81363**
81364** Whether or not the file does end up memory mapped of course depends on
81365** the specific VFS implementation.
81366*/
81367static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
81368  if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
81369    void *p = 0;
81370    int chunksize = 4*1024;
81371    sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
81372    sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
81373    sqlite3OsFetch(pFd, 0, (int)nByte, &p);
81374    sqlite3OsUnfetch(pFd, 0, p);
81375  }
81376}
81377#else
81378# define vdbeSorterExtendFile(x,y,z)
81379#endif
81380
81381/*
81382** Allocate space for a file-handle and open a temporary file. If successful,
81383** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
81384** Otherwise, set *ppFd to 0 and return an SQLite error code.
81385*/
81386static int vdbeSorterOpenTempFile(
81387  sqlite3 *db,                    /* Database handle doing sort */
81388  i64 nExtend,                    /* Attempt to extend file to this size */
81389  sqlite3_file **ppFd
81390){
81391  int rc;
81392  if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
81393  rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
81394      SQLITE_OPEN_TEMP_JOURNAL |
81395      SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
81396      SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &rc
81397  );
81398  if( rc==SQLITE_OK ){
81399    i64 max = SQLITE_MAX_MMAP_SIZE;
81400    sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
81401    if( nExtend>0 ){
81402      vdbeSorterExtendFile(db, *ppFd, nExtend);
81403    }
81404  }
81405  return rc;
81406}
81407
81408/*
81409** If it has not already been allocated, allocate the UnpackedRecord
81410** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
81411** if no allocation was required), or SQLITE_NOMEM otherwise.
81412*/
81413static int vdbeSortAllocUnpacked(SortSubtask *pTask){
81414  if( pTask->pUnpacked==0 ){
81415    char *pFree;
81416    pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(
81417        pTask->pSorter->pKeyInfo, 0, 0, &pFree
81418    );
81419    assert( pTask->pUnpacked==(UnpackedRecord*)pFree );
81420    if( pFree==0 ) return SQLITE_NOMEM;
81421    pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
81422    pTask->pUnpacked->errCode = 0;
81423  }
81424  return SQLITE_OK;
81425}
81426
81427
81428/*
81429** Merge the two sorted lists p1 and p2 into a single list.
81430** Set *ppOut to the head of the new list.
81431*/
81432static void vdbeSorterMerge(
81433  SortSubtask *pTask,             /* Calling thread context */
81434  SorterRecord *p1,               /* First list to merge */
81435  SorterRecord *p2,               /* Second list to merge */
81436  SorterRecord **ppOut            /* OUT: Head of merged list */
81437){
81438  SorterRecord *pFinal = 0;
81439  SorterRecord **pp = &pFinal;
81440  int bCached = 0;
81441
81442  while( p1 && p2 ){
81443    int res;
81444    res = pTask->xCompare(
81445        pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
81446    );
81447
81448    if( res<=0 ){
81449      *pp = p1;
81450      pp = &p1->u.pNext;
81451      p1 = p1->u.pNext;
81452    }else{
81453      *pp = p2;
81454      pp = &p2->u.pNext;
81455      p2 = p2->u.pNext;
81456      bCached = 0;
81457    }
81458  }
81459  *pp = p1 ? p1 : p2;
81460  *ppOut = pFinal;
81461}
81462
81463/*
81464** Return the SorterCompare function to compare values collected by the
81465** sorter object passed as the only argument.
81466*/
81467static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
81468  if( p->typeMask==SORTER_TYPE_INTEGER ){
81469    return vdbeSorterCompareInt;
81470  }else if( p->typeMask==SORTER_TYPE_TEXT ){
81471    return vdbeSorterCompareText;
81472  }
81473  return vdbeSorterCompare;
81474}
81475
81476/*
81477** Sort the linked list of records headed at pTask->pList. Return
81478** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
81479** an error occurs.
81480*/
81481static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
81482  int i;
81483  SorterRecord **aSlot;
81484  SorterRecord *p;
81485  int rc;
81486
81487  rc = vdbeSortAllocUnpacked(pTask);
81488  if( rc!=SQLITE_OK ) return rc;
81489
81490  p = pList->pList;
81491  pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
81492
81493  aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
81494  if( !aSlot ){
81495    return SQLITE_NOMEM;
81496  }
81497
81498  while( p ){
81499    SorterRecord *pNext;
81500    if( pList->aMemory ){
81501      if( (u8*)p==pList->aMemory ){
81502        pNext = 0;
81503      }else{
81504        assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
81505        pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
81506      }
81507    }else{
81508      pNext = p->u.pNext;
81509    }
81510
81511    p->u.pNext = 0;
81512    for(i=0; aSlot[i]; i++){
81513      vdbeSorterMerge(pTask, p, aSlot[i], &p);
81514      aSlot[i] = 0;
81515    }
81516    aSlot[i] = p;
81517    p = pNext;
81518  }
81519
81520  p = 0;
81521  for(i=0; i<64; i++){
81522    vdbeSorterMerge(pTask, p, aSlot[i], &p);
81523  }
81524  pList->pList = p;
81525
81526  sqlite3_free(aSlot);
81527  assert( pTask->pUnpacked->errCode==SQLITE_OK
81528       || pTask->pUnpacked->errCode==SQLITE_NOMEM
81529  );
81530  return pTask->pUnpacked->errCode;
81531}
81532
81533/*
81534** Initialize a PMA-writer object.
81535*/
81536static void vdbePmaWriterInit(
81537  sqlite3_file *pFd,              /* File handle to write to */
81538  PmaWriter *p,                   /* Object to populate */
81539  int nBuf,                       /* Buffer size */
81540  i64 iStart                      /* Offset of pFd to begin writing at */
81541){
81542  memset(p, 0, sizeof(PmaWriter));
81543  p->aBuffer = (u8*)sqlite3Malloc(nBuf);
81544  if( !p->aBuffer ){
81545    p->eFWErr = SQLITE_NOMEM;
81546  }else{
81547    p->iBufEnd = p->iBufStart = (iStart % nBuf);
81548    p->iWriteOff = iStart - p->iBufStart;
81549    p->nBuffer = nBuf;
81550    p->pFd = pFd;
81551  }
81552}
81553
81554/*
81555** Write nData bytes of data to the PMA. Return SQLITE_OK
81556** if successful, or an SQLite error code if an error occurs.
81557*/
81558static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
81559  int nRem = nData;
81560  while( nRem>0 && p->eFWErr==0 ){
81561    int nCopy = nRem;
81562    if( nCopy>(p->nBuffer - p->iBufEnd) ){
81563      nCopy = p->nBuffer - p->iBufEnd;
81564    }
81565
81566    memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
81567    p->iBufEnd += nCopy;
81568    if( p->iBufEnd==p->nBuffer ){
81569      p->eFWErr = sqlite3OsWrite(p->pFd,
81570          &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
81571          p->iWriteOff + p->iBufStart
81572      );
81573      p->iBufStart = p->iBufEnd = 0;
81574      p->iWriteOff += p->nBuffer;
81575    }
81576    assert( p->iBufEnd<p->nBuffer );
81577
81578    nRem -= nCopy;
81579  }
81580}
81581
81582/*
81583** Flush any buffered data to disk and clean up the PMA-writer object.
81584** The results of using the PMA-writer after this call are undefined.
81585** Return SQLITE_OK if flushing the buffered data succeeds or is not
81586** required. Otherwise, return an SQLite error code.
81587**
81588** Before returning, set *piEof to the offset immediately following the
81589** last byte written to the file.
81590*/
81591static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
81592  int rc;
81593  if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
81594    p->eFWErr = sqlite3OsWrite(p->pFd,
81595        &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
81596        p->iWriteOff + p->iBufStart
81597    );
81598  }
81599  *piEof = (p->iWriteOff + p->iBufEnd);
81600  sqlite3_free(p->aBuffer);
81601  rc = p->eFWErr;
81602  memset(p, 0, sizeof(PmaWriter));
81603  return rc;
81604}
81605
81606/*
81607** Write value iVal encoded as a varint to the PMA. Return
81608** SQLITE_OK if successful, or an SQLite error code if an error occurs.
81609*/
81610static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
81611  int nByte;
81612  u8 aByte[10];
81613  nByte = sqlite3PutVarint(aByte, iVal);
81614  vdbePmaWriteBlob(p, aByte, nByte);
81615}
81616
81617/*
81618** Write the current contents of in-memory linked-list pList to a level-0
81619** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
81620** successful, or an SQLite error code otherwise.
81621**
81622** The format of a PMA is:
81623**
81624**     * A varint. This varint contains the total number of bytes of content
81625**       in the PMA (not including the varint itself).
81626**
81627**     * One or more records packed end-to-end in order of ascending keys.
81628**       Each record consists of a varint followed by a blob of data (the
81629**       key). The varint is the number of bytes in the blob of data.
81630*/
81631static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
81632  sqlite3 *db = pTask->pSorter->db;
81633  int rc = SQLITE_OK;             /* Return code */
81634  PmaWriter writer;               /* Object used to write to the file */
81635
81636#ifdef SQLITE_DEBUG
81637  /* Set iSz to the expected size of file pTask->file after writing the PMA.
81638  ** This is used by an assert() statement at the end of this function.  */
81639  i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
81640#endif
81641
81642  vdbeSorterWorkDebug(pTask, "enter");
81643  memset(&writer, 0, sizeof(PmaWriter));
81644  assert( pList->szPMA>0 );
81645
81646  /* If the first temporary PMA file has not been opened, open it now. */
81647  if( pTask->file.pFd==0 ){
81648    rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
81649    assert( rc!=SQLITE_OK || pTask->file.pFd );
81650    assert( pTask->file.iEof==0 );
81651    assert( pTask->nPMA==0 );
81652  }
81653
81654  /* Try to get the file to memory map */
81655  if( rc==SQLITE_OK ){
81656    vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
81657  }
81658
81659  /* Sort the list */
81660  if( rc==SQLITE_OK ){
81661    rc = vdbeSorterSort(pTask, pList);
81662  }
81663
81664  if( rc==SQLITE_OK ){
81665    SorterRecord *p;
81666    SorterRecord *pNext = 0;
81667
81668    vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
81669                      pTask->file.iEof);
81670    pTask->nPMA++;
81671    vdbePmaWriteVarint(&writer, pList->szPMA);
81672    for(p=pList->pList; p; p=pNext){
81673      pNext = p->u.pNext;
81674      vdbePmaWriteVarint(&writer, p->nVal);
81675      vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
81676      if( pList->aMemory==0 ) sqlite3_free(p);
81677    }
81678    pList->pList = p;
81679    rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
81680  }
81681
81682  vdbeSorterWorkDebug(pTask, "exit");
81683  assert( rc!=SQLITE_OK || pList->pList==0 );
81684  assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
81685  return rc;
81686}
81687
81688/*
81689** Advance the MergeEngine to its next entry.
81690** Set *pbEof to true there is no next entry because
81691** the MergeEngine has reached the end of all its inputs.
81692**
81693** Return SQLITE_OK if successful or an error code if an error occurs.
81694*/
81695static int vdbeMergeEngineStep(
81696  MergeEngine *pMerger,      /* The merge engine to advance to the next row */
81697  int *pbEof                 /* Set TRUE at EOF.  Set false for more content */
81698){
81699  int rc;
81700  int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
81701  SortSubtask *pTask = pMerger->pTask;
81702
81703  /* Advance the current PmaReader */
81704  rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
81705
81706  /* Update contents of aTree[] */
81707  if( rc==SQLITE_OK ){
81708    int i;                      /* Index of aTree[] to recalculate */
81709    PmaReader *pReadr1;         /* First PmaReader to compare */
81710    PmaReader *pReadr2;         /* Second PmaReader to compare */
81711    int bCached = 0;
81712
81713    /* Find the first two PmaReaders to compare. The one that was just
81714    ** advanced (iPrev) and the one next to it in the array.  */
81715    pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
81716    pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
81717
81718    for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
81719      /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
81720      int iRes;
81721      if( pReadr1->pFd==0 ){
81722        iRes = +1;
81723      }else if( pReadr2->pFd==0 ){
81724        iRes = -1;
81725      }else{
81726        iRes = pTask->xCompare(pTask, &bCached,
81727            pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
81728        );
81729      }
81730
81731      /* If pReadr1 contained the smaller value, set aTree[i] to its index.
81732      ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
81733      ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
81734      ** pKey2 to point to the record belonging to pReadr2.
81735      **
81736      ** Alternatively, if pReadr2 contains the smaller of the two values,
81737      ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
81738      ** was actually called above, then pTask->pUnpacked now contains
81739      ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
81740      ** vdbeSorterCompare() from decoding pReadr2 again.
81741      **
81742      ** If the two values were equal, then the value from the oldest
81743      ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
81744      ** is sorted from oldest to newest, so pReadr1 contains older values
81745      ** than pReadr2 iff (pReadr1<pReadr2).  */
81746      if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
81747        pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
81748        pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
81749        bCached = 0;
81750      }else{
81751        if( pReadr1->pFd ) bCached = 0;
81752        pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
81753        pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
81754      }
81755    }
81756    *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
81757  }
81758
81759  return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
81760}
81761
81762#if SQLITE_MAX_WORKER_THREADS>0
81763/*
81764** The main routine for background threads that write level-0 PMAs.
81765*/
81766static void *vdbeSorterFlushThread(void *pCtx){
81767  SortSubtask *pTask = (SortSubtask*)pCtx;
81768  int rc;                         /* Return code */
81769  assert( pTask->bDone==0 );
81770  rc = vdbeSorterListToPMA(pTask, &pTask->list);
81771  pTask->bDone = 1;
81772  return SQLITE_INT_TO_PTR(rc);
81773}
81774#endif /* SQLITE_MAX_WORKER_THREADS>0 */
81775
81776/*
81777** Flush the current contents of VdbeSorter.list to a new PMA, possibly
81778** using a background thread.
81779*/
81780static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
81781#if SQLITE_MAX_WORKER_THREADS==0
81782  pSorter->bUsePMA = 1;
81783  return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
81784#else
81785  int rc = SQLITE_OK;
81786  int i;
81787  SortSubtask *pTask = 0;    /* Thread context used to create new PMA */
81788  int nWorker = (pSorter->nTask-1);
81789
81790  /* Set the flag to indicate that at least one PMA has been written.
81791  ** Or will be, anyhow.  */
81792  pSorter->bUsePMA = 1;
81793
81794  /* Select a sub-task to sort and flush the current list of in-memory
81795  ** records to disk. If the sorter is running in multi-threaded mode,
81796  ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
81797  ** the background thread from a sub-tasks previous turn is still running,
81798  ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
81799  ** fall back to using the final sub-task. The first (pSorter->nTask-1)
81800  ** sub-tasks are prefered as they use background threads - the final
81801  ** sub-task uses the main thread. */
81802  for(i=0; i<nWorker; i++){
81803    int iTest = (pSorter->iPrev + i + 1) % nWorker;
81804    pTask = &pSorter->aTask[iTest];
81805    if( pTask->bDone ){
81806      rc = vdbeSorterJoinThread(pTask);
81807    }
81808    if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
81809  }
81810
81811  if( rc==SQLITE_OK ){
81812    if( i==nWorker ){
81813      /* Use the foreground thread for this operation */
81814      rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
81815    }else{
81816      /* Launch a background thread for this operation */
81817      u8 *aMem = pTask->list.aMemory;
81818      void *pCtx = (void*)pTask;
81819
81820      assert( pTask->pThread==0 && pTask->bDone==0 );
81821      assert( pTask->list.pList==0 );
81822      assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
81823
81824      pSorter->iPrev = (u8)(pTask - pSorter->aTask);
81825      pTask->list = pSorter->list;
81826      pSorter->list.pList = 0;
81827      pSorter->list.szPMA = 0;
81828      if( aMem ){
81829        pSorter->list.aMemory = aMem;
81830        pSorter->nMemory = sqlite3MallocSize(aMem);
81831      }else if( pSorter->list.aMemory ){
81832        pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
81833        if( !pSorter->list.aMemory ) return SQLITE_NOMEM;
81834      }
81835
81836      rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
81837    }
81838  }
81839
81840  return rc;
81841#endif /* SQLITE_MAX_WORKER_THREADS!=0 */
81842}
81843
81844/*
81845** Add a record to the sorter.
81846*/
81847SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
81848  const VdbeCursor *pCsr,         /* Sorter cursor */
81849  Mem *pVal                       /* Memory cell containing record */
81850){
81851  VdbeSorter *pSorter = pCsr->pSorter;
81852  int rc = SQLITE_OK;             /* Return Code */
81853  SorterRecord *pNew;             /* New list element */
81854
81855  int bFlush;                     /* True to flush contents of memory to PMA */
81856  int nReq;                       /* Bytes of memory required */
81857  int nPMA;                       /* Bytes of PMA space required */
81858  int t;                          /* serial type of first record field */
81859
81860  getVarint32((const u8*)&pVal->z[1], t);
81861  if( t>0 && t<10 && t!=7 ){
81862    pSorter->typeMask &= SORTER_TYPE_INTEGER;
81863  }else if( t>10 && (t & 0x01) ){
81864    pSorter->typeMask &= SORTER_TYPE_TEXT;
81865  }else{
81866    pSorter->typeMask = 0;
81867  }
81868
81869  assert( pSorter );
81870
81871  /* Figure out whether or not the current contents of memory should be
81872  ** flushed to a PMA before continuing. If so, do so.
81873  **
81874  ** If using the single large allocation mode (pSorter->aMemory!=0), then
81875  ** flush the contents of memory to a new PMA if (a) at least one value is
81876  ** already in memory and (b) the new value will not fit in memory.
81877  **
81878  ** Or, if using separate allocations for each record, flush the contents
81879  ** of memory to a PMA if either of the following are true:
81880  **
81881  **   * The total memory allocated for the in-memory list is greater
81882  **     than (page-size * cache-size), or
81883  **
81884  **   * The total memory allocated for the in-memory list is greater
81885  **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
81886  */
81887  nReq = pVal->n + sizeof(SorterRecord);
81888  nPMA = pVal->n + sqlite3VarintLen(pVal->n);
81889  if( pSorter->mxPmaSize ){
81890    if( pSorter->list.aMemory ){
81891      bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
81892    }else{
81893      bFlush = (
81894          (pSorter->list.szPMA > pSorter->mxPmaSize)
81895       || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
81896      );
81897    }
81898    if( bFlush ){
81899      rc = vdbeSorterFlushPMA(pSorter);
81900      pSorter->list.szPMA = 0;
81901      pSorter->iMemory = 0;
81902      assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
81903    }
81904  }
81905
81906  pSorter->list.szPMA += nPMA;
81907  if( nPMA>pSorter->mxKeysize ){
81908    pSorter->mxKeysize = nPMA;
81909  }
81910
81911  if( pSorter->list.aMemory ){
81912    int nMin = pSorter->iMemory + nReq;
81913
81914    if( nMin>pSorter->nMemory ){
81915      u8 *aNew;
81916      int nNew = pSorter->nMemory * 2;
81917      while( nNew < nMin ) nNew = nNew*2;
81918      if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
81919      if( nNew < nMin ) nNew = nMin;
81920
81921      aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
81922      if( !aNew ) return SQLITE_NOMEM;
81923      pSorter->list.pList = (SorterRecord*)(
81924          aNew + ((u8*)pSorter->list.pList - pSorter->list.aMemory)
81925      );
81926      pSorter->list.aMemory = aNew;
81927      pSorter->nMemory = nNew;
81928    }
81929
81930    pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
81931    pSorter->iMemory += ROUND8(nReq);
81932    pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
81933  }else{
81934    pNew = (SorterRecord *)sqlite3Malloc(nReq);
81935    if( pNew==0 ){
81936      return SQLITE_NOMEM;
81937    }
81938    pNew->u.pNext = pSorter->list.pList;
81939  }
81940
81941  memcpy(SRVAL(pNew), pVal->z, pVal->n);
81942  pNew->nVal = pVal->n;
81943  pSorter->list.pList = pNew;
81944
81945  return rc;
81946}
81947
81948/*
81949** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
81950** of the data stored in aFile[1] is the same as that used by regular PMAs,
81951** except that the number-of-bytes varint is omitted from the start.
81952*/
81953static int vdbeIncrPopulate(IncrMerger *pIncr){
81954  int rc = SQLITE_OK;
81955  int rc2;
81956  i64 iStart = pIncr->iStartOff;
81957  SorterFile *pOut = &pIncr->aFile[1];
81958  SortSubtask *pTask = pIncr->pTask;
81959  MergeEngine *pMerger = pIncr->pMerger;
81960  PmaWriter writer;
81961  assert( pIncr->bEof==0 );
81962
81963  vdbeSorterPopulateDebug(pTask, "enter");
81964
81965  vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
81966  while( rc==SQLITE_OK ){
81967    int dummy;
81968    PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
81969    int nKey = pReader->nKey;
81970    i64 iEof = writer.iWriteOff + writer.iBufEnd;
81971
81972    /* Check if the output file is full or if the input has been exhausted.
81973    ** In either case exit the loop. */
81974    if( pReader->pFd==0 ) break;
81975    if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
81976
81977    /* Write the next key to the output. */
81978    vdbePmaWriteVarint(&writer, nKey);
81979    vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
81980    assert( pIncr->pMerger->pTask==pTask );
81981    rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
81982  }
81983
81984  rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
81985  if( rc==SQLITE_OK ) rc = rc2;
81986  vdbeSorterPopulateDebug(pTask, "exit");
81987  return rc;
81988}
81989
81990#if SQLITE_MAX_WORKER_THREADS>0
81991/*
81992** The main routine for background threads that populate aFile[1] of
81993** multi-threaded IncrMerger objects.
81994*/
81995static void *vdbeIncrPopulateThread(void *pCtx){
81996  IncrMerger *pIncr = (IncrMerger*)pCtx;
81997  void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
81998  pIncr->pTask->bDone = 1;
81999  return pRet;
82000}
82001
82002/*
82003** Launch a background thread to populate aFile[1] of pIncr.
82004*/
82005static int vdbeIncrBgPopulate(IncrMerger *pIncr){
82006  void *p = (void*)pIncr;
82007  assert( pIncr->bUseThread );
82008  return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
82009}
82010#endif
82011
82012/*
82013** This function is called when the PmaReader corresponding to pIncr has
82014** finished reading the contents of aFile[0]. Its purpose is to "refill"
82015** aFile[0] such that the PmaReader should start rereading it from the
82016** beginning.
82017**
82018** For single-threaded objects, this is accomplished by literally reading
82019** keys from pIncr->pMerger and repopulating aFile[0].
82020**
82021** For multi-threaded objects, all that is required is to wait until the
82022** background thread is finished (if it is not already) and then swap
82023** aFile[0] and aFile[1] in place. If the contents of pMerger have not
82024** been exhausted, this function also launches a new background thread
82025** to populate the new aFile[1].
82026**
82027** SQLITE_OK is returned on success, or an SQLite error code otherwise.
82028*/
82029static int vdbeIncrSwap(IncrMerger *pIncr){
82030  int rc = SQLITE_OK;
82031
82032#if SQLITE_MAX_WORKER_THREADS>0
82033  if( pIncr->bUseThread ){
82034    rc = vdbeSorterJoinThread(pIncr->pTask);
82035
82036    if( rc==SQLITE_OK ){
82037      SorterFile f0 = pIncr->aFile[0];
82038      pIncr->aFile[0] = pIncr->aFile[1];
82039      pIncr->aFile[1] = f0;
82040    }
82041
82042    if( rc==SQLITE_OK ){
82043      if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
82044        pIncr->bEof = 1;
82045      }else{
82046        rc = vdbeIncrBgPopulate(pIncr);
82047      }
82048    }
82049  }else
82050#endif
82051  {
82052    rc = vdbeIncrPopulate(pIncr);
82053    pIncr->aFile[0] = pIncr->aFile[1];
82054    if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
82055      pIncr->bEof = 1;
82056    }
82057  }
82058
82059  return rc;
82060}
82061
82062/*
82063** Allocate and return a new IncrMerger object to read data from pMerger.
82064**
82065** If an OOM condition is encountered, return NULL. In this case free the
82066** pMerger argument before returning.
82067*/
82068static int vdbeIncrMergerNew(
82069  SortSubtask *pTask,     /* The thread that will be using the new IncrMerger */
82070  MergeEngine *pMerger,   /* The MergeEngine that the IncrMerger will control */
82071  IncrMerger **ppOut      /* Write the new IncrMerger here */
82072){
82073  int rc = SQLITE_OK;
82074  IncrMerger *pIncr = *ppOut = (IncrMerger*)
82075       (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
82076  if( pIncr ){
82077    pIncr->pMerger = pMerger;
82078    pIncr->pTask = pTask;
82079    pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
82080    pTask->file2.iEof += pIncr->mxSz;
82081  }else{
82082    vdbeMergeEngineFree(pMerger);
82083    rc = SQLITE_NOMEM;
82084  }
82085  return rc;
82086}
82087
82088#if SQLITE_MAX_WORKER_THREADS>0
82089/*
82090** Set the "use-threads" flag on object pIncr.
82091*/
82092static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
82093  pIncr->bUseThread = 1;
82094  pIncr->pTask->file2.iEof -= pIncr->mxSz;
82095}
82096#endif /* SQLITE_MAX_WORKER_THREADS>0 */
82097
82098
82099
82100/*
82101** Recompute pMerger->aTree[iOut] by comparing the next keys on the
82102** two PmaReaders that feed that entry.  Neither of the PmaReaders
82103** are advanced.  This routine merely does the comparison.
82104*/
82105static void vdbeMergeEngineCompare(
82106  MergeEngine *pMerger,  /* Merge engine containing PmaReaders to compare */
82107  int iOut               /* Store the result in pMerger->aTree[iOut] */
82108){
82109  int i1;
82110  int i2;
82111  int iRes;
82112  PmaReader *p1;
82113  PmaReader *p2;
82114
82115  assert( iOut<pMerger->nTree && iOut>0 );
82116
82117  if( iOut>=(pMerger->nTree/2) ){
82118    i1 = (iOut - pMerger->nTree/2) * 2;
82119    i2 = i1 + 1;
82120  }else{
82121    i1 = pMerger->aTree[iOut*2];
82122    i2 = pMerger->aTree[iOut*2+1];
82123  }
82124
82125  p1 = &pMerger->aReadr[i1];
82126  p2 = &pMerger->aReadr[i2];
82127
82128  if( p1->pFd==0 ){
82129    iRes = i2;
82130  }else if( p2->pFd==0 ){
82131    iRes = i1;
82132  }else{
82133    SortSubtask *pTask = pMerger->pTask;
82134    int bCached = 0;
82135    int res;
82136    assert( pTask->pUnpacked!=0 );  /* from vdbeSortSubtaskMain() */
82137    res = pTask->xCompare(
82138        pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
82139    );
82140    if( res<=0 ){
82141      iRes = i1;
82142    }else{
82143      iRes = i2;
82144    }
82145  }
82146
82147  pMerger->aTree[iOut] = iRes;
82148}
82149
82150/*
82151** Allowed values for the eMode parameter to vdbeMergeEngineInit()
82152** and vdbePmaReaderIncrMergeInit().
82153**
82154** Only INCRINIT_NORMAL is valid in single-threaded builds (when
82155** SQLITE_MAX_WORKER_THREADS==0).  The other values are only used
82156** when there exists one or more separate worker threads.
82157*/
82158#define INCRINIT_NORMAL 0
82159#define INCRINIT_TASK   1
82160#define INCRINIT_ROOT   2
82161
82162/*
82163** Forward reference required as the vdbeIncrMergeInit() and
82164** vdbePmaReaderIncrInit() routines are called mutually recursively when
82165** building a merge tree.
82166*/
82167static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
82168
82169/*
82170** Initialize the MergeEngine object passed as the second argument. Once this
82171** function returns, the first key of merged data may be read from the
82172** MergeEngine object in the usual fashion.
82173**
82174** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
82175** objects attached to the PmaReader objects that the merger reads from have
82176** already been populated, but that they have not yet populated aFile[0] and
82177** set the PmaReader objects up to read from it. In this case all that is
82178** required is to call vdbePmaReaderNext() on each PmaReader to point it at
82179** its first key.
82180**
82181** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
82182** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
82183** to pMerger.
82184**
82185** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
82186*/
82187static int vdbeMergeEngineInit(
82188  SortSubtask *pTask,             /* Thread that will run pMerger */
82189  MergeEngine *pMerger,           /* MergeEngine to initialize */
82190  int eMode                       /* One of the INCRINIT_XXX constants */
82191){
82192  int rc = SQLITE_OK;             /* Return code */
82193  int i;                          /* For looping over PmaReader objects */
82194  int nTree = pMerger->nTree;
82195
82196  /* eMode is always INCRINIT_NORMAL in single-threaded mode */
82197  assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
82198
82199  /* Verify that the MergeEngine is assigned to a single thread */
82200  assert( pMerger->pTask==0 );
82201  pMerger->pTask = pTask;
82202
82203  for(i=0; i<nTree; i++){
82204    if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
82205      /* PmaReaders should be normally initialized in order, as if they are
82206      ** reading from the same temp file this makes for more linear file IO.
82207      ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
82208      ** in use it will block the vdbePmaReaderNext() call while it uses
82209      ** the main thread to fill its buffer. So calling PmaReaderNext()
82210      ** on this PmaReader before any of the multi-threaded PmaReaders takes
82211      ** better advantage of multi-processor hardware. */
82212      rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
82213    }else{
82214      rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
82215    }
82216    if( rc!=SQLITE_OK ) return rc;
82217  }
82218
82219  for(i=pMerger->nTree-1; i>0; i--){
82220    vdbeMergeEngineCompare(pMerger, i);
82221  }
82222  return pTask->pUnpacked->errCode;
82223}
82224
82225/*
82226** The PmaReader passed as the first argument is guaranteed to be an
82227** incremental-reader (pReadr->pIncr!=0). This function serves to open
82228** and/or initialize the temp file related fields of the IncrMerge
82229** object at (pReadr->pIncr).
82230**
82231** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
82232** in the sub-tree headed by pReadr are also initialized. Data is then
82233** loaded into the buffers belonging to pReadr and it is set to point to
82234** the first key in its range.
82235**
82236** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
82237** to be a multi-threaded PmaReader and this function is being called in a
82238** background thread. In this case all PmaReaders in the sub-tree are
82239** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
82240** pReadr is populated. However, pReadr itself is not set up to point
82241** to its first key. A call to vdbePmaReaderNext() is still required to do
82242** that.
82243**
82244** The reason this function does not call vdbePmaReaderNext() immediately
82245** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
82246** to block on thread (pTask->thread) before accessing aFile[1]. But, since
82247** this entire function is being run by thread (pTask->thread), that will
82248** lead to the current background thread attempting to join itself.
82249**
82250** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
82251** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
82252** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
82253** In this case vdbePmaReaderNext() is called on all child PmaReaders and
82254** the current PmaReader set to point to the first key in its range.
82255**
82256** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
82257*/
82258static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
82259  int rc = SQLITE_OK;
82260  IncrMerger *pIncr = pReadr->pIncr;
82261  SortSubtask *pTask = pIncr->pTask;
82262  sqlite3 *db = pTask->pSorter->db;
82263
82264  /* eMode is always INCRINIT_NORMAL in single-threaded mode */
82265  assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
82266
82267  rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
82268
82269  /* Set up the required files for pIncr. A multi-theaded IncrMerge object
82270  ** requires two temp files to itself, whereas a single-threaded object
82271  ** only requires a region of pTask->file2. */
82272  if( rc==SQLITE_OK ){
82273    int mxSz = pIncr->mxSz;
82274#if SQLITE_MAX_WORKER_THREADS>0
82275    if( pIncr->bUseThread ){
82276      rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
82277      if( rc==SQLITE_OK ){
82278        rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
82279      }
82280    }else
82281#endif
82282    /*if( !pIncr->bUseThread )*/{
82283      if( pTask->file2.pFd==0 ){
82284        assert( pTask->file2.iEof>0 );
82285        rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
82286        pTask->file2.iEof = 0;
82287      }
82288      if( rc==SQLITE_OK ){
82289        pIncr->aFile[1].pFd = pTask->file2.pFd;
82290        pIncr->iStartOff = pTask->file2.iEof;
82291        pTask->file2.iEof += mxSz;
82292      }
82293    }
82294  }
82295
82296#if SQLITE_MAX_WORKER_THREADS>0
82297  if( rc==SQLITE_OK && pIncr->bUseThread ){
82298    /* Use the current thread to populate aFile[1], even though this
82299    ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
82300    ** then this function is already running in background thread
82301    ** pIncr->pTask->thread.
82302    **
82303    ** If this is the INCRINIT_ROOT object, then it is running in the
82304    ** main VDBE thread. But that is Ok, as that thread cannot return
82305    ** control to the VDBE or proceed with anything useful until the
82306    ** first results are ready from this merger object anyway.
82307    */
82308    assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
82309    rc = vdbeIncrPopulate(pIncr);
82310  }
82311#endif
82312
82313  if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
82314    rc = vdbePmaReaderNext(pReadr);
82315  }
82316
82317  return rc;
82318}
82319
82320#if SQLITE_MAX_WORKER_THREADS>0
82321/*
82322** The main routine for vdbePmaReaderIncrMergeInit() operations run in
82323** background threads.
82324*/
82325static void *vdbePmaReaderBgIncrInit(void *pCtx){
82326  PmaReader *pReader = (PmaReader*)pCtx;
82327  void *pRet = SQLITE_INT_TO_PTR(
82328                  vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
82329               );
82330  pReader->pIncr->pTask->bDone = 1;
82331  return pRet;
82332}
82333#endif
82334
82335/*
82336** If the PmaReader passed as the first argument is not an incremental-reader
82337** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
82338** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
82339** this routine to initialize the incremental merge.
82340**
82341** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
82342** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
82343** Or, if the IncrMerger is single threaded, the same function is called
82344** using the current thread.
82345*/
82346static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
82347  IncrMerger *pIncr = pReadr->pIncr;   /* Incremental merger */
82348  int rc = SQLITE_OK;                  /* Return code */
82349  if( pIncr ){
82350#if SQLITE_MAX_WORKER_THREADS>0
82351    assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
82352    if( pIncr->bUseThread ){
82353      void *pCtx = (void*)pReadr;
82354      rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
82355    }else
82356#endif
82357    {
82358      rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
82359    }
82360  }
82361  return rc;
82362}
82363
82364/*
82365** Allocate a new MergeEngine object to merge the contents of nPMA level-0
82366** PMAs from pTask->file. If no error occurs, set *ppOut to point to
82367** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
82368** to NULL and return an SQLite error code.
82369**
82370** When this function is called, *piOffset is set to the offset of the
82371** first PMA to read from pTask->file. Assuming no error occurs, it is
82372** set to the offset immediately following the last byte of the last
82373** PMA before returning. If an error does occur, then the final value of
82374** *piOffset is undefined.
82375*/
82376static int vdbeMergeEngineLevel0(
82377  SortSubtask *pTask,             /* Sorter task to read from */
82378  int nPMA,                       /* Number of PMAs to read */
82379  i64 *piOffset,                  /* IN/OUT: Readr offset in pTask->file */
82380  MergeEngine **ppOut             /* OUT: New merge-engine */
82381){
82382  MergeEngine *pNew;              /* Merge engine to return */
82383  i64 iOff = *piOffset;
82384  int i;
82385  int rc = SQLITE_OK;
82386
82387  *ppOut = pNew = vdbeMergeEngineNew(nPMA);
82388  if( pNew==0 ) rc = SQLITE_NOMEM;
82389
82390  for(i=0; i<nPMA && rc==SQLITE_OK; i++){
82391    i64 nDummy;
82392    PmaReader *pReadr = &pNew->aReadr[i];
82393    rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
82394    iOff = pReadr->iEof;
82395  }
82396
82397  if( rc!=SQLITE_OK ){
82398    vdbeMergeEngineFree(pNew);
82399    *ppOut = 0;
82400  }
82401  *piOffset = iOff;
82402  return rc;
82403}
82404
82405/*
82406** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
82407** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
82408**
82409** i.e.
82410**
82411**   nPMA<=16    -> TreeDepth() == 0
82412**   nPMA<=256   -> TreeDepth() == 1
82413**   nPMA<=65536 -> TreeDepth() == 2
82414*/
82415static int vdbeSorterTreeDepth(int nPMA){
82416  int nDepth = 0;
82417  i64 nDiv = SORTER_MAX_MERGE_COUNT;
82418  while( nDiv < (i64)nPMA ){
82419    nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
82420    nDepth++;
82421  }
82422  return nDepth;
82423}
82424
82425/*
82426** pRoot is the root of an incremental merge-tree with depth nDepth (according
82427** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
82428** tree, counting from zero. This function adds pLeaf to the tree.
82429**
82430** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
82431** code is returned and pLeaf is freed.
82432*/
82433static int vdbeSorterAddToTree(
82434  SortSubtask *pTask,             /* Task context */
82435  int nDepth,                     /* Depth of tree according to TreeDepth() */
82436  int iSeq,                       /* Sequence number of leaf within tree */
82437  MergeEngine *pRoot,             /* Root of tree */
82438  MergeEngine *pLeaf              /* Leaf to add to tree */
82439){
82440  int rc = SQLITE_OK;
82441  int nDiv = 1;
82442  int i;
82443  MergeEngine *p = pRoot;
82444  IncrMerger *pIncr;
82445
82446  rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
82447
82448  for(i=1; i<nDepth; i++){
82449    nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
82450  }
82451
82452  for(i=1; i<nDepth && rc==SQLITE_OK; i++){
82453    int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
82454    PmaReader *pReadr = &p->aReadr[iIter];
82455
82456    if( pReadr->pIncr==0 ){
82457      MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
82458      if( pNew==0 ){
82459        rc = SQLITE_NOMEM;
82460      }else{
82461        rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
82462      }
82463    }
82464    if( rc==SQLITE_OK ){
82465      p = pReadr->pIncr->pMerger;
82466      nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
82467    }
82468  }
82469
82470  if( rc==SQLITE_OK ){
82471    p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
82472  }else{
82473    vdbeIncrFree(pIncr);
82474  }
82475  return rc;
82476}
82477
82478/*
82479** This function is called as part of a SorterRewind() operation on a sorter
82480** that has already written two or more level-0 PMAs to one or more temp
82481** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
82482** can be used to incrementally merge all PMAs on disk.
82483**
82484** If successful, SQLITE_OK is returned and *ppOut set to point to the
82485** MergeEngine object at the root of the tree before returning. Or, if an
82486** error occurs, an SQLite error code is returned and the final value
82487** of *ppOut is undefined.
82488*/
82489static int vdbeSorterMergeTreeBuild(
82490  VdbeSorter *pSorter,       /* The VDBE cursor that implements the sort */
82491  MergeEngine **ppOut        /* Write the MergeEngine here */
82492){
82493  MergeEngine *pMain = 0;
82494  int rc = SQLITE_OK;
82495  int iTask;
82496
82497#if SQLITE_MAX_WORKER_THREADS>0
82498  /* If the sorter uses more than one task, then create the top-level
82499  ** MergeEngine here. This MergeEngine will read data from exactly
82500  ** one PmaReader per sub-task.  */
82501  assert( pSorter->bUseThreads || pSorter->nTask==1 );
82502  if( pSorter->nTask>1 ){
82503    pMain = vdbeMergeEngineNew(pSorter->nTask);
82504    if( pMain==0 ) rc = SQLITE_NOMEM;
82505  }
82506#endif
82507
82508  for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
82509    SortSubtask *pTask = &pSorter->aTask[iTask];
82510    assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
82511    if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
82512      MergeEngine *pRoot = 0;     /* Root node of tree for this task */
82513      int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
82514      i64 iReadOff = 0;
82515
82516      if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
82517        rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
82518      }else{
82519        int i;
82520        int iSeq = 0;
82521        pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
82522        if( pRoot==0 ) rc = SQLITE_NOMEM;
82523        for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
82524          MergeEngine *pMerger = 0; /* New level-0 PMA merger */
82525          int nReader;              /* Number of level-0 PMAs to merge */
82526
82527          nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
82528          rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
82529          if( rc==SQLITE_OK ){
82530            rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
82531          }
82532        }
82533      }
82534
82535      if( rc==SQLITE_OK ){
82536#if SQLITE_MAX_WORKER_THREADS>0
82537        if( pMain!=0 ){
82538          rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
82539        }else
82540#endif
82541        {
82542          assert( pMain==0 );
82543          pMain = pRoot;
82544        }
82545      }else{
82546        vdbeMergeEngineFree(pRoot);
82547      }
82548    }
82549  }
82550
82551  if( rc!=SQLITE_OK ){
82552    vdbeMergeEngineFree(pMain);
82553    pMain = 0;
82554  }
82555  *ppOut = pMain;
82556  return rc;
82557}
82558
82559/*
82560** This function is called as part of an sqlite3VdbeSorterRewind() operation
82561** on a sorter that has written two or more PMAs to temporary files. It sets
82562** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
82563** (for multi-threaded sorters) so that it can be used to iterate through
82564** all records stored in the sorter.
82565**
82566** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
82567*/
82568static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
82569  int rc;                         /* Return code */
82570  SortSubtask *pTask0 = &pSorter->aTask[0];
82571  MergeEngine *pMain = 0;
82572#if SQLITE_MAX_WORKER_THREADS
82573  sqlite3 *db = pTask0->pSorter->db;
82574  int i;
82575  SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
82576  for(i=0; i<pSorter->nTask; i++){
82577    pSorter->aTask[i].xCompare = xCompare;
82578  }
82579#endif
82580
82581  rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
82582  if( rc==SQLITE_OK ){
82583#if SQLITE_MAX_WORKER_THREADS
82584    assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
82585    if( pSorter->bUseThreads ){
82586      int iTask;
82587      PmaReader *pReadr = 0;
82588      SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
82589      rc = vdbeSortAllocUnpacked(pLast);
82590      if( rc==SQLITE_OK ){
82591        pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
82592        pSorter->pReader = pReadr;
82593        if( pReadr==0 ) rc = SQLITE_NOMEM;
82594      }
82595      if( rc==SQLITE_OK ){
82596        rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
82597        if( rc==SQLITE_OK ){
82598          vdbeIncrMergerSetThreads(pReadr->pIncr);
82599          for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
82600            IncrMerger *pIncr;
82601            if( (pIncr = pMain->aReadr[iTask].pIncr) ){
82602              vdbeIncrMergerSetThreads(pIncr);
82603              assert( pIncr->pTask!=pLast );
82604            }
82605          }
82606          for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
82607            /* Check that:
82608            **
82609            **   a) The incremental merge object is configured to use the
82610            **      right task, and
82611            **   b) If it is using task (nTask-1), it is configured to run
82612            **      in single-threaded mode. This is important, as the
82613            **      root merge (INCRINIT_ROOT) will be using the same task
82614            **      object.
82615            */
82616            PmaReader *p = &pMain->aReadr[iTask];
82617            assert( p->pIncr==0 || (
82618                (p->pIncr->pTask==&pSorter->aTask[iTask])             /* a */
82619             && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0)  /* b */
82620            ));
82621            rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
82622          }
82623        }
82624        pMain = 0;
82625      }
82626      if( rc==SQLITE_OK ){
82627        rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
82628      }
82629    }else
82630#endif
82631    {
82632      rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
82633      pSorter->pMerger = pMain;
82634      pMain = 0;
82635    }
82636  }
82637
82638  if( rc!=SQLITE_OK ){
82639    vdbeMergeEngineFree(pMain);
82640  }
82641  return rc;
82642}
82643
82644
82645/*
82646** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
82647** this function is called to prepare for iterating through the records
82648** in sorted order.
82649*/
82650SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
82651  VdbeSorter *pSorter = pCsr->pSorter;
82652  int rc = SQLITE_OK;             /* Return code */
82653
82654  assert( pSorter );
82655
82656  /* If no data has been written to disk, then do not do so now. Instead,
82657  ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
82658  ** from the in-memory list.  */
82659  if( pSorter->bUsePMA==0 ){
82660    if( pSorter->list.pList ){
82661      *pbEof = 0;
82662      rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
82663    }else{
82664      *pbEof = 1;
82665    }
82666    return rc;
82667  }
82668
82669  /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
82670  ** function flushes the contents of memory to disk, it immediately always
82671  ** creates a new list consisting of a single key immediately afterwards.
82672  ** So the list is never empty at this point.  */
82673  assert( pSorter->list.pList );
82674  rc = vdbeSorterFlushPMA(pSorter);
82675
82676  /* Join all threads */
82677  rc = vdbeSorterJoinAll(pSorter, rc);
82678
82679  vdbeSorterRewindDebug("rewind");
82680
82681  /* Assuming no errors have occurred, set up a merger structure to
82682  ** incrementally read and merge all remaining PMAs.  */
82683  assert( pSorter->pReader==0 );
82684  if( rc==SQLITE_OK ){
82685    rc = vdbeSorterSetupMerge(pSorter);
82686    *pbEof = 0;
82687  }
82688
82689  vdbeSorterRewindDebug("rewinddone");
82690  return rc;
82691}
82692
82693/*
82694** Advance to the next element in the sorter.
82695*/
82696SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
82697  VdbeSorter *pSorter = pCsr->pSorter;
82698  int rc;                         /* Return code */
82699
82700  assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
82701  if( pSorter->bUsePMA ){
82702    assert( pSorter->pReader==0 || pSorter->pMerger==0 );
82703    assert( pSorter->bUseThreads==0 || pSorter->pReader );
82704    assert( pSorter->bUseThreads==1 || pSorter->pMerger );
82705#if SQLITE_MAX_WORKER_THREADS>0
82706    if( pSorter->bUseThreads ){
82707      rc = vdbePmaReaderNext(pSorter->pReader);
82708      *pbEof = (pSorter->pReader->pFd==0);
82709    }else
82710#endif
82711    /*if( !pSorter->bUseThreads )*/ {
82712      assert( pSorter->pMerger!=0 );
82713      assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
82714      rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
82715    }
82716  }else{
82717    SorterRecord *pFree = pSorter->list.pList;
82718    pSorter->list.pList = pFree->u.pNext;
82719    pFree->u.pNext = 0;
82720    if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
82721    *pbEof = !pSorter->list.pList;
82722    rc = SQLITE_OK;
82723  }
82724  return rc;
82725}
82726
82727/*
82728** Return a pointer to a buffer owned by the sorter that contains the
82729** current key.
82730*/
82731static void *vdbeSorterRowkey(
82732  const VdbeSorter *pSorter,      /* Sorter object */
82733  int *pnKey                      /* OUT: Size of current key in bytes */
82734){
82735  void *pKey;
82736  if( pSorter->bUsePMA ){
82737    PmaReader *pReader;
82738#if SQLITE_MAX_WORKER_THREADS>0
82739    if( pSorter->bUseThreads ){
82740      pReader = pSorter->pReader;
82741    }else
82742#endif
82743    /*if( !pSorter->bUseThreads )*/{
82744      pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
82745    }
82746    *pnKey = pReader->nKey;
82747    pKey = pReader->aKey;
82748  }else{
82749    *pnKey = pSorter->list.pList->nVal;
82750    pKey = SRVAL(pSorter->list.pList);
82751  }
82752  return pKey;
82753}
82754
82755/*
82756** Copy the current sorter key into the memory cell pOut.
82757*/
82758SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
82759  VdbeSorter *pSorter = pCsr->pSorter;
82760  void *pKey; int nKey;           /* Sorter key to copy into pOut */
82761
82762  pKey = vdbeSorterRowkey(pSorter, &nKey);
82763  if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
82764    return SQLITE_NOMEM;
82765  }
82766  pOut->n = nKey;
82767  MemSetTypeFlag(pOut, MEM_Blob);
82768  memcpy(pOut->z, pKey, nKey);
82769
82770  return SQLITE_OK;
82771}
82772
82773/*
82774** Compare the key in memory cell pVal with the key that the sorter cursor
82775** passed as the first argument currently points to. For the purposes of
82776** the comparison, ignore the rowid field at the end of each record.
82777**
82778** If the sorter cursor key contains any NULL values, consider it to be
82779** less than pVal. Even if pVal also contains NULL values.
82780**
82781** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
82782** Otherwise, set *pRes to a negative, zero or positive value if the
82783** key in pVal is smaller than, equal to or larger than the current sorter
82784** key.
82785**
82786** This routine forms the core of the OP_SorterCompare opcode, which in
82787** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
82788*/
82789SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
82790  const VdbeCursor *pCsr,         /* Sorter cursor */
82791  Mem *pVal,                      /* Value to compare to current sorter key */
82792  int nKeyCol,                    /* Compare this many columns */
82793  int *pRes                       /* OUT: Result of comparison */
82794){
82795  VdbeSorter *pSorter = pCsr->pSorter;
82796  UnpackedRecord *r2 = pSorter->pUnpacked;
82797  KeyInfo *pKeyInfo = pCsr->pKeyInfo;
82798  int i;
82799  void *pKey; int nKey;           /* Sorter key to compare pVal with */
82800
82801  if( r2==0 ){
82802    char *p;
82803    r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p);
82804    assert( pSorter->pUnpacked==(UnpackedRecord*)p );
82805    if( r2==0 ) return SQLITE_NOMEM;
82806    r2->nField = nKeyCol;
82807  }
82808  assert( r2->nField==nKeyCol );
82809
82810  pKey = vdbeSorterRowkey(pSorter, &nKey);
82811  sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
82812  for(i=0; i<nKeyCol; i++){
82813    if( r2->aMem[i].flags & MEM_Null ){
82814      *pRes = -1;
82815      return SQLITE_OK;
82816    }
82817  }
82818
82819  *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
82820  return SQLITE_OK;
82821}
82822
82823/************** End of vdbesort.c ********************************************/
82824/************** Begin file journal.c *****************************************/
82825/*
82826** 2007 August 22
82827**
82828** The author disclaims copyright to this source code.  In place of
82829** a legal notice, here is a blessing:
82830**
82831**    May you do good and not evil.
82832**    May you find forgiveness for yourself and forgive others.
82833**    May you share freely, never taking more than you give.
82834**
82835*************************************************************************
82836**
82837** This file implements a special kind of sqlite3_file object used
82838** by SQLite to create journal files if the atomic-write optimization
82839** is enabled.
82840**
82841** The distinctive characteristic of this sqlite3_file is that the
82842** actual on disk file is created lazily. When the file is created,
82843** the caller specifies a buffer size for an in-memory buffer to
82844** be used to service read() and write() requests. The actual file
82845** on disk is not created or populated until either:
82846**
82847**   1) The in-memory representation grows too large for the allocated
82848**      buffer, or
82849**   2) The sqlite3JournalCreate() function is called.
82850*/
82851#ifdef SQLITE_ENABLE_ATOMIC_WRITE
82852/* #include "sqliteInt.h" */
82853
82854
82855/*
82856** A JournalFile object is a subclass of sqlite3_file used by
82857** as an open file handle for journal files.
82858*/
82859struct JournalFile {
82860  sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
82861  int nBuf;                       /* Size of zBuf[] in bytes */
82862  char *zBuf;                     /* Space to buffer journal writes */
82863  int iSize;                      /* Amount of zBuf[] currently used */
82864  int flags;                      /* xOpen flags */
82865  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
82866  sqlite3_file *pReal;            /* The "real" underlying file descriptor */
82867  const char *zJournal;           /* Name of the journal file */
82868};
82869typedef struct JournalFile JournalFile;
82870
82871/*
82872** If it does not already exists, create and populate the on-disk file
82873** for JournalFile p.
82874*/
82875static int createFile(JournalFile *p){
82876  int rc = SQLITE_OK;
82877  if( !p->pReal ){
82878    sqlite3_file *pReal = (sqlite3_file *)&p[1];
82879    rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
82880    if( rc==SQLITE_OK ){
82881      p->pReal = pReal;
82882      if( p->iSize>0 ){
82883        assert(p->iSize<=p->nBuf);
82884        rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
82885      }
82886      if( rc!=SQLITE_OK ){
82887        /* If an error occurred while writing to the file, close it before
82888        ** returning. This way, SQLite uses the in-memory journal data to
82889        ** roll back changes made to the internal page-cache before this
82890        ** function was called.  */
82891        sqlite3OsClose(pReal);
82892        p->pReal = 0;
82893      }
82894    }
82895  }
82896  return rc;
82897}
82898
82899/*
82900** Close the file.
82901*/
82902static int jrnlClose(sqlite3_file *pJfd){
82903  JournalFile *p = (JournalFile *)pJfd;
82904  if( p->pReal ){
82905    sqlite3OsClose(p->pReal);
82906  }
82907  sqlite3_free(p->zBuf);
82908  return SQLITE_OK;
82909}
82910
82911/*
82912** Read data from the file.
82913*/
82914static int jrnlRead(
82915  sqlite3_file *pJfd,    /* The journal file from which to read */
82916  void *zBuf,            /* Put the results here */
82917  int iAmt,              /* Number of bytes to read */
82918  sqlite_int64 iOfst     /* Begin reading at this offset */
82919){
82920  int rc = SQLITE_OK;
82921  JournalFile *p = (JournalFile *)pJfd;
82922  if( p->pReal ){
82923    rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
82924  }else if( (iAmt+iOfst)>p->iSize ){
82925    rc = SQLITE_IOERR_SHORT_READ;
82926  }else{
82927    memcpy(zBuf, &p->zBuf[iOfst], iAmt);
82928  }
82929  return rc;
82930}
82931
82932/*
82933** Write data to the file.
82934*/
82935static int jrnlWrite(
82936  sqlite3_file *pJfd,    /* The journal file into which to write */
82937  const void *zBuf,      /* Take data to be written from here */
82938  int iAmt,              /* Number of bytes to write */
82939  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
82940){
82941  int rc = SQLITE_OK;
82942  JournalFile *p = (JournalFile *)pJfd;
82943  if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
82944    rc = createFile(p);
82945  }
82946  if( rc==SQLITE_OK ){
82947    if( p->pReal ){
82948      rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
82949    }else{
82950      memcpy(&p->zBuf[iOfst], zBuf, iAmt);
82951      if( p->iSize<(iOfst+iAmt) ){
82952        p->iSize = (iOfst+iAmt);
82953      }
82954    }
82955  }
82956  return rc;
82957}
82958
82959/*
82960** Truncate the file.
82961*/
82962static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
82963  int rc = SQLITE_OK;
82964  JournalFile *p = (JournalFile *)pJfd;
82965  if( p->pReal ){
82966    rc = sqlite3OsTruncate(p->pReal, size);
82967  }else if( size<p->iSize ){
82968    p->iSize = size;
82969  }
82970  return rc;
82971}
82972
82973/*
82974** Sync the file.
82975*/
82976static int jrnlSync(sqlite3_file *pJfd, int flags){
82977  int rc;
82978  JournalFile *p = (JournalFile *)pJfd;
82979  if( p->pReal ){
82980    rc = sqlite3OsSync(p->pReal, flags);
82981  }else{
82982    rc = SQLITE_OK;
82983  }
82984  return rc;
82985}
82986
82987/*
82988** Query the size of the file in bytes.
82989*/
82990static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
82991  int rc = SQLITE_OK;
82992  JournalFile *p = (JournalFile *)pJfd;
82993  if( p->pReal ){
82994    rc = sqlite3OsFileSize(p->pReal, pSize);
82995  }else{
82996    *pSize = (sqlite_int64) p->iSize;
82997  }
82998  return rc;
82999}
83000
83001/*
83002** Table of methods for JournalFile sqlite3_file object.
83003*/
83004static struct sqlite3_io_methods JournalFileMethods = {
83005  1,             /* iVersion */
83006  jrnlClose,     /* xClose */
83007  jrnlRead,      /* xRead */
83008  jrnlWrite,     /* xWrite */
83009  jrnlTruncate,  /* xTruncate */
83010  jrnlSync,      /* xSync */
83011  jrnlFileSize,  /* xFileSize */
83012  0,             /* xLock */
83013  0,             /* xUnlock */
83014  0,             /* xCheckReservedLock */
83015  0,             /* xFileControl */
83016  0,             /* xSectorSize */
83017  0,             /* xDeviceCharacteristics */
83018  0,             /* xShmMap */
83019  0,             /* xShmLock */
83020  0,             /* xShmBarrier */
83021  0              /* xShmUnmap */
83022};
83023
83024/*
83025** Open a journal file.
83026*/
83027SQLITE_PRIVATE int sqlite3JournalOpen(
83028  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
83029  const char *zName,         /* Name of the journal file */
83030  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
83031  int flags,                 /* Opening flags */
83032  int nBuf                   /* Bytes buffered before opening the file */
83033){
83034  JournalFile *p = (JournalFile *)pJfd;
83035  memset(p, 0, sqlite3JournalSize(pVfs));
83036  if( nBuf>0 ){
83037    p->zBuf = sqlite3MallocZero(nBuf);
83038    if( !p->zBuf ){
83039      return SQLITE_NOMEM;
83040    }
83041  }else{
83042    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
83043  }
83044  p->pMethod = &JournalFileMethods;
83045  p->nBuf = nBuf;
83046  p->flags = flags;
83047  p->zJournal = zName;
83048  p->pVfs = pVfs;
83049  return SQLITE_OK;
83050}
83051
83052/*
83053** If the argument p points to a JournalFile structure, and the underlying
83054** file has not yet been created, create it now.
83055*/
83056SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
83057  if( p->pMethods!=&JournalFileMethods ){
83058    return SQLITE_OK;
83059  }
83060  return createFile((JournalFile *)p);
83061}
83062
83063/*
83064** The file-handle passed as the only argument is guaranteed to be an open
83065** file. It may or may not be of class JournalFile. If the file is a
83066** JournalFile, and the underlying file on disk has not yet been opened,
83067** return 0. Otherwise, return 1.
83068*/
83069SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
83070  return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
83071}
83072
83073/*
83074** Return the number of bytes required to store a JournalFile that uses vfs
83075** pVfs to create the underlying on-disk files.
83076*/
83077SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
83078  return (pVfs->szOsFile+sizeof(JournalFile));
83079}
83080#endif
83081
83082/************** End of journal.c *********************************************/
83083/************** Begin file memjournal.c **************************************/
83084/*
83085** 2008 October 7
83086**
83087** The author disclaims copyright to this source code.  In place of
83088** a legal notice, here is a blessing:
83089**
83090**    May you do good and not evil.
83091**    May you find forgiveness for yourself and forgive others.
83092**    May you share freely, never taking more than you give.
83093**
83094*************************************************************************
83095**
83096** This file contains code use to implement an in-memory rollback journal.
83097** The in-memory rollback journal is used to journal transactions for
83098** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
83099*/
83100/* #include "sqliteInt.h" */
83101
83102/* Forward references to internal structures */
83103typedef struct MemJournal MemJournal;
83104typedef struct FilePoint FilePoint;
83105typedef struct FileChunk FileChunk;
83106
83107/* Space to hold the rollback journal is allocated in increments of
83108** this many bytes.
83109**
83110** The size chosen is a little less than a power of two.  That way,
83111** the FileChunk object will have a size that almost exactly fills
83112** a power-of-two allocation.  This minimizes wasted space in power-of-two
83113** memory allocators.
83114*/
83115#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
83116
83117/*
83118** The rollback journal is composed of a linked list of these structures.
83119*/
83120struct FileChunk {
83121  FileChunk *pNext;               /* Next chunk in the journal */
83122  u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
83123};
83124
83125/*
83126** An instance of this object serves as a cursor into the rollback journal.
83127** The cursor can be either for reading or writing.
83128*/
83129struct FilePoint {
83130  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
83131  FileChunk *pChunk;              /* Specific chunk into which cursor points */
83132};
83133
83134/*
83135** This subclass is a subclass of sqlite3_file.  Each open memory-journal
83136** is an instance of this class.
83137*/
83138struct MemJournal {
83139  sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
83140  FileChunk *pFirst;              /* Head of in-memory chunk-list */
83141  FilePoint endpoint;             /* Pointer to the end of the file */
83142  FilePoint readpoint;            /* Pointer to the end of the last xRead() */
83143};
83144
83145/*
83146** Read data from the in-memory journal file.  This is the implementation
83147** of the sqlite3_vfs.xRead method.
83148*/
83149static int memjrnlRead(
83150  sqlite3_file *pJfd,    /* The journal file from which to read */
83151  void *zBuf,            /* Put the results here */
83152  int iAmt,              /* Number of bytes to read */
83153  sqlite_int64 iOfst     /* Begin reading at this offset */
83154){
83155  MemJournal *p = (MemJournal *)pJfd;
83156  u8 *zOut = zBuf;
83157  int nRead = iAmt;
83158  int iChunkOffset;
83159  FileChunk *pChunk;
83160
83161  /* SQLite never tries to read past the end of a rollback journal file */
83162  assert( iOfst+iAmt<=p->endpoint.iOffset );
83163
83164  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
83165    sqlite3_int64 iOff = 0;
83166    for(pChunk=p->pFirst;
83167        ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
83168        pChunk=pChunk->pNext
83169    ){
83170      iOff += JOURNAL_CHUNKSIZE;
83171    }
83172  }else{
83173    pChunk = p->readpoint.pChunk;
83174  }
83175
83176  iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
83177  do {
83178    int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
83179    int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
83180    memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
83181    zOut += nCopy;
83182    nRead -= iSpace;
83183    iChunkOffset = 0;
83184  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
83185  p->readpoint.iOffset = iOfst+iAmt;
83186  p->readpoint.pChunk = pChunk;
83187
83188  return SQLITE_OK;
83189}
83190
83191/*
83192** Write data to the file.
83193*/
83194static int memjrnlWrite(
83195  sqlite3_file *pJfd,    /* The journal file into which to write */
83196  const void *zBuf,      /* Take data to be written from here */
83197  int iAmt,              /* Number of bytes to write */
83198  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
83199){
83200  MemJournal *p = (MemJournal *)pJfd;
83201  int nWrite = iAmt;
83202  u8 *zWrite = (u8 *)zBuf;
83203
83204  /* An in-memory journal file should only ever be appended to. Random
83205  ** access writes are not required by sqlite.
83206  */
83207  assert( iOfst==p->endpoint.iOffset );
83208  UNUSED_PARAMETER(iOfst);
83209
83210  while( nWrite>0 ){
83211    FileChunk *pChunk = p->endpoint.pChunk;
83212    int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
83213    int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
83214
83215    if( iChunkOffset==0 ){
83216      /* New chunk is required to extend the file. */
83217      FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
83218      if( !pNew ){
83219        return SQLITE_IOERR_NOMEM;
83220      }
83221      pNew->pNext = 0;
83222      if( pChunk ){
83223        assert( p->pFirst );
83224        pChunk->pNext = pNew;
83225      }else{
83226        assert( !p->pFirst );
83227        p->pFirst = pNew;
83228      }
83229      p->endpoint.pChunk = pNew;
83230    }
83231
83232    memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
83233    zWrite += iSpace;
83234    nWrite -= iSpace;
83235    p->endpoint.iOffset += iSpace;
83236  }
83237
83238  return SQLITE_OK;
83239}
83240
83241/*
83242** Truncate the file.
83243*/
83244static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
83245  MemJournal *p = (MemJournal *)pJfd;
83246  FileChunk *pChunk;
83247  assert(size==0);
83248  UNUSED_PARAMETER(size);
83249  pChunk = p->pFirst;
83250  while( pChunk ){
83251    FileChunk *pTmp = pChunk;
83252    pChunk = pChunk->pNext;
83253    sqlite3_free(pTmp);
83254  }
83255  sqlite3MemJournalOpen(pJfd);
83256  return SQLITE_OK;
83257}
83258
83259/*
83260** Close the file.
83261*/
83262static int memjrnlClose(sqlite3_file *pJfd){
83263  memjrnlTruncate(pJfd, 0);
83264  return SQLITE_OK;
83265}
83266
83267
83268/*
83269** Sync the file.
83270**
83271** Syncing an in-memory journal is a no-op.  And, in fact, this routine
83272** is never called in a working implementation.  This implementation
83273** exists purely as a contingency, in case some malfunction in some other
83274** part of SQLite causes Sync to be called by mistake.
83275*/
83276static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
83277  UNUSED_PARAMETER2(NotUsed, NotUsed2);
83278  return SQLITE_OK;
83279}
83280
83281/*
83282** Query the size of the file in bytes.
83283*/
83284static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
83285  MemJournal *p = (MemJournal *)pJfd;
83286  *pSize = (sqlite_int64) p->endpoint.iOffset;
83287  return SQLITE_OK;
83288}
83289
83290/*
83291** Table of methods for MemJournal sqlite3_file object.
83292*/
83293static const struct sqlite3_io_methods MemJournalMethods = {
83294  1,                /* iVersion */
83295  memjrnlClose,     /* xClose */
83296  memjrnlRead,      /* xRead */
83297  memjrnlWrite,     /* xWrite */
83298  memjrnlTruncate,  /* xTruncate */
83299  memjrnlSync,      /* xSync */
83300  memjrnlFileSize,  /* xFileSize */
83301  0,                /* xLock */
83302  0,                /* xUnlock */
83303  0,                /* xCheckReservedLock */
83304  0,                /* xFileControl */
83305  0,                /* xSectorSize */
83306  0,                /* xDeviceCharacteristics */
83307  0,                /* xShmMap */
83308  0,                /* xShmLock */
83309  0,                /* xShmBarrier */
83310  0,                /* xShmUnmap */
83311  0,                /* xFetch */
83312  0                 /* xUnfetch */
83313};
83314
83315/*
83316** Open a journal file.
83317*/
83318SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
83319  MemJournal *p = (MemJournal *)pJfd;
83320  assert( EIGHT_BYTE_ALIGNMENT(p) );
83321  memset(p, 0, sqlite3MemJournalSize());
83322  p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
83323}
83324
83325/*
83326** Return true if the file-handle passed as an argument is
83327** an in-memory journal
83328*/
83329SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
83330  return pJfd->pMethods==&MemJournalMethods;
83331}
83332
83333/*
83334** Return the number of bytes required to store a MemJournal file descriptor.
83335*/
83336SQLITE_PRIVATE int sqlite3MemJournalSize(void){
83337  return sizeof(MemJournal);
83338}
83339
83340/************** End of memjournal.c ******************************************/
83341/************** Begin file walker.c ******************************************/
83342/*
83343** 2008 August 16
83344**
83345** The author disclaims copyright to this source code.  In place of
83346** a legal notice, here is a blessing:
83347**
83348**    May you do good and not evil.
83349**    May you find forgiveness for yourself and forgive others.
83350**    May you share freely, never taking more than you give.
83351**
83352*************************************************************************
83353** This file contains routines used for walking the parser tree for
83354** an SQL statement.
83355*/
83356/* #include "sqliteInt.h" */
83357/* #include <stdlib.h> */
83358/* #include <string.h> */
83359
83360
83361/*
83362** Walk an expression tree.  Invoke the callback once for each node
83363** of the expression, while descending.  (In other words, the callback
83364** is invoked before visiting children.)
83365**
83366** The return value from the callback should be one of the WRC_*
83367** constants to specify how to proceed with the walk.
83368**
83369**    WRC_Continue      Continue descending down the tree.
83370**
83371**    WRC_Prune         Do not descend into child nodes.  But allow
83372**                      the walk to continue with sibling nodes.
83373**
83374**    WRC_Abort         Do no more callbacks.  Unwind the stack and
83375**                      return the top-level walk call.
83376**
83377** The return value from this routine is WRC_Abort to abandon the tree walk
83378** and WRC_Continue to continue.
83379*/
83380SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
83381  int rc;
83382  if( pExpr==0 ) return WRC_Continue;
83383  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
83384  testcase( ExprHasProperty(pExpr, EP_Reduced) );
83385  rc = pWalker->xExprCallback(pWalker, pExpr);
83386  if( rc==WRC_Continue
83387              && !ExprHasProperty(pExpr,EP_TokenOnly) ){
83388    if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
83389    if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
83390    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
83391      if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
83392    }else{
83393      if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
83394    }
83395  }
83396  return rc & WRC_Abort;
83397}
83398
83399/*
83400** Call sqlite3WalkExpr() for every expression in list p or until
83401** an abort request is seen.
83402*/
83403SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
83404  int i;
83405  struct ExprList_item *pItem;
83406  if( p ){
83407    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
83408      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
83409    }
83410  }
83411  return WRC_Continue;
83412}
83413
83414/*
83415** Walk all expressions associated with SELECT statement p.  Do
83416** not invoke the SELECT callback on p, but do (of course) invoke
83417** any expr callbacks and SELECT callbacks that come from subqueries.
83418** Return WRC_Abort or WRC_Continue.
83419*/
83420SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
83421  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
83422  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
83423  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
83424  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
83425  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
83426  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
83427  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
83428  return WRC_Continue;
83429}
83430
83431/*
83432** Walk the parse trees associated with all subqueries in the
83433** FROM clause of SELECT statement p.  Do not invoke the select
83434** callback on p, but do invoke it on each FROM clause subquery
83435** and on any subqueries further down in the tree.  Return
83436** WRC_Abort or WRC_Continue;
83437*/
83438SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
83439  SrcList *pSrc;
83440  int i;
83441  struct SrcList_item *pItem;
83442
83443  pSrc = p->pSrc;
83444  if( ALWAYS(pSrc) ){
83445    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
83446      if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
83447        return WRC_Abort;
83448      }
83449      if( pItem->fg.isTabFunc
83450       && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
83451      ){
83452        return WRC_Abort;
83453      }
83454    }
83455  }
83456  return WRC_Continue;
83457}
83458
83459/*
83460** Call sqlite3WalkExpr() for every expression in Select statement p.
83461** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
83462** on the compound select chain, p->pPrior.
83463**
83464** If it is not NULL, the xSelectCallback() callback is invoked before
83465** the walk of the expressions and FROM clause. The xSelectCallback2()
83466** method, if it is not NULL, is invoked following the walk of the
83467** expressions and FROM clause.
83468**
83469** Return WRC_Continue under normal conditions.  Return WRC_Abort if
83470** there is an abort request.
83471**
83472** If the Walker does not have an xSelectCallback() then this routine
83473** is a no-op returning WRC_Continue.
83474*/
83475SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
83476  int rc;
83477  if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
83478    return WRC_Continue;
83479  }
83480  rc = WRC_Continue;
83481  pWalker->walkerDepth++;
83482  while( p ){
83483    if( pWalker->xSelectCallback ){
83484       rc = pWalker->xSelectCallback(pWalker, p);
83485       if( rc ) break;
83486    }
83487    if( sqlite3WalkSelectExpr(pWalker, p)
83488     || sqlite3WalkSelectFrom(pWalker, p)
83489    ){
83490      pWalker->walkerDepth--;
83491      return WRC_Abort;
83492    }
83493    if( pWalker->xSelectCallback2 ){
83494      pWalker->xSelectCallback2(pWalker, p);
83495    }
83496    p = p->pPrior;
83497  }
83498  pWalker->walkerDepth--;
83499  return rc & WRC_Abort;
83500}
83501
83502/************** End of walker.c **********************************************/
83503/************** Begin file resolve.c *****************************************/
83504/*
83505** 2008 August 18
83506**
83507** The author disclaims copyright to this source code.  In place of
83508** a legal notice, here is a blessing:
83509**
83510**    May you do good and not evil.
83511**    May you find forgiveness for yourself and forgive others.
83512**    May you share freely, never taking more than you give.
83513**
83514*************************************************************************
83515**
83516** This file contains routines used for walking the parser tree and
83517** resolve all identifiers by associating them with a particular
83518** table and column.
83519*/
83520/* #include "sqliteInt.h" */
83521/* #include <stdlib.h> */
83522/* #include <string.h> */
83523
83524/*
83525** Walk the expression tree pExpr and increase the aggregate function
83526** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
83527** This needs to occur when copying a TK_AGG_FUNCTION node from an
83528** outer query into an inner subquery.
83529**
83530** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
83531** is a helper function - a callback for the tree walker.
83532*/
83533static int incrAggDepth(Walker *pWalker, Expr *pExpr){
83534  if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
83535  return WRC_Continue;
83536}
83537static void incrAggFunctionDepth(Expr *pExpr, int N){
83538  if( N>0 ){
83539    Walker w;
83540    memset(&w, 0, sizeof(w));
83541    w.xExprCallback = incrAggDepth;
83542    w.u.n = N;
83543    sqlite3WalkExpr(&w, pExpr);
83544  }
83545}
83546
83547/*
83548** Turn the pExpr expression into an alias for the iCol-th column of the
83549** result set in pEList.
83550**
83551** If the reference is followed by a COLLATE operator, then make sure
83552** the COLLATE operator is preserved.  For example:
83553**
83554**     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
83555**
83556** Should be transformed into:
83557**
83558**     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
83559**
83560** The nSubquery parameter specifies how many levels of subquery the
83561** alias is removed from the original expression.  The usual value is
83562** zero but it might be more if the alias is contained within a subquery
83563** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
83564** structures must be increased by the nSubquery amount.
83565*/
83566static void resolveAlias(
83567  Parse *pParse,         /* Parsing context */
83568  ExprList *pEList,      /* A result set */
83569  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
83570  Expr *pExpr,           /* Transform this into an alias to the result set */
83571  const char *zType,     /* "GROUP" or "ORDER" or "" */
83572  int nSubquery          /* Number of subqueries that the label is moving */
83573){
83574  Expr *pOrig;           /* The iCol-th column of the result set */
83575  Expr *pDup;            /* Copy of pOrig */
83576  sqlite3 *db;           /* The database connection */
83577
83578  assert( iCol>=0 && iCol<pEList->nExpr );
83579  pOrig = pEList->a[iCol].pExpr;
83580  assert( pOrig!=0 );
83581  db = pParse->db;
83582  pDup = sqlite3ExprDup(db, pOrig, 0);
83583  if( pDup==0 ) return;
83584  if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
83585  if( pExpr->op==TK_COLLATE ){
83586    pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
83587  }
83588  ExprSetProperty(pDup, EP_Alias);
83589
83590  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
83591  ** prevents ExprDelete() from deleting the Expr structure itself,
83592  ** allowing it to be repopulated by the memcpy() on the following line.
83593  ** The pExpr->u.zToken might point into memory that will be freed by the
83594  ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
83595  ** make a copy of the token before doing the sqlite3DbFree().
83596  */
83597  ExprSetProperty(pExpr, EP_Static);
83598  sqlite3ExprDelete(db, pExpr);
83599  memcpy(pExpr, pDup, sizeof(*pExpr));
83600  if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
83601    assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
83602    pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
83603    pExpr->flags |= EP_MemToken;
83604  }
83605  sqlite3DbFree(db, pDup);
83606}
83607
83608
83609/*
83610** Return TRUE if the name zCol occurs anywhere in the USING clause.
83611**
83612** Return FALSE if the USING clause is NULL or if it does not contain
83613** zCol.
83614*/
83615static int nameInUsingClause(IdList *pUsing, const char *zCol){
83616  if( pUsing ){
83617    int k;
83618    for(k=0; k<pUsing->nId; k++){
83619      if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
83620    }
83621  }
83622  return 0;
83623}
83624
83625/*
83626** Subqueries stores the original database, table and column names for their
83627** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
83628** Check to see if the zSpan given to this routine matches the zDb, zTab,
83629** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
83630** match anything.
83631*/
83632SQLITE_PRIVATE int sqlite3MatchSpanName(
83633  const char *zSpan,
83634  const char *zCol,
83635  const char *zTab,
83636  const char *zDb
83637){
83638  int n;
83639  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
83640  if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
83641    return 0;
83642  }
83643  zSpan += n+1;
83644  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
83645  if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
83646    return 0;
83647  }
83648  zSpan += n+1;
83649  if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
83650    return 0;
83651  }
83652  return 1;
83653}
83654
83655/*
83656** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
83657** that name in the set of source tables in pSrcList and make the pExpr
83658** expression node refer back to that source column.  The following changes
83659** are made to pExpr:
83660**
83661**    pExpr->iDb           Set the index in db->aDb[] of the database X
83662**                         (even if X is implied).
83663**    pExpr->iTable        Set to the cursor number for the table obtained
83664**                         from pSrcList.
83665**    pExpr->pTab          Points to the Table structure of X.Y (even if
83666**                         X and/or Y are implied.)
83667**    pExpr->iColumn       Set to the column number within the table.
83668**    pExpr->op            Set to TK_COLUMN.
83669**    pExpr->pLeft         Any expression this points to is deleted
83670**    pExpr->pRight        Any expression this points to is deleted.
83671**
83672** The zDb variable is the name of the database (the "X").  This value may be
83673** NULL meaning that name is of the form Y.Z or Z.  Any available database
83674** can be used.  The zTable variable is the name of the table (the "Y").  This
83675** value can be NULL if zDb is also NULL.  If zTable is NULL it
83676** means that the form of the name is Z and that columns from any table
83677** can be used.
83678**
83679** If the name cannot be resolved unambiguously, leave an error message
83680** in pParse and return WRC_Abort.  Return WRC_Prune on success.
83681*/
83682static int lookupName(
83683  Parse *pParse,       /* The parsing context */
83684  const char *zDb,     /* Name of the database containing table, or NULL */
83685  const char *zTab,    /* Name of table containing column, or NULL */
83686  const char *zCol,    /* Name of the column. */
83687  NameContext *pNC,    /* The name context used to resolve the name */
83688  Expr *pExpr          /* Make this EXPR node point to the selected column */
83689){
83690  int i, j;                         /* Loop counters */
83691  int cnt = 0;                      /* Number of matching column names */
83692  int cntTab = 0;                   /* Number of matching table names */
83693  int nSubquery = 0;                /* How many levels of subquery */
83694  sqlite3 *db = pParse->db;         /* The database connection */
83695  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
83696  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
83697  NameContext *pTopNC = pNC;        /* First namecontext in the list */
83698  Schema *pSchema = 0;              /* Schema of the expression */
83699  int isTrigger = 0;                /* True if resolved to a trigger column */
83700  Table *pTab = 0;                  /* Table hold the row */
83701  Column *pCol;                     /* A column of pTab */
83702
83703  assert( pNC );     /* the name context cannot be NULL. */
83704  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
83705  assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
83706
83707  /* Initialize the node to no-match */
83708  pExpr->iTable = -1;
83709  pExpr->pTab = 0;
83710  ExprSetVVAProperty(pExpr, EP_NoReduce);
83711
83712  /* Translate the schema name in zDb into a pointer to the corresponding
83713  ** schema.  If not found, pSchema will remain NULL and nothing will match
83714  ** resulting in an appropriate error message toward the end of this routine
83715  */
83716  if( zDb ){
83717    testcase( pNC->ncFlags & NC_PartIdx );
83718    testcase( pNC->ncFlags & NC_IsCheck );
83719    if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
83720      /* Silently ignore database qualifiers inside CHECK constraints and
83721      ** partial indices.  Do not raise errors because that might break
83722      ** legacy and because it does not hurt anything to just ignore the
83723      ** database name. */
83724      zDb = 0;
83725    }else{
83726      for(i=0; i<db->nDb; i++){
83727        assert( db->aDb[i].zName );
83728        if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
83729          pSchema = db->aDb[i].pSchema;
83730          break;
83731        }
83732      }
83733    }
83734  }
83735
83736  /* Start at the inner-most context and move outward until a match is found */
83737  while( pNC && cnt==0 ){
83738    ExprList *pEList;
83739    SrcList *pSrcList = pNC->pSrcList;
83740
83741    if( pSrcList ){
83742      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
83743        pTab = pItem->pTab;
83744        assert( pTab!=0 && pTab->zName!=0 );
83745        assert( pTab->nCol>0 );
83746        if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
83747          int hit = 0;
83748          pEList = pItem->pSelect->pEList;
83749          for(j=0; j<pEList->nExpr; j++){
83750            if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
83751              cnt++;
83752              cntTab = 2;
83753              pMatch = pItem;
83754              pExpr->iColumn = j;
83755              hit = 1;
83756            }
83757          }
83758          if( hit || zTab==0 ) continue;
83759        }
83760        if( zDb && pTab->pSchema!=pSchema ){
83761          continue;
83762        }
83763        if( zTab ){
83764          const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
83765          assert( zTabName!=0 );
83766          if( sqlite3StrICmp(zTabName, zTab)!=0 ){
83767            continue;
83768          }
83769        }
83770        if( 0==(cntTab++) ){
83771          pMatch = pItem;
83772        }
83773        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
83774          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
83775            /* If there has been exactly one prior match and this match
83776            ** is for the right-hand table of a NATURAL JOIN or is in a
83777            ** USING clause, then skip this match.
83778            */
83779            if( cnt==1 ){
83780              if( pItem->fg.jointype & JT_NATURAL ) continue;
83781              if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
83782            }
83783            cnt++;
83784            pMatch = pItem;
83785            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
83786            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
83787            break;
83788          }
83789        }
83790      }
83791      if( pMatch ){
83792        pExpr->iTable = pMatch->iCursor;
83793        pExpr->pTab = pMatch->pTab;
83794        /* RIGHT JOIN not (yet) supported */
83795        assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
83796        if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
83797          ExprSetProperty(pExpr, EP_CanBeNull);
83798        }
83799        pSchema = pExpr->pTab->pSchema;
83800      }
83801    } /* if( pSrcList ) */
83802
83803#ifndef SQLITE_OMIT_TRIGGER
83804    /* If we have not already resolved the name, then maybe
83805    ** it is a new.* or old.* trigger argument reference
83806    */
83807    if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
83808      int op = pParse->eTriggerOp;
83809      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
83810      if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
83811        pExpr->iTable = 1;
83812        pTab = pParse->pTriggerTab;
83813      }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
83814        pExpr->iTable = 0;
83815        pTab = pParse->pTriggerTab;
83816      }else{
83817        pTab = 0;
83818      }
83819
83820      if( pTab ){
83821        int iCol;
83822        pSchema = pTab->pSchema;
83823        cntTab++;
83824        for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
83825          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
83826            if( iCol==pTab->iPKey ){
83827              iCol = -1;
83828            }
83829            break;
83830          }
83831        }
83832        if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
83833          /* IMP: R-51414-32910 */
83834          /* IMP: R-44911-55124 */
83835          iCol = -1;
83836        }
83837        if( iCol<pTab->nCol ){
83838          cnt++;
83839          if( iCol<0 ){
83840            pExpr->affinity = SQLITE_AFF_INTEGER;
83841          }else if( pExpr->iTable==0 ){
83842            testcase( iCol==31 );
83843            testcase( iCol==32 );
83844            pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
83845          }else{
83846            testcase( iCol==31 );
83847            testcase( iCol==32 );
83848            pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
83849          }
83850          pExpr->iColumn = (i16)iCol;
83851          pExpr->pTab = pTab;
83852          isTrigger = 1;
83853        }
83854      }
83855    }
83856#endif /* !defined(SQLITE_OMIT_TRIGGER) */
83857
83858    /*
83859    ** Perhaps the name is a reference to the ROWID
83860    */
83861    if( cnt==0
83862     && cntTab==1
83863     && pMatch
83864     && (pNC->ncFlags & NC_IdxExpr)==0
83865     && sqlite3IsRowid(zCol)
83866     && VisibleRowid(pMatch->pTab)
83867    ){
83868      cnt = 1;
83869      pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
83870      pExpr->affinity = SQLITE_AFF_INTEGER;
83871    }
83872
83873    /*
83874    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
83875    ** might refer to an result-set alias.  This happens, for example, when
83876    ** we are resolving names in the WHERE clause of the following command:
83877    **
83878    **     SELECT a+b AS x FROM table WHERE x<10;
83879    **
83880    ** In cases like this, replace pExpr with a copy of the expression that
83881    ** forms the result set entry ("a+b" in the example) and return immediately.
83882    ** Note that the expression in the result set should have already been
83883    ** resolved by the time the WHERE clause is resolved.
83884    **
83885    ** The ability to use an output result-set column in the WHERE, GROUP BY,
83886    ** or HAVING clauses, or as part of a larger expression in the ORDER BY
83887    ** clause is not standard SQL.  This is a (goofy) SQLite extension, that
83888    ** is supported for backwards compatibility only. Hence, we issue a warning
83889    ** on sqlite3_log() whenever the capability is used.
83890    */
83891    if( (pEList = pNC->pEList)!=0
83892     && zTab==0
83893     && cnt==0
83894    ){
83895      for(j=0; j<pEList->nExpr; j++){
83896        char *zAs = pEList->a[j].zName;
83897        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
83898          Expr *pOrig;
83899          assert( pExpr->pLeft==0 && pExpr->pRight==0 );
83900          assert( pExpr->x.pList==0 );
83901          assert( pExpr->x.pSelect==0 );
83902          pOrig = pEList->a[j].pExpr;
83903          if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
83904            sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
83905            return WRC_Abort;
83906          }
83907          resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
83908          cnt = 1;
83909          pMatch = 0;
83910          assert( zTab==0 && zDb==0 );
83911          goto lookupname_end;
83912        }
83913      }
83914    }
83915
83916    /* Advance to the next name context.  The loop will exit when either
83917    ** we have a match (cnt>0) or when we run out of name contexts.
83918    */
83919    if( cnt==0 ){
83920      pNC = pNC->pNext;
83921      nSubquery++;
83922    }
83923  }
83924
83925  /*
83926  ** If X and Y are NULL (in other words if only the column name Z is
83927  ** supplied) and the value of Z is enclosed in double-quotes, then
83928  ** Z is a string literal if it doesn't match any column names.  In that
83929  ** case, we need to return right away and not make any changes to
83930  ** pExpr.
83931  **
83932  ** Because no reference was made to outer contexts, the pNC->nRef
83933  ** fields are not changed in any context.
83934  */
83935  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
83936    pExpr->op = TK_STRING;
83937    pExpr->pTab = 0;
83938    return WRC_Prune;
83939  }
83940
83941  /*
83942  ** cnt==0 means there was not match.  cnt>1 means there were two or
83943  ** more matches.  Either way, we have an error.
83944  */
83945  if( cnt!=1 ){
83946    const char *zErr;
83947    zErr = cnt==0 ? "no such column" : "ambiguous column name";
83948    if( zDb ){
83949      sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
83950    }else if( zTab ){
83951      sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
83952    }else{
83953      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
83954    }
83955    pParse->checkSchema = 1;
83956    pTopNC->nErr++;
83957  }
83958
83959  /* If a column from a table in pSrcList is referenced, then record
83960  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
83961  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
83962  ** column number is greater than the number of bits in the bitmask
83963  ** then set the high-order bit of the bitmask.
83964  */
83965  if( pExpr->iColumn>=0 && pMatch!=0 ){
83966    int n = pExpr->iColumn;
83967    testcase( n==BMS-1 );
83968    if( n>=BMS ){
83969      n = BMS-1;
83970    }
83971    assert( pMatch->iCursor==pExpr->iTable );
83972    pMatch->colUsed |= ((Bitmask)1)<<n;
83973  }
83974
83975  /* Clean up and return
83976  */
83977  sqlite3ExprDelete(db, pExpr->pLeft);
83978  pExpr->pLeft = 0;
83979  sqlite3ExprDelete(db, pExpr->pRight);
83980  pExpr->pRight = 0;
83981  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
83982lookupname_end:
83983  if( cnt==1 ){
83984    assert( pNC!=0 );
83985    if( !ExprHasProperty(pExpr, EP_Alias) ){
83986      sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
83987    }
83988    /* Increment the nRef value on all name contexts from TopNC up to
83989    ** the point where the name matched. */
83990    for(;;){
83991      assert( pTopNC!=0 );
83992      pTopNC->nRef++;
83993      if( pTopNC==pNC ) break;
83994      pTopNC = pTopNC->pNext;
83995    }
83996    return WRC_Prune;
83997  } else {
83998    return WRC_Abort;
83999  }
84000}
84001
84002/*
84003** Allocate and return a pointer to an expression to load the column iCol
84004** from datasource iSrc in SrcList pSrc.
84005*/
84006SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
84007  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
84008  if( p ){
84009    struct SrcList_item *pItem = &pSrc->a[iSrc];
84010    p->pTab = pItem->pTab;
84011    p->iTable = pItem->iCursor;
84012    if( p->pTab->iPKey==iCol ){
84013      p->iColumn = -1;
84014    }else{
84015      p->iColumn = (ynVar)iCol;
84016      testcase( iCol==BMS );
84017      testcase( iCol==BMS-1 );
84018      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
84019    }
84020    ExprSetProperty(p, EP_Resolved);
84021  }
84022  return p;
84023}
84024
84025/*
84026** Report an error that an expression is not valid for some set of
84027** pNC->ncFlags values determined by validMask.
84028*/
84029static void notValid(
84030  Parse *pParse,       /* Leave error message here */
84031  NameContext *pNC,    /* The name context */
84032  const char *zMsg,    /* Type of error */
84033  int validMask        /* Set of contexts for which prohibited */
84034){
84035  assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
84036  if( (pNC->ncFlags & validMask)!=0 ){
84037    const char *zIn = "partial index WHERE clauses";
84038    if( pNC->ncFlags & NC_IdxExpr )      zIn = "index expressions";
84039#ifndef SQLITE_OMIT_CHECK
84040    else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
84041#endif
84042    sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
84043  }
84044}
84045
84046/*
84047** Expression p should encode a floating point value between 1.0 and 0.0.
84048** Return 1024 times this value.  Or return -1 if p is not a floating point
84049** value between 1.0 and 0.0.
84050*/
84051static int exprProbability(Expr *p){
84052  double r = -1.0;
84053  if( p->op!=TK_FLOAT ) return -1;
84054  sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
84055  assert( r>=0.0 );
84056  if( r>1.0 ) return -1;
84057  return (int)(r*134217728.0);
84058}
84059
84060/*
84061** This routine is callback for sqlite3WalkExpr().
84062**
84063** Resolve symbolic names into TK_COLUMN operators for the current
84064** node in the expression tree.  Return 0 to continue the search down
84065** the tree or 2 to abort the tree walk.
84066**
84067** This routine also does error checking and name resolution for
84068** function names.  The operator for aggregate functions is changed
84069** to TK_AGG_FUNCTION.
84070*/
84071static int resolveExprStep(Walker *pWalker, Expr *pExpr){
84072  NameContext *pNC;
84073  Parse *pParse;
84074
84075  pNC = pWalker->u.pNC;
84076  assert( pNC!=0 );
84077  pParse = pNC->pParse;
84078  assert( pParse==pWalker->pParse );
84079
84080  if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
84081  ExprSetProperty(pExpr, EP_Resolved);
84082#ifndef NDEBUG
84083  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
84084    SrcList *pSrcList = pNC->pSrcList;
84085    int i;
84086    for(i=0; i<pNC->pSrcList->nSrc; i++){
84087      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
84088    }
84089  }
84090#endif
84091  switch( pExpr->op ){
84092
84093#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
84094    /* The special operator TK_ROW means use the rowid for the first
84095    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
84096    ** clause processing on UPDATE and DELETE statements.
84097    */
84098    case TK_ROW: {
84099      SrcList *pSrcList = pNC->pSrcList;
84100      struct SrcList_item *pItem;
84101      assert( pSrcList && pSrcList->nSrc==1 );
84102      pItem = pSrcList->a;
84103      pExpr->op = TK_COLUMN;
84104      pExpr->pTab = pItem->pTab;
84105      pExpr->iTable = pItem->iCursor;
84106      pExpr->iColumn = -1;
84107      pExpr->affinity = SQLITE_AFF_INTEGER;
84108      break;
84109    }
84110#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
84111          && !defined(SQLITE_OMIT_SUBQUERY) */
84112
84113    /* A lone identifier is the name of a column.
84114    */
84115    case TK_ID: {
84116      return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
84117    }
84118
84119    /* A table name and column name:     ID.ID
84120    ** Or a database, table and column:  ID.ID.ID
84121    */
84122    case TK_DOT: {
84123      const char *zColumn;
84124      const char *zTable;
84125      const char *zDb;
84126      Expr *pRight;
84127
84128      /* if( pSrcList==0 ) break; */
84129      notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
84130      /*notValid(pParse, pNC, "the \".\" operator", NC_PartIdx|NC_IsCheck, 1);*/
84131      pRight = pExpr->pRight;
84132      if( pRight->op==TK_ID ){
84133        zDb = 0;
84134        zTable = pExpr->pLeft->u.zToken;
84135        zColumn = pRight->u.zToken;
84136      }else{
84137        assert( pRight->op==TK_DOT );
84138        zDb = pExpr->pLeft->u.zToken;
84139        zTable = pRight->pLeft->u.zToken;
84140        zColumn = pRight->pRight->u.zToken;
84141      }
84142      return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
84143    }
84144
84145    /* Resolve function names
84146    */
84147    case TK_FUNCTION: {
84148      ExprList *pList = pExpr->x.pList;    /* The argument list */
84149      int n = pList ? pList->nExpr : 0;    /* Number of arguments */
84150      int no_such_func = 0;       /* True if no such function exists */
84151      int wrong_num_args = 0;     /* True if wrong number of arguments */
84152      int is_agg = 0;             /* True if is an aggregate function */
84153      int auth;                   /* Authorization to use the function */
84154      int nId;                    /* Number of characters in function name */
84155      const char *zId;            /* The function name. */
84156      FuncDef *pDef;              /* Information about the function */
84157      u8 enc = ENC(pParse->db);   /* The database encoding */
84158
84159      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
84160      notValid(pParse, pNC, "functions", NC_PartIdx);
84161      zId = pExpr->u.zToken;
84162      nId = sqlite3Strlen30(zId);
84163      pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
84164      if( pDef==0 ){
84165        pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
84166        if( pDef==0 ){
84167          no_such_func = 1;
84168        }else{
84169          wrong_num_args = 1;
84170        }
84171      }else{
84172        is_agg = pDef->xFunc==0;
84173        if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
84174          ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
84175          if( n==2 ){
84176            pExpr->iTable = exprProbability(pList->a[1].pExpr);
84177            if( pExpr->iTable<0 ){
84178              sqlite3ErrorMsg(pParse,
84179                "second argument to likelihood() must be a "
84180                "constant between 0.0 and 1.0");
84181              pNC->nErr++;
84182            }
84183          }else{
84184            /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
84185            ** equivalent to likelihood(X, 0.0625).
84186            ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
84187            ** short-hand for likelihood(X,0.0625).
84188            ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
84189            ** for likelihood(X,0.9375).
84190            ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
84191            ** to likelihood(X,0.9375). */
84192            /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */
84193            pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
84194          }
84195        }
84196#ifndef SQLITE_OMIT_AUTHORIZATION
84197        auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
84198        if( auth!=SQLITE_OK ){
84199          if( auth==SQLITE_DENY ){
84200            sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
84201                                    pDef->zName);
84202            pNC->nErr++;
84203          }
84204          pExpr->op = TK_NULL;
84205          return WRC_Prune;
84206        }
84207#endif
84208        if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
84209          /* For the purposes of the EP_ConstFunc flag, date and time
84210          ** functions and other functions that change slowly are considered
84211          ** constant because they are constant for the duration of one query */
84212          ExprSetProperty(pExpr,EP_ConstFunc);
84213        }
84214        if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
84215          /* Date/time functions that use 'now', and other functions like
84216          ** sqlite_version() that might change over time cannot be used
84217          ** in an index. */
84218          notValid(pParse, pNC, "non-deterministic functions", NC_IdxExpr);
84219        }
84220      }
84221      if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
84222        sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
84223        pNC->nErr++;
84224        is_agg = 0;
84225      }else if( no_such_func && pParse->db->init.busy==0 ){
84226        sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
84227        pNC->nErr++;
84228      }else if( wrong_num_args ){
84229        sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
84230             nId, zId);
84231        pNC->nErr++;
84232      }
84233      if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
84234      sqlite3WalkExprList(pWalker, pList);
84235      if( is_agg ){
84236        NameContext *pNC2 = pNC;
84237        pExpr->op = TK_AGG_FUNCTION;
84238        pExpr->op2 = 0;
84239        while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
84240          pExpr->op2++;
84241          pNC2 = pNC2->pNext;
84242        }
84243        assert( pDef!=0 );
84244        if( pNC2 ){
84245          assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
84246          testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
84247          pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
84248
84249        }
84250        pNC->ncFlags |= NC_AllowAgg;
84251      }
84252      /* FIX ME:  Compute pExpr->affinity based on the expected return
84253      ** type of the function
84254      */
84255      return WRC_Prune;
84256    }
84257#ifndef SQLITE_OMIT_SUBQUERY
84258    case TK_SELECT:
84259    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
84260#endif
84261    case TK_IN: {
84262      testcase( pExpr->op==TK_IN );
84263      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
84264        int nRef = pNC->nRef;
84265        notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
84266        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
84267        assert( pNC->nRef>=nRef );
84268        if( nRef!=pNC->nRef ){
84269          ExprSetProperty(pExpr, EP_VarSelect);
84270        }
84271      }
84272      break;
84273    }
84274    case TK_VARIABLE: {
84275      notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
84276      break;
84277    }
84278  }
84279  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
84280}
84281
84282/*
84283** pEList is a list of expressions which are really the result set of the
84284** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
84285** This routine checks to see if pE is a simple identifier which corresponds
84286** to the AS-name of one of the terms of the expression list.  If it is,
84287** this routine return an integer between 1 and N where N is the number of
84288** elements in pEList, corresponding to the matching entry.  If there is
84289** no match, or if pE is not a simple identifier, then this routine
84290** return 0.
84291**
84292** pEList has been resolved.  pE has not.
84293*/
84294static int resolveAsName(
84295  Parse *pParse,     /* Parsing context for error messages */
84296  ExprList *pEList,  /* List of expressions to scan */
84297  Expr *pE           /* Expression we are trying to match */
84298){
84299  int i;             /* Loop counter */
84300
84301  UNUSED_PARAMETER(pParse);
84302
84303  if( pE->op==TK_ID ){
84304    char *zCol = pE->u.zToken;
84305    for(i=0; i<pEList->nExpr; i++){
84306      char *zAs = pEList->a[i].zName;
84307      if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
84308        return i+1;
84309      }
84310    }
84311  }
84312  return 0;
84313}
84314
84315/*
84316** pE is a pointer to an expression which is a single term in the
84317** ORDER BY of a compound SELECT.  The expression has not been
84318** name resolved.
84319**
84320** At the point this routine is called, we already know that the
84321** ORDER BY term is not an integer index into the result set.  That
84322** case is handled by the calling routine.
84323**
84324** Attempt to match pE against result set columns in the left-most
84325** SELECT statement.  Return the index i of the matching column,
84326** as an indication to the caller that it should sort by the i-th column.
84327** The left-most column is 1.  In other words, the value returned is the
84328** same integer value that would be used in the SQL statement to indicate
84329** the column.
84330**
84331** If there is no match, return 0.  Return -1 if an error occurs.
84332*/
84333static int resolveOrderByTermToExprList(
84334  Parse *pParse,     /* Parsing context for error messages */
84335  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
84336  Expr *pE           /* The specific ORDER BY term */
84337){
84338  int i;             /* Loop counter */
84339  ExprList *pEList;  /* The columns of the result set */
84340  NameContext nc;    /* Name context for resolving pE */
84341  sqlite3 *db;       /* Database connection */
84342  int rc;            /* Return code from subprocedures */
84343  u8 savedSuppErr;   /* Saved value of db->suppressErr */
84344
84345  assert( sqlite3ExprIsInteger(pE, &i)==0 );
84346  pEList = pSelect->pEList;
84347
84348  /* Resolve all names in the ORDER BY term expression
84349  */
84350  memset(&nc, 0, sizeof(nc));
84351  nc.pParse = pParse;
84352  nc.pSrcList = pSelect->pSrc;
84353  nc.pEList = pEList;
84354  nc.ncFlags = NC_AllowAgg;
84355  nc.nErr = 0;
84356  db = pParse->db;
84357  savedSuppErr = db->suppressErr;
84358  db->suppressErr = 1;
84359  rc = sqlite3ResolveExprNames(&nc, pE);
84360  db->suppressErr = savedSuppErr;
84361  if( rc ) return 0;
84362
84363  /* Try to match the ORDER BY expression against an expression
84364  ** in the result set.  Return an 1-based index of the matching
84365  ** result-set entry.
84366  */
84367  for(i=0; i<pEList->nExpr; i++){
84368    if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
84369      return i+1;
84370    }
84371  }
84372
84373  /* If no match, return 0. */
84374  return 0;
84375}
84376
84377/*
84378** Generate an ORDER BY or GROUP BY term out-of-range error.
84379*/
84380static void resolveOutOfRangeError(
84381  Parse *pParse,         /* The error context into which to write the error */
84382  const char *zType,     /* "ORDER" or "GROUP" */
84383  int i,                 /* The index (1-based) of the term out of range */
84384  int mx                 /* Largest permissible value of i */
84385){
84386  sqlite3ErrorMsg(pParse,
84387    "%r %s BY term out of range - should be "
84388    "between 1 and %d", i, zType, mx);
84389}
84390
84391/*
84392** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
84393** each term of the ORDER BY clause is a constant integer between 1
84394** and N where N is the number of columns in the compound SELECT.
84395**
84396** ORDER BY terms that are already an integer between 1 and N are
84397** unmodified.  ORDER BY terms that are integers outside the range of
84398** 1 through N generate an error.  ORDER BY terms that are expressions
84399** are matched against result set expressions of compound SELECT
84400** beginning with the left-most SELECT and working toward the right.
84401** At the first match, the ORDER BY expression is transformed into
84402** the integer column number.
84403**
84404** Return the number of errors seen.
84405*/
84406static int resolveCompoundOrderBy(
84407  Parse *pParse,        /* Parsing context.  Leave error messages here */
84408  Select *pSelect       /* The SELECT statement containing the ORDER BY */
84409){
84410  int i;
84411  ExprList *pOrderBy;
84412  ExprList *pEList;
84413  sqlite3 *db;
84414  int moreToDo = 1;
84415
84416  pOrderBy = pSelect->pOrderBy;
84417  if( pOrderBy==0 ) return 0;
84418  db = pParse->db;
84419#if SQLITE_MAX_COLUMN
84420  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
84421    sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
84422    return 1;
84423  }
84424#endif
84425  for(i=0; i<pOrderBy->nExpr; i++){
84426    pOrderBy->a[i].done = 0;
84427  }
84428  pSelect->pNext = 0;
84429  while( pSelect->pPrior ){
84430    pSelect->pPrior->pNext = pSelect;
84431    pSelect = pSelect->pPrior;
84432  }
84433  while( pSelect && moreToDo ){
84434    struct ExprList_item *pItem;
84435    moreToDo = 0;
84436    pEList = pSelect->pEList;
84437    assert( pEList!=0 );
84438    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
84439      int iCol = -1;
84440      Expr *pE, *pDup;
84441      if( pItem->done ) continue;
84442      pE = sqlite3ExprSkipCollate(pItem->pExpr);
84443      if( sqlite3ExprIsInteger(pE, &iCol) ){
84444        if( iCol<=0 || iCol>pEList->nExpr ){
84445          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
84446          return 1;
84447        }
84448      }else{
84449        iCol = resolveAsName(pParse, pEList, pE);
84450        if( iCol==0 ){
84451          pDup = sqlite3ExprDup(db, pE, 0);
84452          if( !db->mallocFailed ){
84453            assert(pDup);
84454            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
84455          }
84456          sqlite3ExprDelete(db, pDup);
84457        }
84458      }
84459      if( iCol>0 ){
84460        /* Convert the ORDER BY term into an integer column number iCol,
84461        ** taking care to preserve the COLLATE clause if it exists */
84462        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
84463        if( pNew==0 ) return 1;
84464        pNew->flags |= EP_IntValue;
84465        pNew->u.iValue = iCol;
84466        if( pItem->pExpr==pE ){
84467          pItem->pExpr = pNew;
84468        }else{
84469          Expr *pParent = pItem->pExpr;
84470          assert( pParent->op==TK_COLLATE );
84471          while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
84472          assert( pParent->pLeft==pE );
84473          pParent->pLeft = pNew;
84474        }
84475        sqlite3ExprDelete(db, pE);
84476        pItem->u.x.iOrderByCol = (u16)iCol;
84477        pItem->done = 1;
84478      }else{
84479        moreToDo = 1;
84480      }
84481    }
84482    pSelect = pSelect->pNext;
84483  }
84484  for(i=0; i<pOrderBy->nExpr; i++){
84485    if( pOrderBy->a[i].done==0 ){
84486      sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
84487            "column in the result set", i+1);
84488      return 1;
84489    }
84490  }
84491  return 0;
84492}
84493
84494/*
84495** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
84496** the SELECT statement pSelect.  If any term is reference to a
84497** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
84498** field) then convert that term into a copy of the corresponding result set
84499** column.
84500**
84501** If any errors are detected, add an error message to pParse and
84502** return non-zero.  Return zero if no errors are seen.
84503*/
84504SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
84505  Parse *pParse,        /* Parsing context.  Leave error messages here */
84506  Select *pSelect,      /* The SELECT statement containing the clause */
84507  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
84508  const char *zType     /* "ORDER" or "GROUP" */
84509){
84510  int i;
84511  sqlite3 *db = pParse->db;
84512  ExprList *pEList;
84513  struct ExprList_item *pItem;
84514
84515  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
84516#if SQLITE_MAX_COLUMN
84517  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
84518    sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
84519    return 1;
84520  }
84521#endif
84522  pEList = pSelect->pEList;
84523  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
84524  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
84525    if( pItem->u.x.iOrderByCol ){
84526      if( pItem->u.x.iOrderByCol>pEList->nExpr ){
84527        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
84528        return 1;
84529      }
84530      resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
84531                   zType,0);
84532    }
84533  }
84534  return 0;
84535}
84536
84537/*
84538** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
84539** The Name context of the SELECT statement is pNC.  zType is either
84540** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
84541**
84542** This routine resolves each term of the clause into an expression.
84543** If the order-by term is an integer I between 1 and N (where N is the
84544** number of columns in the result set of the SELECT) then the expression
84545** in the resolution is a copy of the I-th result-set expression.  If
84546** the order-by term is an identifier that corresponds to the AS-name of
84547** a result-set expression, then the term resolves to a copy of the
84548** result-set expression.  Otherwise, the expression is resolved in
84549** the usual way - using sqlite3ResolveExprNames().
84550**
84551** This routine returns the number of errors.  If errors occur, then
84552** an appropriate error message might be left in pParse.  (OOM errors
84553** excepted.)
84554*/
84555static int resolveOrderGroupBy(
84556  NameContext *pNC,     /* The name context of the SELECT statement */
84557  Select *pSelect,      /* The SELECT statement holding pOrderBy */
84558  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
84559  const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
84560){
84561  int i, j;                      /* Loop counters */
84562  int iCol;                      /* Column number */
84563  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
84564  Parse *pParse;                 /* Parsing context */
84565  int nResult;                   /* Number of terms in the result set */
84566
84567  if( pOrderBy==0 ) return 0;
84568  nResult = pSelect->pEList->nExpr;
84569  pParse = pNC->pParse;
84570  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
84571    Expr *pE = pItem->pExpr;
84572    Expr *pE2 = sqlite3ExprSkipCollate(pE);
84573    if( zType[0]!='G' ){
84574      iCol = resolveAsName(pParse, pSelect->pEList, pE2);
84575      if( iCol>0 ){
84576        /* If an AS-name match is found, mark this ORDER BY column as being
84577        ** a copy of the iCol-th result-set column.  The subsequent call to
84578        ** sqlite3ResolveOrderGroupBy() will convert the expression to a
84579        ** copy of the iCol-th result-set expression. */
84580        pItem->u.x.iOrderByCol = (u16)iCol;
84581        continue;
84582      }
84583    }
84584    if( sqlite3ExprIsInteger(pE2, &iCol) ){
84585      /* The ORDER BY term is an integer constant.  Again, set the column
84586      ** number so that sqlite3ResolveOrderGroupBy() will convert the
84587      ** order-by term to a copy of the result-set expression */
84588      if( iCol<1 || iCol>0xffff ){
84589        resolveOutOfRangeError(pParse, zType, i+1, nResult);
84590        return 1;
84591      }
84592      pItem->u.x.iOrderByCol = (u16)iCol;
84593      continue;
84594    }
84595
84596    /* Otherwise, treat the ORDER BY term as an ordinary expression */
84597    pItem->u.x.iOrderByCol = 0;
84598    if( sqlite3ResolveExprNames(pNC, pE) ){
84599      return 1;
84600    }
84601    for(j=0; j<pSelect->pEList->nExpr; j++){
84602      if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
84603        pItem->u.x.iOrderByCol = j+1;
84604      }
84605    }
84606  }
84607  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
84608}
84609
84610/*
84611** Resolve names in the SELECT statement p and all of its descendants.
84612*/
84613static int resolveSelectStep(Walker *pWalker, Select *p){
84614  NameContext *pOuterNC;  /* Context that contains this SELECT */
84615  NameContext sNC;        /* Name context of this SELECT */
84616  int isCompound;         /* True if p is a compound select */
84617  int nCompound;          /* Number of compound terms processed so far */
84618  Parse *pParse;          /* Parsing context */
84619  int i;                  /* Loop counter */
84620  ExprList *pGroupBy;     /* The GROUP BY clause */
84621  Select *pLeftmost;      /* Left-most of SELECT of a compound */
84622  sqlite3 *db;            /* Database connection */
84623
84624
84625  assert( p!=0 );
84626  if( p->selFlags & SF_Resolved ){
84627    return WRC_Prune;
84628  }
84629  pOuterNC = pWalker->u.pNC;
84630  pParse = pWalker->pParse;
84631  db = pParse->db;
84632
84633  /* Normally sqlite3SelectExpand() will be called first and will have
84634  ** already expanded this SELECT.  However, if this is a subquery within
84635  ** an expression, sqlite3ResolveExprNames() will be called without a
84636  ** prior call to sqlite3SelectExpand().  When that happens, let
84637  ** sqlite3SelectPrep() do all of the processing for this SELECT.
84638  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
84639  ** this routine in the correct order.
84640  */
84641  if( (p->selFlags & SF_Expanded)==0 ){
84642    sqlite3SelectPrep(pParse, p, pOuterNC);
84643    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
84644  }
84645
84646  isCompound = p->pPrior!=0;
84647  nCompound = 0;
84648  pLeftmost = p;
84649  while( p ){
84650    assert( (p->selFlags & SF_Expanded)!=0 );
84651    assert( (p->selFlags & SF_Resolved)==0 );
84652    p->selFlags |= SF_Resolved;
84653
84654    /* Resolve the expressions in the LIMIT and OFFSET clauses. These
84655    ** are not allowed to refer to any names, so pass an empty NameContext.
84656    */
84657    memset(&sNC, 0, sizeof(sNC));
84658    sNC.pParse = pParse;
84659    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
84660        sqlite3ResolveExprNames(&sNC, p->pOffset) ){
84661      return WRC_Abort;
84662    }
84663
84664    /* If the SF_Converted flags is set, then this Select object was
84665    ** was created by the convertCompoundSelectToSubquery() function.
84666    ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
84667    ** as if it were part of the sub-query, not the parent. This block
84668    ** moves the pOrderBy down to the sub-query. It will be moved back
84669    ** after the names have been resolved.  */
84670    if( p->selFlags & SF_Converted ){
84671      Select *pSub = p->pSrc->a[0].pSelect;
84672      assert( p->pSrc->nSrc==1 && p->pOrderBy );
84673      assert( pSub->pPrior && pSub->pOrderBy==0 );
84674      pSub->pOrderBy = p->pOrderBy;
84675      p->pOrderBy = 0;
84676    }
84677
84678    /* Recursively resolve names in all subqueries
84679    */
84680    for(i=0; i<p->pSrc->nSrc; i++){
84681      struct SrcList_item *pItem = &p->pSrc->a[i];
84682      if( pItem->pSelect ){
84683        NameContext *pNC;         /* Used to iterate name contexts */
84684        int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
84685        const char *zSavedContext = pParse->zAuthContext;
84686
84687        /* Count the total number of references to pOuterNC and all of its
84688        ** parent contexts. After resolving references to expressions in
84689        ** pItem->pSelect, check if this value has changed. If so, then
84690        ** SELECT statement pItem->pSelect must be correlated. Set the
84691        ** pItem->fg.isCorrelated flag if this is the case. */
84692        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
84693
84694        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
84695        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
84696        pParse->zAuthContext = zSavedContext;
84697        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
84698
84699        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
84700        assert( pItem->fg.isCorrelated==0 && nRef<=0 );
84701        pItem->fg.isCorrelated = (nRef!=0);
84702      }
84703    }
84704
84705    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
84706    ** resolve the result-set expression list.
84707    */
84708    sNC.ncFlags = NC_AllowAgg;
84709    sNC.pSrcList = p->pSrc;
84710    sNC.pNext = pOuterNC;
84711
84712    /* Resolve names in the result set. */
84713    if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
84714
84715    /* If there are no aggregate functions in the result-set, and no GROUP BY
84716    ** expression, do not allow aggregates in any of the other expressions.
84717    */
84718    assert( (p->selFlags & SF_Aggregate)==0 );
84719    pGroupBy = p->pGroupBy;
84720    if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
84721      assert( NC_MinMaxAgg==SF_MinMaxAgg );
84722      p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
84723    }else{
84724      sNC.ncFlags &= ~NC_AllowAgg;
84725    }
84726
84727    /* If a HAVING clause is present, then there must be a GROUP BY clause.
84728    */
84729    if( p->pHaving && !pGroupBy ){
84730      sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
84731      return WRC_Abort;
84732    }
84733
84734    /* Add the output column list to the name-context before parsing the
84735    ** other expressions in the SELECT statement. This is so that
84736    ** expressions in the WHERE clause (etc.) can refer to expressions by
84737    ** aliases in the result set.
84738    **
84739    ** Minor point: If this is the case, then the expression will be
84740    ** re-evaluated for each reference to it.
84741    */
84742    sNC.pEList = p->pEList;
84743    if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
84744    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
84745
84746    /* Resolve names in table-valued-function arguments */
84747    for(i=0; i<p->pSrc->nSrc; i++){
84748      struct SrcList_item *pItem = &p->pSrc->a[i];
84749      if( pItem->fg.isTabFunc
84750       && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
84751      ){
84752        return WRC_Abort;
84753      }
84754    }
84755
84756    /* The ORDER BY and GROUP BY clauses may not refer to terms in
84757    ** outer queries
84758    */
84759    sNC.pNext = 0;
84760    sNC.ncFlags |= NC_AllowAgg;
84761
84762    /* If this is a converted compound query, move the ORDER BY clause from
84763    ** the sub-query back to the parent query. At this point each term
84764    ** within the ORDER BY clause has been transformed to an integer value.
84765    ** These integers will be replaced by copies of the corresponding result
84766    ** set expressions by the call to resolveOrderGroupBy() below.  */
84767    if( p->selFlags & SF_Converted ){
84768      Select *pSub = p->pSrc->a[0].pSelect;
84769      p->pOrderBy = pSub->pOrderBy;
84770      pSub->pOrderBy = 0;
84771    }
84772
84773    /* Process the ORDER BY clause for singleton SELECT statements.
84774    ** The ORDER BY clause for compounds SELECT statements is handled
84775    ** below, after all of the result-sets for all of the elements of
84776    ** the compound have been resolved.
84777    **
84778    ** If there is an ORDER BY clause on a term of a compound-select other
84779    ** than the right-most term, then that is a syntax error.  But the error
84780    ** is not detected until much later, and so we need to go ahead and
84781    ** resolve those symbols on the incorrect ORDER BY for consistency.
84782    */
84783    if( isCompound<=nCompound  /* Defer right-most ORDER BY of a compound */
84784     && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
84785    ){
84786      return WRC_Abort;
84787    }
84788    if( db->mallocFailed ){
84789      return WRC_Abort;
84790    }
84791
84792    /* Resolve the GROUP BY clause.  At the same time, make sure
84793    ** the GROUP BY clause does not contain aggregate functions.
84794    */
84795    if( pGroupBy ){
84796      struct ExprList_item *pItem;
84797
84798      if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
84799        return WRC_Abort;
84800      }
84801      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
84802        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
84803          sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
84804              "the GROUP BY clause");
84805          return WRC_Abort;
84806        }
84807      }
84808    }
84809
84810    /* If this is part of a compound SELECT, check that it has the right
84811    ** number of expressions in the select list. */
84812    if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
84813      sqlite3SelectWrongNumTermsError(pParse, p->pNext);
84814      return WRC_Abort;
84815    }
84816
84817    /* Advance to the next term of the compound
84818    */
84819    p = p->pPrior;
84820    nCompound++;
84821  }
84822
84823  /* Resolve the ORDER BY on a compound SELECT after all terms of
84824  ** the compound have been resolved.
84825  */
84826  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
84827    return WRC_Abort;
84828  }
84829
84830  return WRC_Prune;
84831}
84832
84833/*
84834** This routine walks an expression tree and resolves references to
84835** table columns and result-set columns.  At the same time, do error
84836** checking on function usage and set a flag if any aggregate functions
84837** are seen.
84838**
84839** To resolve table columns references we look for nodes (or subtrees) of the
84840** form X.Y.Z or Y.Z or just Z where
84841**
84842**      X:   The name of a database.  Ex:  "main" or "temp" or
84843**           the symbolic name assigned to an ATTACH-ed database.
84844**
84845**      Y:   The name of a table in a FROM clause.  Or in a trigger
84846**           one of the special names "old" or "new".
84847**
84848**      Z:   The name of a column in table Y.
84849**
84850** The node at the root of the subtree is modified as follows:
84851**
84852**    Expr.op        Changed to TK_COLUMN
84853**    Expr.pTab      Points to the Table object for X.Y
84854**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
84855**    Expr.iTable    The VDBE cursor number for X.Y
84856**
84857**
84858** To resolve result-set references, look for expression nodes of the
84859** form Z (with no X and Y prefix) where the Z matches the right-hand
84860** size of an AS clause in the result-set of a SELECT.  The Z expression
84861** is replaced by a copy of the left-hand side of the result-set expression.
84862** Table-name and function resolution occurs on the substituted expression
84863** tree.  For example, in:
84864**
84865**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
84866**
84867** The "x" term of the order by is replaced by "a+b" to render:
84868**
84869**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
84870**
84871** Function calls are checked to make sure that the function is
84872** defined and that the correct number of arguments are specified.
84873** If the function is an aggregate function, then the NC_HasAgg flag is
84874** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
84875** If an expression contains aggregate functions then the EP_Agg
84876** property on the expression is set.
84877**
84878** An error message is left in pParse if anything is amiss.  The number
84879** if errors is returned.
84880*/
84881SQLITE_PRIVATE int sqlite3ResolveExprNames(
84882  NameContext *pNC,       /* Namespace to resolve expressions in. */
84883  Expr *pExpr             /* The expression to be analyzed. */
84884){
84885  u16 savedHasAgg;
84886  Walker w;
84887
84888  if( pExpr==0 ) return 0;
84889#if SQLITE_MAX_EXPR_DEPTH>0
84890  {
84891    Parse *pParse = pNC->pParse;
84892    if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
84893      return 1;
84894    }
84895    pParse->nHeight += pExpr->nHeight;
84896  }
84897#endif
84898  savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
84899  pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
84900  memset(&w, 0, sizeof(w));
84901  w.xExprCallback = resolveExprStep;
84902  w.xSelectCallback = resolveSelectStep;
84903  w.pParse = pNC->pParse;
84904  w.u.pNC = pNC;
84905  sqlite3WalkExpr(&w, pExpr);
84906#if SQLITE_MAX_EXPR_DEPTH>0
84907  pNC->pParse->nHeight -= pExpr->nHeight;
84908#endif
84909  if( pNC->nErr>0 || w.pParse->nErr>0 ){
84910    ExprSetProperty(pExpr, EP_Error);
84911  }
84912  if( pNC->ncFlags & NC_HasAgg ){
84913    ExprSetProperty(pExpr, EP_Agg);
84914  }
84915  pNC->ncFlags |= savedHasAgg;
84916  return ExprHasProperty(pExpr, EP_Error);
84917}
84918
84919/*
84920** Resolve all names for all expression in an expression list.  This is
84921** just like sqlite3ResolveExprNames() except that it works for an expression
84922** list rather than a single expression.
84923*/
84924SQLITE_PRIVATE int sqlite3ResolveExprListNames(
84925  NameContext *pNC,       /* Namespace to resolve expressions in. */
84926  ExprList *pList         /* The expression list to be analyzed. */
84927){
84928  int i;
84929  assert( pList!=0 );
84930  for(i=0; i<pList->nExpr; i++){
84931    if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
84932  }
84933  return WRC_Continue;
84934}
84935
84936/*
84937** Resolve all names in all expressions of a SELECT and in all
84938** decendents of the SELECT, including compounds off of p->pPrior,
84939** subqueries in expressions, and subqueries used as FROM clause
84940** terms.
84941**
84942** See sqlite3ResolveExprNames() for a description of the kinds of
84943** transformations that occur.
84944**
84945** All SELECT statements should have been expanded using
84946** sqlite3SelectExpand() prior to invoking this routine.
84947*/
84948SQLITE_PRIVATE void sqlite3ResolveSelectNames(
84949  Parse *pParse,         /* The parser context */
84950  Select *p,             /* The SELECT statement being coded. */
84951  NameContext *pOuterNC  /* Name context for parent SELECT statement */
84952){
84953  Walker w;
84954
84955  assert( p!=0 );
84956  memset(&w, 0, sizeof(w));
84957  w.xExprCallback = resolveExprStep;
84958  w.xSelectCallback = resolveSelectStep;
84959  w.pParse = pParse;
84960  w.u.pNC = pOuterNC;
84961  sqlite3WalkSelect(&w, p);
84962}
84963
84964/*
84965** Resolve names in expressions that can only reference a single table:
84966**
84967**    *   CHECK constraints
84968**    *   WHERE clauses on partial indices
84969**
84970** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
84971** is set to -1 and the Expr.iColumn value is set to the column number.
84972**
84973** Any errors cause an error message to be set in pParse.
84974*/
84975SQLITE_PRIVATE void sqlite3ResolveSelfReference(
84976  Parse *pParse,      /* Parsing context */
84977  Table *pTab,        /* The table being referenced */
84978  int type,           /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
84979  Expr *pExpr,        /* Expression to resolve.  May be NULL. */
84980  ExprList *pList     /* Expression list to resolve.  May be NUL. */
84981){
84982  SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
84983  NameContext sNC;                /* Name context for pParse->pNewTable */
84984
84985  assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
84986  memset(&sNC, 0, sizeof(sNC));
84987  memset(&sSrc, 0, sizeof(sSrc));
84988  sSrc.nSrc = 1;
84989  sSrc.a[0].zName = pTab->zName;
84990  sSrc.a[0].pTab = pTab;
84991  sSrc.a[0].iCursor = -1;
84992  sNC.pParse = pParse;
84993  sNC.pSrcList = &sSrc;
84994  sNC.ncFlags = type;
84995  if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
84996  if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
84997}
84998
84999/************** End of resolve.c *********************************************/
85000/************** Begin file expr.c ********************************************/
85001/*
85002** 2001 September 15
85003**
85004** The author disclaims copyright to this source code.  In place of
85005** a legal notice, here is a blessing:
85006**
85007**    May you do good and not evil.
85008**    May you find forgiveness for yourself and forgive others.
85009**    May you share freely, never taking more than you give.
85010**
85011*************************************************************************
85012** This file contains routines used for analyzing expressions and
85013** for generating VDBE code that evaluates expressions in SQLite.
85014*/
85015/* #include "sqliteInt.h" */
85016
85017/*
85018** Return the 'affinity' of the expression pExpr if any.
85019**
85020** If pExpr is a column, a reference to a column via an 'AS' alias,
85021** or a sub-select with a column as the return value, then the
85022** affinity of that column is returned. Otherwise, 0x00 is returned,
85023** indicating no affinity for the expression.
85024**
85025** i.e. the WHERE clause expressions in the following statements all
85026** have an affinity:
85027**
85028** CREATE TABLE t1(a);
85029** SELECT * FROM t1 WHERE a;
85030** SELECT a AS b FROM t1 WHERE b;
85031** SELECT * FROM t1 WHERE (select a from t1);
85032*/
85033SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
85034  int op;
85035  pExpr = sqlite3ExprSkipCollate(pExpr);
85036  if( pExpr->flags & EP_Generic ) return 0;
85037  op = pExpr->op;
85038  if( op==TK_SELECT ){
85039    assert( pExpr->flags&EP_xIsSelect );
85040    return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
85041  }
85042#ifndef SQLITE_OMIT_CAST
85043  if( op==TK_CAST ){
85044    assert( !ExprHasProperty(pExpr, EP_IntValue) );
85045    return sqlite3AffinityType(pExpr->u.zToken, 0);
85046  }
85047#endif
85048  if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
85049   && pExpr->pTab!=0
85050  ){
85051    /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
85052    ** a TK_COLUMN but was previously evaluated and cached in a register */
85053    int j = pExpr->iColumn;
85054    if( j<0 ) return SQLITE_AFF_INTEGER;
85055    assert( pExpr->pTab && j<pExpr->pTab->nCol );
85056    return pExpr->pTab->aCol[j].affinity;
85057  }
85058  return pExpr->affinity;
85059}
85060
85061/*
85062** Set the collating sequence for expression pExpr to be the collating
85063** sequence named by pToken.   Return a pointer to a new Expr node that
85064** implements the COLLATE operator.
85065**
85066** If a memory allocation error occurs, that fact is recorded in pParse->db
85067** and the pExpr parameter is returned unchanged.
85068*/
85069SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
85070  Parse *pParse,           /* Parsing context */
85071  Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
85072  const Token *pCollName,  /* Name of collating sequence */
85073  int dequote              /* True to dequote pCollName */
85074){
85075  if( pCollName->n>0 ){
85076    Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
85077    if( pNew ){
85078      pNew->pLeft = pExpr;
85079      pNew->flags |= EP_Collate|EP_Skip;
85080      pExpr = pNew;
85081    }
85082  }
85083  return pExpr;
85084}
85085SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
85086  Token s;
85087  assert( zC!=0 );
85088  s.z = zC;
85089  s.n = sqlite3Strlen30(s.z);
85090  return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
85091}
85092
85093/*
85094** Skip over any TK_COLLATE operators and any unlikely()
85095** or likelihood() function at the root of an expression.
85096*/
85097SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
85098  while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
85099    if( ExprHasProperty(pExpr, EP_Unlikely) ){
85100      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
85101      assert( pExpr->x.pList->nExpr>0 );
85102      assert( pExpr->op==TK_FUNCTION );
85103      pExpr = pExpr->x.pList->a[0].pExpr;
85104    }else{
85105      assert( pExpr->op==TK_COLLATE );
85106      pExpr = pExpr->pLeft;
85107    }
85108  }
85109  return pExpr;
85110}
85111
85112/*
85113** Return the collation sequence for the expression pExpr. If
85114** there is no defined collating sequence, return NULL.
85115**
85116** The collating sequence might be determined by a COLLATE operator
85117** or by the presence of a column with a defined collating sequence.
85118** COLLATE operators take first precedence.  Left operands take
85119** precedence over right operands.
85120*/
85121SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
85122  sqlite3 *db = pParse->db;
85123  CollSeq *pColl = 0;
85124  Expr *p = pExpr;
85125  while( p ){
85126    int op = p->op;
85127    if( p->flags & EP_Generic ) break;
85128    if( op==TK_CAST || op==TK_UPLUS ){
85129      p = p->pLeft;
85130      continue;
85131    }
85132    if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
85133      pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
85134      break;
85135    }
85136    if( (op==TK_AGG_COLUMN || op==TK_COLUMN
85137          || op==TK_REGISTER || op==TK_TRIGGER)
85138     && p->pTab!=0
85139    ){
85140      /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
85141      ** a TK_COLUMN but was previously evaluated and cached in a register */
85142      int j = p->iColumn;
85143      if( j>=0 ){
85144        const char *zColl = p->pTab->aCol[j].zColl;
85145        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
85146      }
85147      break;
85148    }
85149    if( p->flags & EP_Collate ){
85150      if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
85151        p = p->pLeft;
85152      }else{
85153        Expr *pNext  = p->pRight;
85154        /* The Expr.x union is never used at the same time as Expr.pRight */
85155        assert( p->x.pList==0 || p->pRight==0 );
85156        /* p->flags holds EP_Collate and p->pLeft->flags does not.  And
85157        ** p->x.pSelect cannot.  So if p->x.pLeft exists, it must hold at
85158        ** least one EP_Collate. Thus the following two ALWAYS. */
85159        if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
85160          int i;
85161          for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
85162            if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
85163              pNext = p->x.pList->a[i].pExpr;
85164              break;
85165            }
85166          }
85167        }
85168        p = pNext;
85169      }
85170    }else{
85171      break;
85172    }
85173  }
85174  if( sqlite3CheckCollSeq(pParse, pColl) ){
85175    pColl = 0;
85176  }
85177  return pColl;
85178}
85179
85180/*
85181** pExpr is an operand of a comparison operator.  aff2 is the
85182** type affinity of the other operand.  This routine returns the
85183** type affinity that should be used for the comparison operator.
85184*/
85185SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
85186  char aff1 = sqlite3ExprAffinity(pExpr);
85187  if( aff1 && aff2 ){
85188    /* Both sides of the comparison are columns. If one has numeric
85189    ** affinity, use that. Otherwise use no affinity.
85190    */
85191    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
85192      return SQLITE_AFF_NUMERIC;
85193    }else{
85194      return SQLITE_AFF_BLOB;
85195    }
85196  }else if( !aff1 && !aff2 ){
85197    /* Neither side of the comparison is a column.  Compare the
85198    ** results directly.
85199    */
85200    return SQLITE_AFF_BLOB;
85201  }else{
85202    /* One side is a column, the other is not. Use the columns affinity. */
85203    assert( aff1==0 || aff2==0 );
85204    return (aff1 + aff2);
85205  }
85206}
85207
85208/*
85209** pExpr is a comparison operator.  Return the type affinity that should
85210** be applied to both operands prior to doing the comparison.
85211*/
85212static char comparisonAffinity(Expr *pExpr){
85213  char aff;
85214  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
85215          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
85216          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
85217  assert( pExpr->pLeft );
85218  aff = sqlite3ExprAffinity(pExpr->pLeft);
85219  if( pExpr->pRight ){
85220    aff = sqlite3CompareAffinity(pExpr->pRight, aff);
85221  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
85222    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
85223  }else if( !aff ){
85224    aff = SQLITE_AFF_BLOB;
85225  }
85226  return aff;
85227}
85228
85229/*
85230** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
85231** idx_affinity is the affinity of an indexed column. Return true
85232** if the index with affinity idx_affinity may be used to implement
85233** the comparison in pExpr.
85234*/
85235SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
85236  char aff = comparisonAffinity(pExpr);
85237  switch( aff ){
85238    case SQLITE_AFF_BLOB:
85239      return 1;
85240    case SQLITE_AFF_TEXT:
85241      return idx_affinity==SQLITE_AFF_TEXT;
85242    default:
85243      return sqlite3IsNumericAffinity(idx_affinity);
85244  }
85245}
85246
85247/*
85248** Return the P5 value that should be used for a binary comparison
85249** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
85250*/
85251static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
85252  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
85253  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
85254  return aff;
85255}
85256
85257/*
85258** Return a pointer to the collation sequence that should be used by
85259** a binary comparison operator comparing pLeft and pRight.
85260**
85261** If the left hand expression has a collating sequence type, then it is
85262** used. Otherwise the collation sequence for the right hand expression
85263** is used, or the default (BINARY) if neither expression has a collating
85264** type.
85265**
85266** Argument pRight (but not pLeft) may be a null pointer. In this case,
85267** it is not considered.
85268*/
85269SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
85270  Parse *pParse,
85271  Expr *pLeft,
85272  Expr *pRight
85273){
85274  CollSeq *pColl;
85275  assert( pLeft );
85276  if( pLeft->flags & EP_Collate ){
85277    pColl = sqlite3ExprCollSeq(pParse, pLeft);
85278  }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
85279    pColl = sqlite3ExprCollSeq(pParse, pRight);
85280  }else{
85281    pColl = sqlite3ExprCollSeq(pParse, pLeft);
85282    if( !pColl ){
85283      pColl = sqlite3ExprCollSeq(pParse, pRight);
85284    }
85285  }
85286  return pColl;
85287}
85288
85289/*
85290** Generate code for a comparison operator.
85291*/
85292static int codeCompare(
85293  Parse *pParse,    /* The parsing (and code generating) context */
85294  Expr *pLeft,      /* The left operand */
85295  Expr *pRight,     /* The right operand */
85296  int opcode,       /* The comparison opcode */
85297  int in1, int in2, /* Register holding operands */
85298  int dest,         /* Jump here if true.  */
85299  int jumpIfNull    /* If true, jump if either operand is NULL */
85300){
85301  int p5;
85302  int addr;
85303  CollSeq *p4;
85304
85305  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
85306  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
85307  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
85308                           (void*)p4, P4_COLLSEQ);
85309  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
85310  return addr;
85311}
85312
85313#if SQLITE_MAX_EXPR_DEPTH>0
85314/*
85315** Check that argument nHeight is less than or equal to the maximum
85316** expression depth allowed. If it is not, leave an error message in
85317** pParse.
85318*/
85319SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
85320  int rc = SQLITE_OK;
85321  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
85322  if( nHeight>mxHeight ){
85323    sqlite3ErrorMsg(pParse,
85324       "Expression tree is too large (maximum depth %d)", mxHeight
85325    );
85326    rc = SQLITE_ERROR;
85327  }
85328  return rc;
85329}
85330
85331/* The following three functions, heightOfExpr(), heightOfExprList()
85332** and heightOfSelect(), are used to determine the maximum height
85333** of any expression tree referenced by the structure passed as the
85334** first argument.
85335**
85336** If this maximum height is greater than the current value pointed
85337** to by pnHeight, the second parameter, then set *pnHeight to that
85338** value.
85339*/
85340static void heightOfExpr(Expr *p, int *pnHeight){
85341  if( p ){
85342    if( p->nHeight>*pnHeight ){
85343      *pnHeight = p->nHeight;
85344    }
85345  }
85346}
85347static void heightOfExprList(ExprList *p, int *pnHeight){
85348  if( p ){
85349    int i;
85350    for(i=0; i<p->nExpr; i++){
85351      heightOfExpr(p->a[i].pExpr, pnHeight);
85352    }
85353  }
85354}
85355static void heightOfSelect(Select *p, int *pnHeight){
85356  if( p ){
85357    heightOfExpr(p->pWhere, pnHeight);
85358    heightOfExpr(p->pHaving, pnHeight);
85359    heightOfExpr(p->pLimit, pnHeight);
85360    heightOfExpr(p->pOffset, pnHeight);
85361    heightOfExprList(p->pEList, pnHeight);
85362    heightOfExprList(p->pGroupBy, pnHeight);
85363    heightOfExprList(p->pOrderBy, pnHeight);
85364    heightOfSelect(p->pPrior, pnHeight);
85365  }
85366}
85367
85368/*
85369** Set the Expr.nHeight variable in the structure passed as an
85370** argument. An expression with no children, Expr.pList or
85371** Expr.pSelect member has a height of 1. Any other expression
85372** has a height equal to the maximum height of any other
85373** referenced Expr plus one.
85374**
85375** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
85376** if appropriate.
85377*/
85378static void exprSetHeight(Expr *p){
85379  int nHeight = 0;
85380  heightOfExpr(p->pLeft, &nHeight);
85381  heightOfExpr(p->pRight, &nHeight);
85382  if( ExprHasProperty(p, EP_xIsSelect) ){
85383    heightOfSelect(p->x.pSelect, &nHeight);
85384  }else if( p->x.pList ){
85385    heightOfExprList(p->x.pList, &nHeight);
85386    p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
85387  }
85388  p->nHeight = nHeight + 1;
85389}
85390
85391/*
85392** Set the Expr.nHeight variable using the exprSetHeight() function. If
85393** the height is greater than the maximum allowed expression depth,
85394** leave an error in pParse.
85395**
85396** Also propagate all EP_Propagate flags from the Expr.x.pList into
85397** Expr.flags.
85398*/
85399SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
85400  if( pParse->nErr ) return;
85401  exprSetHeight(p);
85402  sqlite3ExprCheckHeight(pParse, p->nHeight);
85403}
85404
85405/*
85406** Return the maximum height of any expression tree referenced
85407** by the select statement passed as an argument.
85408*/
85409SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
85410  int nHeight = 0;
85411  heightOfSelect(p, &nHeight);
85412  return nHeight;
85413}
85414#else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
85415/*
85416** Propagate all EP_Propagate flags from the Expr.x.pList into
85417** Expr.flags.
85418*/
85419SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
85420  if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
85421    p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
85422  }
85423}
85424#define exprSetHeight(y)
85425#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
85426
85427/*
85428** This routine is the core allocator for Expr nodes.
85429**
85430** Construct a new expression node and return a pointer to it.  Memory
85431** for this node and for the pToken argument is a single allocation
85432** obtained from sqlite3DbMalloc().  The calling function
85433** is responsible for making sure the node eventually gets freed.
85434**
85435** If dequote is true, then the token (if it exists) is dequoted.
85436** If dequote is false, no dequoting is performed.  The deQuote
85437** parameter is ignored if pToken is NULL or if the token does not
85438** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
85439** then the EP_DblQuoted flag is set on the expression node.
85440**
85441** Special case:  If op==TK_INTEGER and pToken points to a string that
85442** can be translated into a 32-bit integer, then the token is not
85443** stored in u.zToken.  Instead, the integer values is written
85444** into u.iValue and the EP_IntValue flag is set.  No extra storage
85445** is allocated to hold the integer text and the dequote flag is ignored.
85446*/
85447SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
85448  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
85449  int op,                 /* Expression opcode */
85450  const Token *pToken,    /* Token argument.  Might be NULL */
85451  int dequote             /* True to dequote */
85452){
85453  Expr *pNew;
85454  int nExtra = 0;
85455  int iValue = 0;
85456
85457  if( pToken ){
85458    if( op!=TK_INTEGER || pToken->z==0
85459          || sqlite3GetInt32(pToken->z, &iValue)==0 ){
85460      nExtra = pToken->n+1;
85461      assert( iValue>=0 );
85462    }
85463  }
85464  pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
85465  if( pNew ){
85466    pNew->op = (u8)op;
85467    pNew->iAgg = -1;
85468    if( pToken ){
85469      if( nExtra==0 ){
85470        pNew->flags |= EP_IntValue;
85471        pNew->u.iValue = iValue;
85472      }else{
85473        int c;
85474        pNew->u.zToken = (char*)&pNew[1];
85475        assert( pToken->z!=0 || pToken->n==0 );
85476        if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
85477        pNew->u.zToken[pToken->n] = 0;
85478        if( dequote && nExtra>=3
85479             && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
85480          sqlite3Dequote(pNew->u.zToken);
85481          if( c=='"' ) pNew->flags |= EP_DblQuoted;
85482        }
85483      }
85484    }
85485#if SQLITE_MAX_EXPR_DEPTH>0
85486    pNew->nHeight = 1;
85487#endif
85488  }
85489  return pNew;
85490}
85491
85492/*
85493** Allocate a new expression node from a zero-terminated token that has
85494** already been dequoted.
85495*/
85496SQLITE_PRIVATE Expr *sqlite3Expr(
85497  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
85498  int op,                 /* Expression opcode */
85499  const char *zToken      /* Token argument.  Might be NULL */
85500){
85501  Token x;
85502  x.z = zToken;
85503  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
85504  return sqlite3ExprAlloc(db, op, &x, 0);
85505}
85506
85507/*
85508** Attach subtrees pLeft and pRight to the Expr node pRoot.
85509**
85510** If pRoot==NULL that means that a memory allocation error has occurred.
85511** In that case, delete the subtrees pLeft and pRight.
85512*/
85513SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
85514  sqlite3 *db,
85515  Expr *pRoot,
85516  Expr *pLeft,
85517  Expr *pRight
85518){
85519  if( pRoot==0 ){
85520    assert( db->mallocFailed );
85521    sqlite3ExprDelete(db, pLeft);
85522    sqlite3ExprDelete(db, pRight);
85523  }else{
85524    if( pRight ){
85525      pRoot->pRight = pRight;
85526      pRoot->flags |= EP_Propagate & pRight->flags;
85527    }
85528    if( pLeft ){
85529      pRoot->pLeft = pLeft;
85530      pRoot->flags |= EP_Propagate & pLeft->flags;
85531    }
85532    exprSetHeight(pRoot);
85533  }
85534}
85535
85536/*
85537** Allocate an Expr node which joins as many as two subtrees.
85538**
85539** One or both of the subtrees can be NULL.  Return a pointer to the new
85540** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
85541** free the subtrees and return NULL.
85542*/
85543SQLITE_PRIVATE Expr *sqlite3PExpr(
85544  Parse *pParse,          /* Parsing context */
85545  int op,                 /* Expression opcode */
85546  Expr *pLeft,            /* Left operand */
85547  Expr *pRight,           /* Right operand */
85548  const Token *pToken     /* Argument token */
85549){
85550  Expr *p;
85551  if( op==TK_AND && pLeft && pRight && pParse->nErr==0 ){
85552    /* Take advantage of short-circuit false optimization for AND */
85553    p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
85554  }else{
85555    p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
85556    sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
85557  }
85558  if( p ) {
85559    sqlite3ExprCheckHeight(pParse, p->nHeight);
85560  }
85561  return p;
85562}
85563
85564/*
85565** If the expression is always either TRUE or FALSE (respectively),
85566** then return 1.  If one cannot determine the truth value of the
85567** expression at compile-time return 0.
85568**
85569** This is an optimization.  If is OK to return 0 here even if
85570** the expression really is always false or false (a false negative).
85571** But it is a bug to return 1 if the expression might have different
85572** boolean values in different circumstances (a false positive.)
85573**
85574** Note that if the expression is part of conditional for a
85575** LEFT JOIN, then we cannot determine at compile-time whether or not
85576** is it true or false, so always return 0.
85577*/
85578static int exprAlwaysTrue(Expr *p){
85579  int v = 0;
85580  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
85581  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
85582  return v!=0;
85583}
85584static int exprAlwaysFalse(Expr *p){
85585  int v = 0;
85586  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
85587  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
85588  return v==0;
85589}
85590
85591/*
85592** Join two expressions using an AND operator.  If either expression is
85593** NULL, then just return the other expression.
85594**
85595** If one side or the other of the AND is known to be false, then instead
85596** of returning an AND expression, just return a constant expression with
85597** a value of false.
85598*/
85599SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
85600  if( pLeft==0 ){
85601    return pRight;
85602  }else if( pRight==0 ){
85603    return pLeft;
85604  }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
85605    sqlite3ExprDelete(db, pLeft);
85606    sqlite3ExprDelete(db, pRight);
85607    return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
85608  }else{
85609    Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
85610    sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
85611    return pNew;
85612  }
85613}
85614
85615/*
85616** Construct a new expression node for a function with multiple
85617** arguments.
85618*/
85619SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
85620  Expr *pNew;
85621  sqlite3 *db = pParse->db;
85622  assert( pToken );
85623  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
85624  if( pNew==0 ){
85625    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
85626    return 0;
85627  }
85628  pNew->x.pList = pList;
85629  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
85630  sqlite3ExprSetHeightAndFlags(pParse, pNew);
85631  return pNew;
85632}
85633
85634/*
85635** Assign a variable number to an expression that encodes a wildcard
85636** in the original SQL statement.
85637**
85638** Wildcards consisting of a single "?" are assigned the next sequential
85639** variable number.
85640**
85641** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
85642** sure "nnn" is not too be to avoid a denial of service attack when
85643** the SQL statement comes from an external source.
85644**
85645** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
85646** as the previous instance of the same wildcard.  Or if this is the first
85647** instance of the wildcard, the next sequential variable number is
85648** assigned.
85649*/
85650SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
85651  sqlite3 *db = pParse->db;
85652  const char *z;
85653
85654  if( pExpr==0 ) return;
85655  assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
85656  z = pExpr->u.zToken;
85657  assert( z!=0 );
85658  assert( z[0]!=0 );
85659  if( z[1]==0 ){
85660    /* Wildcard of the form "?".  Assign the next variable number */
85661    assert( z[0]=='?' );
85662    pExpr->iColumn = (ynVar)(++pParse->nVar);
85663  }else{
85664    ynVar x = 0;
85665    u32 n = sqlite3Strlen30(z);
85666    if( z[0]=='?' ){
85667      /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
85668      ** use it as the variable number */
85669      i64 i;
85670      int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
85671      pExpr->iColumn = x = (ynVar)i;
85672      testcase( i==0 );
85673      testcase( i==1 );
85674      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
85675      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
85676      if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
85677        sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
85678            db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
85679        x = 0;
85680      }
85681      if( i>pParse->nVar ){
85682        pParse->nVar = (int)i;
85683      }
85684    }else{
85685      /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
85686      ** number as the prior appearance of the same name, or if the name
85687      ** has never appeared before, reuse the same variable number
85688      */
85689      ynVar i;
85690      for(i=0; i<pParse->nzVar; i++){
85691        if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
85692          pExpr->iColumn = x = (ynVar)i+1;
85693          break;
85694        }
85695      }
85696      if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
85697    }
85698    if( x>0 ){
85699      if( x>pParse->nzVar ){
85700        char **a;
85701        a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
85702        if( a==0 ) return;  /* Error reported through db->mallocFailed */
85703        pParse->azVar = a;
85704        memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
85705        pParse->nzVar = x;
85706      }
85707      if( z[0]!='?' || pParse->azVar[x-1]==0 ){
85708        sqlite3DbFree(db, pParse->azVar[x-1]);
85709        pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
85710      }
85711    }
85712  }
85713  if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
85714    sqlite3ErrorMsg(pParse, "too many SQL variables");
85715  }
85716}
85717
85718/*
85719** Recursively delete an expression tree.
85720*/
85721SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
85722  if( p==0 ) return;
85723  /* Sanity check: Assert that the IntValue is non-negative if it exists */
85724  assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
85725  if( !ExprHasProperty(p, EP_TokenOnly) ){
85726    /* The Expr.x union is never used at the same time as Expr.pRight */
85727    assert( p->x.pList==0 || p->pRight==0 );
85728    sqlite3ExprDelete(db, p->pLeft);
85729    sqlite3ExprDelete(db, p->pRight);
85730    if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
85731    if( ExprHasProperty(p, EP_xIsSelect) ){
85732      sqlite3SelectDelete(db, p->x.pSelect);
85733    }else{
85734      sqlite3ExprListDelete(db, p->x.pList);
85735    }
85736  }
85737  if( !ExprHasProperty(p, EP_Static) ){
85738    sqlite3DbFree(db, p);
85739  }
85740}
85741
85742/*
85743** Return the number of bytes allocated for the expression structure
85744** passed as the first argument. This is always one of EXPR_FULLSIZE,
85745** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
85746*/
85747static int exprStructSize(Expr *p){
85748  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
85749  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
85750  return EXPR_FULLSIZE;
85751}
85752
85753/*
85754** The dupedExpr*Size() routines each return the number of bytes required
85755** to store a copy of an expression or expression tree.  They differ in
85756** how much of the tree is measured.
85757**
85758**     dupedExprStructSize()     Size of only the Expr structure
85759**     dupedExprNodeSize()       Size of Expr + space for token
85760**     dupedExprSize()           Expr + token + subtree components
85761**
85762***************************************************************************
85763**
85764** The dupedExprStructSize() function returns two values OR-ed together:
85765** (1) the space required for a copy of the Expr structure only and
85766** (2) the EP_xxx flags that indicate what the structure size should be.
85767** The return values is always one of:
85768**
85769**      EXPR_FULLSIZE
85770**      EXPR_REDUCEDSIZE   | EP_Reduced
85771**      EXPR_TOKENONLYSIZE | EP_TokenOnly
85772**
85773** The size of the structure can be found by masking the return value
85774** of this routine with 0xfff.  The flags can be found by masking the
85775** return value with EP_Reduced|EP_TokenOnly.
85776**
85777** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
85778** (unreduced) Expr objects as they or originally constructed by the parser.
85779** During expression analysis, extra information is computed and moved into
85780** later parts of teh Expr object and that extra information might get chopped
85781** off if the expression is reduced.  Note also that it does not work to
85782** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
85783** to reduce a pristine expression tree from the parser.  The implementation
85784** of dupedExprStructSize() contain multiple assert() statements that attempt
85785** to enforce this constraint.
85786*/
85787static int dupedExprStructSize(Expr *p, int flags){
85788  int nSize;
85789  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
85790  assert( EXPR_FULLSIZE<=0xfff );
85791  assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
85792  if( 0==(flags&EXPRDUP_REDUCE) ){
85793    nSize = EXPR_FULLSIZE;
85794  }else{
85795    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
85796    assert( !ExprHasProperty(p, EP_FromJoin) );
85797    assert( !ExprHasProperty(p, EP_MemToken) );
85798    assert( !ExprHasProperty(p, EP_NoReduce) );
85799    if( p->pLeft || p->x.pList ){
85800      nSize = EXPR_REDUCEDSIZE | EP_Reduced;
85801    }else{
85802      assert( p->pRight==0 );
85803      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
85804    }
85805  }
85806  return nSize;
85807}
85808
85809/*
85810** This function returns the space in bytes required to store the copy
85811** of the Expr structure and a copy of the Expr.u.zToken string (if that
85812** string is defined.)
85813*/
85814static int dupedExprNodeSize(Expr *p, int flags){
85815  int nByte = dupedExprStructSize(p, flags) & 0xfff;
85816  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
85817    nByte += sqlite3Strlen30(p->u.zToken)+1;
85818  }
85819  return ROUND8(nByte);
85820}
85821
85822/*
85823** Return the number of bytes required to create a duplicate of the
85824** expression passed as the first argument. The second argument is a
85825** mask containing EXPRDUP_XXX flags.
85826**
85827** The value returned includes space to create a copy of the Expr struct
85828** itself and the buffer referred to by Expr.u.zToken, if any.
85829**
85830** If the EXPRDUP_REDUCE flag is set, then the return value includes
85831** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
85832** and Expr.pRight variables (but not for any structures pointed to or
85833** descended from the Expr.x.pList or Expr.x.pSelect variables).
85834*/
85835static int dupedExprSize(Expr *p, int flags){
85836  int nByte = 0;
85837  if( p ){
85838    nByte = dupedExprNodeSize(p, flags);
85839    if( flags&EXPRDUP_REDUCE ){
85840      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
85841    }
85842  }
85843  return nByte;
85844}
85845
85846/*
85847** This function is similar to sqlite3ExprDup(), except that if pzBuffer
85848** is not NULL then *pzBuffer is assumed to point to a buffer large enough
85849** to store the copy of expression p, the copies of p->u.zToken
85850** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
85851** if any. Before returning, *pzBuffer is set to the first byte past the
85852** portion of the buffer copied into by this function.
85853*/
85854static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
85855  Expr *pNew = 0;                      /* Value to return */
85856  if( p ){
85857    const int isReduced = (flags&EXPRDUP_REDUCE);
85858    u8 *zAlloc;
85859    u32 staticFlag = 0;
85860
85861    assert( pzBuffer==0 || isReduced );
85862
85863    /* Figure out where to write the new Expr structure. */
85864    if( pzBuffer ){
85865      zAlloc = *pzBuffer;
85866      staticFlag = EP_Static;
85867    }else{
85868      zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
85869    }
85870    pNew = (Expr *)zAlloc;
85871
85872    if( pNew ){
85873      /* Set nNewSize to the size allocated for the structure pointed to
85874      ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
85875      ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
85876      ** by the copy of the p->u.zToken string (if any).
85877      */
85878      const unsigned nStructSize = dupedExprStructSize(p, flags);
85879      const int nNewSize = nStructSize & 0xfff;
85880      int nToken;
85881      if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
85882        nToken = sqlite3Strlen30(p->u.zToken) + 1;
85883      }else{
85884        nToken = 0;
85885      }
85886      if( isReduced ){
85887        assert( ExprHasProperty(p, EP_Reduced)==0 );
85888        memcpy(zAlloc, p, nNewSize);
85889      }else{
85890        int nSize = exprStructSize(p);
85891        memcpy(zAlloc, p, nSize);
85892        memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
85893      }
85894
85895      /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
85896      pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
85897      pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
85898      pNew->flags |= staticFlag;
85899
85900      /* Copy the p->u.zToken string, if any. */
85901      if( nToken ){
85902        char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
85903        memcpy(zToken, p->u.zToken, nToken);
85904      }
85905
85906      if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
85907        /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
85908        if( ExprHasProperty(p, EP_xIsSelect) ){
85909          pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
85910        }else{
85911          pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
85912        }
85913      }
85914
85915      /* Fill in pNew->pLeft and pNew->pRight. */
85916      if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
85917        zAlloc += dupedExprNodeSize(p, flags);
85918        if( ExprHasProperty(pNew, EP_Reduced) ){
85919          pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
85920          pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
85921        }
85922        if( pzBuffer ){
85923          *pzBuffer = zAlloc;
85924        }
85925      }else{
85926        if( !ExprHasProperty(p, EP_TokenOnly) ){
85927          pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
85928          pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
85929        }
85930      }
85931
85932    }
85933  }
85934  return pNew;
85935}
85936
85937/*
85938** Create and return a deep copy of the object passed as the second
85939** argument. If an OOM condition is encountered, NULL is returned
85940** and the db->mallocFailed flag set.
85941*/
85942#ifndef SQLITE_OMIT_CTE
85943static With *withDup(sqlite3 *db, With *p){
85944  With *pRet = 0;
85945  if( p ){
85946    int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
85947    pRet = sqlite3DbMallocZero(db, nByte);
85948    if( pRet ){
85949      int i;
85950      pRet->nCte = p->nCte;
85951      for(i=0; i<p->nCte; i++){
85952        pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
85953        pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
85954        pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
85955      }
85956    }
85957  }
85958  return pRet;
85959}
85960#else
85961# define withDup(x,y) 0
85962#endif
85963
85964/*
85965** The following group of routines make deep copies of expressions,
85966** expression lists, ID lists, and select statements.  The copies can
85967** be deleted (by being passed to their respective ...Delete() routines)
85968** without effecting the originals.
85969**
85970** The expression list, ID, and source lists return by sqlite3ExprListDup(),
85971** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
85972** by subsequent calls to sqlite*ListAppend() routines.
85973**
85974** Any tables that the SrcList might point to are not duplicated.
85975**
85976** The flags parameter contains a combination of the EXPRDUP_XXX flags.
85977** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
85978** truncated version of the usual Expr structure that will be stored as
85979** part of the in-memory representation of the database schema.
85980*/
85981SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
85982  return exprDup(db, p, flags, 0);
85983}
85984SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
85985  ExprList *pNew;
85986  struct ExprList_item *pItem, *pOldItem;
85987  int i;
85988  if( p==0 ) return 0;
85989  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
85990  if( pNew==0 ) return 0;
85991  pNew->nExpr = i = p->nExpr;
85992  if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
85993  pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
85994  if( pItem==0 ){
85995    sqlite3DbFree(db, pNew);
85996    return 0;
85997  }
85998  pOldItem = p->a;
85999  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
86000    Expr *pOldExpr = pOldItem->pExpr;
86001    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
86002    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
86003    pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
86004    pItem->sortOrder = pOldItem->sortOrder;
86005    pItem->done = 0;
86006    pItem->bSpanIsTab = pOldItem->bSpanIsTab;
86007    pItem->u = pOldItem->u;
86008  }
86009  return pNew;
86010}
86011
86012/*
86013** If cursors, triggers, views and subqueries are all omitted from
86014** the build, then none of the following routines, except for
86015** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
86016** called with a NULL argument.
86017*/
86018#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
86019 || !defined(SQLITE_OMIT_SUBQUERY)
86020SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
86021  SrcList *pNew;
86022  int i;
86023  int nByte;
86024  if( p==0 ) return 0;
86025  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
86026  pNew = sqlite3DbMallocRaw(db, nByte );
86027  if( pNew==0 ) return 0;
86028  pNew->nSrc = pNew->nAlloc = p->nSrc;
86029  for(i=0; i<p->nSrc; i++){
86030    struct SrcList_item *pNewItem = &pNew->a[i];
86031    struct SrcList_item *pOldItem = &p->a[i];
86032    Table *pTab;
86033    pNewItem->pSchema = pOldItem->pSchema;
86034    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
86035    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
86036    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
86037    pNewItem->fg = pOldItem->fg;
86038    pNewItem->iCursor = pOldItem->iCursor;
86039    pNewItem->addrFillSub = pOldItem->addrFillSub;
86040    pNewItem->regReturn = pOldItem->regReturn;
86041    if( pNewItem->fg.isIndexedBy ){
86042      pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
86043    }
86044    pNewItem->pIBIndex = pOldItem->pIBIndex;
86045    if( pNewItem->fg.isTabFunc ){
86046      pNewItem->u1.pFuncArg =
86047          sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
86048    }
86049    pTab = pNewItem->pTab = pOldItem->pTab;
86050    if( pTab ){
86051      pTab->nRef++;
86052    }
86053    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
86054    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
86055    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
86056    pNewItem->colUsed = pOldItem->colUsed;
86057  }
86058  return pNew;
86059}
86060SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
86061  IdList *pNew;
86062  int i;
86063  if( p==0 ) return 0;
86064  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
86065  if( pNew==0 ) return 0;
86066  pNew->nId = p->nId;
86067  pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
86068  if( pNew->a==0 ){
86069    sqlite3DbFree(db, pNew);
86070    return 0;
86071  }
86072  /* Note that because the size of the allocation for p->a[] is not
86073  ** necessarily a power of two, sqlite3IdListAppend() may not be called
86074  ** on the duplicate created by this function. */
86075  for(i=0; i<p->nId; i++){
86076    struct IdList_item *pNewItem = &pNew->a[i];
86077    struct IdList_item *pOldItem = &p->a[i];
86078    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
86079    pNewItem->idx = pOldItem->idx;
86080  }
86081  return pNew;
86082}
86083SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
86084  Select *pNew, *pPrior;
86085  if( p==0 ) return 0;
86086  pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
86087  if( pNew==0 ) return 0;
86088  pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
86089  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
86090  pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
86091  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
86092  pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
86093  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
86094  pNew->op = p->op;
86095  pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
86096  if( pPrior ) pPrior->pNext = pNew;
86097  pNew->pNext = 0;
86098  pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
86099  pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
86100  pNew->iLimit = 0;
86101  pNew->iOffset = 0;
86102  pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
86103  pNew->addrOpenEphm[0] = -1;
86104  pNew->addrOpenEphm[1] = -1;
86105  pNew->nSelectRow = p->nSelectRow;
86106  pNew->pWith = withDup(db, p->pWith);
86107  sqlite3SelectSetName(pNew, p->zSelName);
86108  return pNew;
86109}
86110#else
86111SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
86112  assert( p==0 );
86113  return 0;
86114}
86115#endif
86116
86117
86118/*
86119** Add a new element to the end of an expression list.  If pList is
86120** initially NULL, then create a new expression list.
86121**
86122** If a memory allocation error occurs, the entire list is freed and
86123** NULL is returned.  If non-NULL is returned, then it is guaranteed
86124** that the new entry was successfully appended.
86125*/
86126SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
86127  Parse *pParse,          /* Parsing context */
86128  ExprList *pList,        /* List to which to append. Might be NULL */
86129  Expr *pExpr             /* Expression to be appended. Might be NULL */
86130){
86131  sqlite3 *db = pParse->db;
86132  if( pList==0 ){
86133    pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
86134    if( pList==0 ){
86135      goto no_mem;
86136    }
86137    pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
86138    if( pList->a==0 ) goto no_mem;
86139  }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
86140    struct ExprList_item *a;
86141    assert( pList->nExpr>0 );
86142    a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
86143    if( a==0 ){
86144      goto no_mem;
86145    }
86146    pList->a = a;
86147  }
86148  assert( pList->a!=0 );
86149  if( 1 ){
86150    struct ExprList_item *pItem = &pList->a[pList->nExpr++];
86151    memset(pItem, 0, sizeof(*pItem));
86152    pItem->pExpr = pExpr;
86153  }
86154  return pList;
86155
86156no_mem:
86157  /* Avoid leaking memory if malloc has failed. */
86158  sqlite3ExprDelete(db, pExpr);
86159  sqlite3ExprListDelete(db, pList);
86160  return 0;
86161}
86162
86163/*
86164** Set the sort order for the last element on the given ExprList.
86165*/
86166SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
86167  if( p==0 ) return;
86168  assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
86169  assert( p->nExpr>0 );
86170  if( iSortOrder<0 ){
86171    assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
86172    return;
86173  }
86174  p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
86175}
86176
86177/*
86178** Set the ExprList.a[].zName element of the most recently added item
86179** on the expression list.
86180**
86181** pList might be NULL following an OOM error.  But pName should never be
86182** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
86183** is set.
86184*/
86185SQLITE_PRIVATE void sqlite3ExprListSetName(
86186  Parse *pParse,          /* Parsing context */
86187  ExprList *pList,        /* List to which to add the span. */
86188  Token *pName,           /* Name to be added */
86189  int dequote             /* True to cause the name to be dequoted */
86190){
86191  assert( pList!=0 || pParse->db->mallocFailed!=0 );
86192  if( pList ){
86193    struct ExprList_item *pItem;
86194    assert( pList->nExpr>0 );
86195    pItem = &pList->a[pList->nExpr-1];
86196    assert( pItem->zName==0 );
86197    pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
86198    if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
86199  }
86200}
86201
86202/*
86203** Set the ExprList.a[].zSpan element of the most recently added item
86204** on the expression list.
86205**
86206** pList might be NULL following an OOM error.  But pSpan should never be
86207** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
86208** is set.
86209*/
86210SQLITE_PRIVATE void sqlite3ExprListSetSpan(
86211  Parse *pParse,          /* Parsing context */
86212  ExprList *pList,        /* List to which to add the span. */
86213  ExprSpan *pSpan         /* The span to be added */
86214){
86215  sqlite3 *db = pParse->db;
86216  assert( pList!=0 || db->mallocFailed!=0 );
86217  if( pList ){
86218    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
86219    assert( pList->nExpr>0 );
86220    assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
86221    sqlite3DbFree(db, pItem->zSpan);
86222    pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
86223                                    (int)(pSpan->zEnd - pSpan->zStart));
86224  }
86225}
86226
86227/*
86228** If the expression list pEList contains more than iLimit elements,
86229** leave an error message in pParse.
86230*/
86231SQLITE_PRIVATE void sqlite3ExprListCheckLength(
86232  Parse *pParse,
86233  ExprList *pEList,
86234  const char *zObject
86235){
86236  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
86237  testcase( pEList && pEList->nExpr==mx );
86238  testcase( pEList && pEList->nExpr==mx+1 );
86239  if( pEList && pEList->nExpr>mx ){
86240    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
86241  }
86242}
86243
86244/*
86245** Delete an entire expression list.
86246*/
86247SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
86248  int i;
86249  struct ExprList_item *pItem;
86250  if( pList==0 ) return;
86251  assert( pList->a!=0 || pList->nExpr==0 );
86252  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
86253    sqlite3ExprDelete(db, pItem->pExpr);
86254    sqlite3DbFree(db, pItem->zName);
86255    sqlite3DbFree(db, pItem->zSpan);
86256  }
86257  sqlite3DbFree(db, pList->a);
86258  sqlite3DbFree(db, pList);
86259}
86260
86261/*
86262** Return the bitwise-OR of all Expr.flags fields in the given
86263** ExprList.
86264*/
86265SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
86266  int i;
86267  u32 m = 0;
86268  if( pList ){
86269    for(i=0; i<pList->nExpr; i++){
86270       Expr *pExpr = pList->a[i].pExpr;
86271       if( ALWAYS(pExpr) ) m |= pExpr->flags;
86272    }
86273  }
86274  return m;
86275}
86276
86277/*
86278** These routines are Walker callbacks used to check expressions to
86279** see if they are "constant" for some definition of constant.  The
86280** Walker.eCode value determines the type of "constant" we are looking
86281** for.
86282**
86283** These callback routines are used to implement the following:
86284**
86285**     sqlite3ExprIsConstant()                  pWalker->eCode==1
86286**     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
86287**     sqlite3ExprIsTableConstant()             pWalker->eCode==3
86288**     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
86289**
86290** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
86291** is found to not be a constant.
86292**
86293** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
86294** in a CREATE TABLE statement.  The Walker.eCode value is 5 when parsing
86295** an existing schema and 4 when processing a new statement.  A bound
86296** parameter raises an error for new statements, but is silently converted
86297** to NULL for existing schemas.  This allows sqlite_master tables that
86298** contain a bound parameter because they were generated by older versions
86299** of SQLite to be parsed by newer versions of SQLite without raising a
86300** malformed schema error.
86301*/
86302static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
86303
86304  /* If pWalker->eCode is 2 then any term of the expression that comes from
86305  ** the ON or USING clauses of a left join disqualifies the expression
86306  ** from being considered constant. */
86307  if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
86308    pWalker->eCode = 0;
86309    return WRC_Abort;
86310  }
86311
86312  switch( pExpr->op ){
86313    /* Consider functions to be constant if all their arguments are constant
86314    ** and either pWalker->eCode==4 or 5 or the function has the
86315    ** SQLITE_FUNC_CONST flag. */
86316    case TK_FUNCTION:
86317      if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
86318        return WRC_Continue;
86319      }else{
86320        pWalker->eCode = 0;
86321        return WRC_Abort;
86322      }
86323    case TK_ID:
86324    case TK_COLUMN:
86325    case TK_AGG_FUNCTION:
86326    case TK_AGG_COLUMN:
86327      testcase( pExpr->op==TK_ID );
86328      testcase( pExpr->op==TK_COLUMN );
86329      testcase( pExpr->op==TK_AGG_FUNCTION );
86330      testcase( pExpr->op==TK_AGG_COLUMN );
86331      if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
86332        return WRC_Continue;
86333      }else{
86334        pWalker->eCode = 0;
86335        return WRC_Abort;
86336      }
86337    case TK_VARIABLE:
86338      if( pWalker->eCode==5 ){
86339        /* Silently convert bound parameters that appear inside of CREATE
86340        ** statements into a NULL when parsing the CREATE statement text out
86341        ** of the sqlite_master table */
86342        pExpr->op = TK_NULL;
86343      }else if( pWalker->eCode==4 ){
86344        /* A bound parameter in a CREATE statement that originates from
86345        ** sqlite3_prepare() causes an error */
86346        pWalker->eCode = 0;
86347        return WRC_Abort;
86348      }
86349      /* Fall through */
86350    default:
86351      testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
86352      testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
86353      return WRC_Continue;
86354  }
86355}
86356static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
86357  UNUSED_PARAMETER(NotUsed);
86358  pWalker->eCode = 0;
86359  return WRC_Abort;
86360}
86361static int exprIsConst(Expr *p, int initFlag, int iCur){
86362  Walker w;
86363  memset(&w, 0, sizeof(w));
86364  w.eCode = initFlag;
86365  w.xExprCallback = exprNodeIsConstant;
86366  w.xSelectCallback = selectNodeIsConstant;
86367  w.u.iCur = iCur;
86368  sqlite3WalkExpr(&w, p);
86369  return w.eCode;
86370}
86371
86372/*
86373** Walk an expression tree.  Return non-zero if the expression is constant
86374** and 0 if it involves variables or function calls.
86375**
86376** For the purposes of this function, a double-quoted string (ex: "abc")
86377** is considered a variable but a single-quoted string (ex: 'abc') is
86378** a constant.
86379*/
86380SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
86381  return exprIsConst(p, 1, 0);
86382}
86383
86384/*
86385** Walk an expression tree.  Return non-zero if the expression is constant
86386** that does no originate from the ON or USING clauses of a join.
86387** Return 0 if it involves variables or function calls or terms from
86388** an ON or USING clause.
86389*/
86390SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
86391  return exprIsConst(p, 2, 0);
86392}
86393
86394/*
86395** Walk an expression tree.  Return non-zero if the expression is constant
86396** for any single row of the table with cursor iCur.  In other words, the
86397** expression must not refer to any non-deterministic function nor any
86398** table other than iCur.
86399*/
86400SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
86401  return exprIsConst(p, 3, iCur);
86402}
86403
86404/*
86405** Walk an expression tree.  Return non-zero if the expression is constant
86406** or a function call with constant arguments.  Return and 0 if there
86407** are any variables.
86408**
86409** For the purposes of this function, a double-quoted string (ex: "abc")
86410** is considered a variable but a single-quoted string (ex: 'abc') is
86411** a constant.
86412*/
86413SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
86414  assert( isInit==0 || isInit==1 );
86415  return exprIsConst(p, 4+isInit, 0);
86416}
86417
86418/*
86419** If the expression p codes a constant integer that is small enough
86420** to fit in a 32-bit integer, return 1 and put the value of the integer
86421** in *pValue.  If the expression is not an integer or if it is too big
86422** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
86423*/
86424SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
86425  int rc = 0;
86426
86427  /* If an expression is an integer literal that fits in a signed 32-bit
86428  ** integer, then the EP_IntValue flag will have already been set */
86429  assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
86430           || sqlite3GetInt32(p->u.zToken, &rc)==0 );
86431
86432  if( p->flags & EP_IntValue ){
86433    *pValue = p->u.iValue;
86434    return 1;
86435  }
86436  switch( p->op ){
86437    case TK_UPLUS: {
86438      rc = sqlite3ExprIsInteger(p->pLeft, pValue);
86439      break;
86440    }
86441    case TK_UMINUS: {
86442      int v;
86443      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
86444        assert( v!=(-2147483647-1) );
86445        *pValue = -v;
86446        rc = 1;
86447      }
86448      break;
86449    }
86450    default: break;
86451  }
86452  return rc;
86453}
86454
86455/*
86456** Return FALSE if there is no chance that the expression can be NULL.
86457**
86458** If the expression might be NULL or if the expression is too complex
86459** to tell return TRUE.
86460**
86461** This routine is used as an optimization, to skip OP_IsNull opcodes
86462** when we know that a value cannot be NULL.  Hence, a false positive
86463** (returning TRUE when in fact the expression can never be NULL) might
86464** be a small performance hit but is otherwise harmless.  On the other
86465** hand, a false negative (returning FALSE when the result could be NULL)
86466** will likely result in an incorrect answer.  So when in doubt, return
86467** TRUE.
86468*/
86469SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
86470  u8 op;
86471  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
86472  op = p->op;
86473  if( op==TK_REGISTER ) op = p->op2;
86474  switch( op ){
86475    case TK_INTEGER:
86476    case TK_STRING:
86477    case TK_FLOAT:
86478    case TK_BLOB:
86479      return 0;
86480    case TK_COLUMN:
86481      assert( p->pTab!=0 );
86482      return ExprHasProperty(p, EP_CanBeNull) ||
86483             (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
86484    default:
86485      return 1;
86486  }
86487}
86488
86489/*
86490** Return TRUE if the given expression is a constant which would be
86491** unchanged by OP_Affinity with the affinity given in the second
86492** argument.
86493**
86494** This routine is used to determine if the OP_Affinity operation
86495** can be omitted.  When in doubt return FALSE.  A false negative
86496** is harmless.  A false positive, however, can result in the wrong
86497** answer.
86498*/
86499SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
86500  u8 op;
86501  if( aff==SQLITE_AFF_BLOB ) return 1;
86502  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
86503  op = p->op;
86504  if( op==TK_REGISTER ) op = p->op2;
86505  switch( op ){
86506    case TK_INTEGER: {
86507      return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
86508    }
86509    case TK_FLOAT: {
86510      return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
86511    }
86512    case TK_STRING: {
86513      return aff==SQLITE_AFF_TEXT;
86514    }
86515    case TK_BLOB: {
86516      return 1;
86517    }
86518    case TK_COLUMN: {
86519      assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
86520      return p->iColumn<0
86521          && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
86522    }
86523    default: {
86524      return 0;
86525    }
86526  }
86527}
86528
86529/*
86530** Return TRUE if the given string is a row-id column name.
86531*/
86532SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
86533  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
86534  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
86535  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
86536  return 0;
86537}
86538
86539/*
86540** Return true if we are able to the IN operator optimization on a
86541** query of the form
86542**
86543**       x IN (SELECT ...)
86544**
86545** Where the SELECT... clause is as specified by the parameter to this
86546** routine.
86547**
86548** The Select object passed in has already been preprocessed and no
86549** errors have been found.
86550*/
86551#ifndef SQLITE_OMIT_SUBQUERY
86552static int isCandidateForInOpt(Select *p){
86553  SrcList *pSrc;
86554  ExprList *pEList;
86555  Table *pTab;
86556  if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
86557  if( p->pPrior ) return 0;              /* Not a compound SELECT */
86558  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
86559    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
86560    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
86561    return 0; /* No DISTINCT keyword and no aggregate functions */
86562  }
86563  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
86564  if( p->pLimit ) return 0;              /* Has no LIMIT clause */
86565  assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
86566  if( p->pWhere ) return 0;              /* Has no WHERE clause */
86567  pSrc = p->pSrc;
86568  assert( pSrc!=0 );
86569  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
86570  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
86571  pTab = pSrc->a[0].pTab;
86572  if( NEVER(pTab==0) ) return 0;
86573  assert( pTab->pSelect==0 );            /* FROM clause is not a view */
86574  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
86575  pEList = p->pEList;
86576  if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
86577  if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
86578  return 1;
86579}
86580#endif /* SQLITE_OMIT_SUBQUERY */
86581
86582/*
86583** Code an OP_Once instruction and allocate space for its flag. Return the
86584** address of the new instruction.
86585*/
86586SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
86587  Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
86588  return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
86589}
86590
86591/*
86592** Generate code that checks the left-most column of index table iCur to see if
86593** it contains any NULL entries.  Cause the register at regHasNull to be set
86594** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
86595** to be set to NULL if iCur contains one or more NULL values.
86596*/
86597static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
86598  int addr1;
86599  sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
86600  addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
86601  sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
86602  sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
86603  VdbeComment((v, "first_entry_in(%d)", iCur));
86604  sqlite3VdbeJumpHere(v, addr1);
86605}
86606
86607
86608#ifndef SQLITE_OMIT_SUBQUERY
86609/*
86610** The argument is an IN operator with a list (not a subquery) on the
86611** right-hand side.  Return TRUE if that list is constant.
86612*/
86613static int sqlite3InRhsIsConstant(Expr *pIn){
86614  Expr *pLHS;
86615  int res;
86616  assert( !ExprHasProperty(pIn, EP_xIsSelect) );
86617  pLHS = pIn->pLeft;
86618  pIn->pLeft = 0;
86619  res = sqlite3ExprIsConstant(pIn);
86620  pIn->pLeft = pLHS;
86621  return res;
86622}
86623#endif
86624
86625/*
86626** This function is used by the implementation of the IN (...) operator.
86627** The pX parameter is the expression on the RHS of the IN operator, which
86628** might be either a list of expressions or a subquery.
86629**
86630** The job of this routine is to find or create a b-tree object that can
86631** be used either to test for membership in the RHS set or to iterate through
86632** all members of the RHS set, skipping duplicates.
86633**
86634** A cursor is opened on the b-tree object that is the RHS of the IN operator
86635** and pX->iTable is set to the index of that cursor.
86636**
86637** The returned value of this function indicates the b-tree type, as follows:
86638**
86639**   IN_INDEX_ROWID      - The cursor was opened on a database table.
86640**   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
86641**   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
86642**   IN_INDEX_EPH        - The cursor was opened on a specially created and
86643**                         populated epheremal table.
86644**   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
86645**                         implemented as a sequence of comparisons.
86646**
86647** An existing b-tree might be used if the RHS expression pX is a simple
86648** subquery such as:
86649**
86650**     SELECT <column> FROM <table>
86651**
86652** If the RHS of the IN operator is a list or a more complex subquery, then
86653** an ephemeral table might need to be generated from the RHS and then
86654** pX->iTable made to point to the ephemeral table instead of an
86655** existing table.
86656**
86657** The inFlags parameter must contain exactly one of the bits
86658** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP.  If inFlags contains
86659** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
86660** fast membership test.  When the IN_INDEX_LOOP bit is set, the
86661** IN index will be used to loop over all values of the RHS of the
86662** IN operator.
86663**
86664** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
86665** through the set members) then the b-tree must not contain duplicates.
86666** An epheremal table must be used unless the selected <column> is guaranteed
86667** to be unique - either because it is an INTEGER PRIMARY KEY or it
86668** has a UNIQUE constraint or UNIQUE index.
86669**
86670** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
86671** for fast set membership tests) then an epheremal table must
86672** be used unless <column> is an INTEGER PRIMARY KEY or an index can
86673** be found with <column> as its left-most column.
86674**
86675** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
86676** if the RHS of the IN operator is a list (not a subquery) then this
86677** routine might decide that creating an ephemeral b-tree for membership
86678** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
86679** calling routine should implement the IN operator using a sequence
86680** of Eq or Ne comparison operations.
86681**
86682** When the b-tree is being used for membership tests, the calling function
86683** might need to know whether or not the RHS side of the IN operator
86684** contains a NULL.  If prRhsHasNull is not a NULL pointer and
86685** if there is any chance that the (...) might contain a NULL value at
86686** runtime, then a register is allocated and the register number written
86687** to *prRhsHasNull. If there is no chance that the (...) contains a
86688** NULL value, then *prRhsHasNull is left unchanged.
86689**
86690** If a register is allocated and its location stored in *prRhsHasNull, then
86691** the value in that register will be NULL if the b-tree contains one or more
86692** NULL values, and it will be some non-NULL value if the b-tree contains no
86693** NULL values.
86694*/
86695#ifndef SQLITE_OMIT_SUBQUERY
86696SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
86697  Select *p;                            /* SELECT to the right of IN operator */
86698  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
86699  int iTab = pParse->nTab++;            /* Cursor of the RHS table */
86700  int mustBeUnique;                     /* True if RHS must be unique */
86701  Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
86702
86703  assert( pX->op==TK_IN );
86704  mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
86705
86706  /* Check to see if an existing table or index can be used to
86707  ** satisfy the query.  This is preferable to generating a new
86708  ** ephemeral table.
86709  */
86710  p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
86711  if( pParse->nErr==0 && isCandidateForInOpt(p) ){
86712    sqlite3 *db = pParse->db;              /* Database connection */
86713    Table *pTab;                           /* Table <table>. */
86714    Expr *pExpr;                           /* Expression <column> */
86715    i16 iCol;                              /* Index of column <column> */
86716    i16 iDb;                               /* Database idx for pTab */
86717
86718    assert( p );                        /* Because of isCandidateForInOpt(p) */
86719    assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
86720    assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
86721    assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
86722    pTab = p->pSrc->a[0].pTab;
86723    pExpr = p->pEList->a[0].pExpr;
86724    iCol = (i16)pExpr->iColumn;
86725
86726    /* Code an OP_Transaction and OP_TableLock for <table>. */
86727    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
86728    sqlite3CodeVerifySchema(pParse, iDb);
86729    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
86730
86731    /* This function is only called from two places. In both cases the vdbe
86732    ** has already been allocated. So assume sqlite3GetVdbe() is always
86733    ** successful here.
86734    */
86735    assert(v);
86736    if( iCol<0 ){
86737      int iAddr = sqlite3CodeOnce(pParse);
86738      VdbeCoverage(v);
86739
86740      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
86741      eType = IN_INDEX_ROWID;
86742
86743      sqlite3VdbeJumpHere(v, iAddr);
86744    }else{
86745      Index *pIdx;                         /* Iterator variable */
86746
86747      /* The collation sequence used by the comparison. If an index is to
86748      ** be used in place of a temp-table, it must be ordered according
86749      ** to this collation sequence.  */
86750      CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
86751
86752      /* Check that the affinity that will be used to perform the
86753      ** comparison is the same as the affinity of the column. If
86754      ** it is not, it is not possible to use any index.
86755      */
86756      int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
86757
86758      for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
86759        if( (pIdx->aiColumn[0]==iCol)
86760         && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
86761         && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
86762        ){
86763          int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
86764          sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
86765          sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
86766          VdbeComment((v, "%s", pIdx->zName));
86767          assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
86768          eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
86769
86770          if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
86771            *prRhsHasNull = ++pParse->nMem;
86772            sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
86773          }
86774          sqlite3VdbeJumpHere(v, iAddr);
86775        }
86776      }
86777    }
86778  }
86779
86780  /* If no preexisting index is available for the IN clause
86781  ** and IN_INDEX_NOOP is an allowed reply
86782  ** and the RHS of the IN operator is a list, not a subquery
86783  ** and the RHS is not contant or has two or fewer terms,
86784  ** then it is not worth creating an ephemeral table to evaluate
86785  ** the IN operator so return IN_INDEX_NOOP.
86786  */
86787  if( eType==0
86788   && (inFlags & IN_INDEX_NOOP_OK)
86789   && !ExprHasProperty(pX, EP_xIsSelect)
86790   && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
86791  ){
86792    eType = IN_INDEX_NOOP;
86793  }
86794
86795
86796  if( eType==0 ){
86797    /* Could not find an existing table or index to use as the RHS b-tree.
86798    ** We will have to generate an ephemeral table to do the job.
86799    */
86800    u32 savedNQueryLoop = pParse->nQueryLoop;
86801    int rMayHaveNull = 0;
86802    eType = IN_INDEX_EPH;
86803    if( inFlags & IN_INDEX_LOOP ){
86804      pParse->nQueryLoop = 0;
86805      if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
86806        eType = IN_INDEX_ROWID;
86807      }
86808    }else if( prRhsHasNull ){
86809      *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
86810    }
86811    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
86812    pParse->nQueryLoop = savedNQueryLoop;
86813  }else{
86814    pX->iTable = iTab;
86815  }
86816  return eType;
86817}
86818#endif
86819
86820/*
86821** Generate code for scalar subqueries used as a subquery expression, EXISTS,
86822** or IN operators.  Examples:
86823**
86824**     (SELECT a FROM b)          -- subquery
86825**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
86826**     x IN (4,5,11)              -- IN operator with list on right-hand side
86827**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
86828**
86829** The pExpr parameter describes the expression that contains the IN
86830** operator or subquery.
86831**
86832** If parameter isRowid is non-zero, then expression pExpr is guaranteed
86833** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
86834** to some integer key column of a table B-Tree. In this case, use an
86835** intkey B-Tree to store the set of IN(...) values instead of the usual
86836** (slower) variable length keys B-Tree.
86837**
86838** If rMayHaveNull is non-zero, that means that the operation is an IN
86839** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
86840** All this routine does is initialize the register given by rMayHaveNull
86841** to NULL.  Calling routines will take care of changing this register
86842** value to non-NULL if the RHS is NULL-free.
86843**
86844** For a SELECT or EXISTS operator, return the register that holds the
86845** result.  For IN operators or if an error occurs, the return value is 0.
86846*/
86847#ifndef SQLITE_OMIT_SUBQUERY
86848SQLITE_PRIVATE int sqlite3CodeSubselect(
86849  Parse *pParse,          /* Parsing context */
86850  Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
86851  int rHasNullFlag,       /* Register that records whether NULLs exist in RHS */
86852  int isRowid             /* If true, LHS of IN operator is a rowid */
86853){
86854  int jmpIfDynamic = -1;                      /* One-time test address */
86855  int rReg = 0;                           /* Register storing resulting */
86856  Vdbe *v = sqlite3GetVdbe(pParse);
86857  if( NEVER(v==0) ) return 0;
86858  sqlite3ExprCachePush(pParse);
86859
86860  /* This code must be run in its entirety every time it is encountered
86861  ** if any of the following is true:
86862  **
86863  **    *  The right-hand side is a correlated subquery
86864  **    *  The right-hand side is an expression list containing variables
86865  **    *  We are inside a trigger
86866  **
86867  ** If all of the above are false, then we can run this code just once
86868  ** save the results, and reuse the same result on subsequent invocations.
86869  */
86870  if( !ExprHasProperty(pExpr, EP_VarSelect) ){
86871    jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
86872  }
86873
86874#ifndef SQLITE_OMIT_EXPLAIN
86875  if( pParse->explain==2 ){
86876    char *zMsg = sqlite3MPrintf(
86877        pParse->db, "EXECUTE %s%s SUBQUERY %d", jmpIfDynamic>=0?"":"CORRELATED ",
86878        pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
86879    );
86880    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
86881  }
86882#endif
86883
86884  switch( pExpr->op ){
86885    case TK_IN: {
86886      char affinity;              /* Affinity of the LHS of the IN */
86887      int addr;                   /* Address of OP_OpenEphemeral instruction */
86888      Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
86889      KeyInfo *pKeyInfo = 0;      /* Key information */
86890
86891      affinity = sqlite3ExprAffinity(pLeft);
86892
86893      /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
86894      ** expression it is handled the same way.  An ephemeral table is
86895      ** filled with single-field index keys representing the results
86896      ** from the SELECT or the <exprlist>.
86897      **
86898      ** If the 'x' expression is a column value, or the SELECT...
86899      ** statement returns a column value, then the affinity of that
86900      ** column is used to build the index keys. If both 'x' and the
86901      ** SELECT... statement are columns, then numeric affinity is used
86902      ** if either column has NUMERIC or INTEGER affinity. If neither
86903      ** 'x' nor the SELECT... statement are columns, then numeric affinity
86904      ** is used.
86905      */
86906      pExpr->iTable = pParse->nTab++;
86907      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
86908      pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
86909
86910      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
86911        /* Case 1:     expr IN (SELECT ...)
86912        **
86913        ** Generate code to write the results of the select into the temporary
86914        ** table allocated and opened above.
86915        */
86916        Select *pSelect = pExpr->x.pSelect;
86917        SelectDest dest;
86918        ExprList *pEList;
86919
86920        assert( !isRowid );
86921        sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
86922        dest.affSdst = (u8)affinity;
86923        assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
86924        pSelect->iLimit = 0;
86925        testcase( pSelect->selFlags & SF_Distinct );
86926        testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
86927        if( sqlite3Select(pParse, pSelect, &dest) ){
86928          sqlite3KeyInfoUnref(pKeyInfo);
86929          return 0;
86930        }
86931        pEList = pSelect->pEList;
86932        assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
86933        assert( pEList!=0 );
86934        assert( pEList->nExpr>0 );
86935        assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
86936        pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
86937                                                         pEList->a[0].pExpr);
86938      }else if( ALWAYS(pExpr->x.pList!=0) ){
86939        /* Case 2:     expr IN (exprlist)
86940        **
86941        ** For each expression, build an index key from the evaluation and
86942        ** store it in the temporary table. If <expr> is a column, then use
86943        ** that columns affinity when building index keys. If <expr> is not
86944        ** a column, use numeric affinity.
86945        */
86946        int i;
86947        ExprList *pList = pExpr->x.pList;
86948        struct ExprList_item *pItem;
86949        int r1, r2, r3;
86950
86951        if( !affinity ){
86952          affinity = SQLITE_AFF_BLOB;
86953        }
86954        if( pKeyInfo ){
86955          assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
86956          pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
86957        }
86958
86959        /* Loop through each expression in <exprlist>. */
86960        r1 = sqlite3GetTempReg(pParse);
86961        r2 = sqlite3GetTempReg(pParse);
86962        if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
86963        for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
86964          Expr *pE2 = pItem->pExpr;
86965          int iValToIns;
86966
86967          /* If the expression is not constant then we will need to
86968          ** disable the test that was generated above that makes sure
86969          ** this code only executes once.  Because for a non-constant
86970          ** expression we need to rerun this code each time.
86971          */
86972          if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
86973            sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
86974            jmpIfDynamic = -1;
86975          }
86976
86977          /* Evaluate the expression and insert it into the temp table */
86978          if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
86979            sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
86980          }else{
86981            r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
86982            if( isRowid ){
86983              sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
86984                                sqlite3VdbeCurrentAddr(v)+2);
86985              VdbeCoverage(v);
86986              sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
86987            }else{
86988              sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
86989              sqlite3ExprCacheAffinityChange(pParse, r3, 1);
86990              sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
86991            }
86992          }
86993        }
86994        sqlite3ReleaseTempReg(pParse, r1);
86995        sqlite3ReleaseTempReg(pParse, r2);
86996      }
86997      if( pKeyInfo ){
86998        sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
86999      }
87000      break;
87001    }
87002
87003    case TK_EXISTS:
87004    case TK_SELECT:
87005    default: {
87006      /* If this has to be a scalar SELECT.  Generate code to put the
87007      ** value of this select in a memory cell and record the number
87008      ** of the memory cell in iColumn.  If this is an EXISTS, write
87009      ** an integer 0 (not exists) or 1 (exists) into a memory cell
87010      ** and record that memory cell in iColumn.
87011      */
87012      Select *pSel;                         /* SELECT statement to encode */
87013      SelectDest dest;                      /* How to deal with SELECt result */
87014
87015      testcase( pExpr->op==TK_EXISTS );
87016      testcase( pExpr->op==TK_SELECT );
87017      assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
87018
87019      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
87020      pSel = pExpr->x.pSelect;
87021      sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
87022      if( pExpr->op==TK_SELECT ){
87023        dest.eDest = SRT_Mem;
87024        dest.iSdst = dest.iSDParm;
87025        sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
87026        VdbeComment((v, "Init subquery result"));
87027      }else{
87028        dest.eDest = SRT_Exists;
87029        sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
87030        VdbeComment((v, "Init EXISTS result"));
87031      }
87032      sqlite3ExprDelete(pParse->db, pSel->pLimit);
87033      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
87034                                  &sqlite3IntTokens[1]);
87035      pSel->iLimit = 0;
87036      pSel->selFlags &= ~SF_MultiValue;
87037      if( sqlite3Select(pParse, pSel, &dest) ){
87038        return 0;
87039      }
87040      rReg = dest.iSDParm;
87041      ExprSetVVAProperty(pExpr, EP_NoReduce);
87042      break;
87043    }
87044  }
87045
87046  if( rHasNullFlag ){
87047    sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
87048  }
87049
87050  if( jmpIfDynamic>=0 ){
87051    sqlite3VdbeJumpHere(v, jmpIfDynamic);
87052  }
87053  sqlite3ExprCachePop(pParse);
87054
87055  return rReg;
87056}
87057#endif /* SQLITE_OMIT_SUBQUERY */
87058
87059#ifndef SQLITE_OMIT_SUBQUERY
87060/*
87061** Generate code for an IN expression.
87062**
87063**      x IN (SELECT ...)
87064**      x IN (value, value, ...)
87065**
87066** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
87067** is an array of zero or more values.  The expression is true if the LHS is
87068** contained within the RHS.  The value of the expression is unknown (NULL)
87069** if the LHS is NULL or if the LHS is not contained within the RHS and the
87070** RHS contains one or more NULL values.
87071**
87072** This routine generates code that jumps to destIfFalse if the LHS is not
87073** contained within the RHS.  If due to NULLs we cannot determine if the LHS
87074** is contained in the RHS then jump to destIfNull.  If the LHS is contained
87075** within the RHS then fall through.
87076*/
87077static void sqlite3ExprCodeIN(
87078  Parse *pParse,        /* Parsing and code generating context */
87079  Expr *pExpr,          /* The IN expression */
87080  int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
87081  int destIfNull        /* Jump here if the results are unknown due to NULLs */
87082){
87083  int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
87084  char affinity;        /* Comparison affinity to use */
87085  int eType;            /* Type of the RHS */
87086  int r1;               /* Temporary use register */
87087  Vdbe *v;              /* Statement under construction */
87088
87089  /* Compute the RHS.   After this step, the table with cursor
87090  ** pExpr->iTable will contains the values that make up the RHS.
87091  */
87092  v = pParse->pVdbe;
87093  assert( v!=0 );       /* OOM detected prior to this routine */
87094  VdbeNoopComment((v, "begin IN expr"));
87095  eType = sqlite3FindInIndex(pParse, pExpr,
87096                             IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
87097                             destIfFalse==destIfNull ? 0 : &rRhsHasNull);
87098
87099  /* Figure out the affinity to use to create a key from the results
87100  ** of the expression. affinityStr stores a static string suitable for
87101  ** P4 of OP_MakeRecord.
87102  */
87103  affinity = comparisonAffinity(pExpr);
87104
87105  /* Code the LHS, the <expr> from "<expr> IN (...)".
87106  */
87107  sqlite3ExprCachePush(pParse);
87108  r1 = sqlite3GetTempReg(pParse);
87109  sqlite3ExprCode(pParse, pExpr->pLeft, r1);
87110
87111  /* If sqlite3FindInIndex() did not find or create an index that is
87112  ** suitable for evaluating the IN operator, then evaluate using a
87113  ** sequence of comparisons.
87114  */
87115  if( eType==IN_INDEX_NOOP ){
87116    ExprList *pList = pExpr->x.pList;
87117    CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
87118    int labelOk = sqlite3VdbeMakeLabel(v);
87119    int r2, regToFree;
87120    int regCkNull = 0;
87121    int ii;
87122    assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
87123    if( destIfNull!=destIfFalse ){
87124      regCkNull = sqlite3GetTempReg(pParse);
87125      sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
87126    }
87127    for(ii=0; ii<pList->nExpr; ii++){
87128      r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
87129      if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
87130        sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
87131      }
87132      if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
87133        sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
87134                          (void*)pColl, P4_COLLSEQ);
87135        VdbeCoverageIf(v, ii<pList->nExpr-1);
87136        VdbeCoverageIf(v, ii==pList->nExpr-1);
87137        sqlite3VdbeChangeP5(v, affinity);
87138      }else{
87139        assert( destIfNull==destIfFalse );
87140        sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
87141                          (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
87142        sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
87143      }
87144      sqlite3ReleaseTempReg(pParse, regToFree);
87145    }
87146    if( regCkNull ){
87147      sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
87148      sqlite3VdbeGoto(v, destIfFalse);
87149    }
87150    sqlite3VdbeResolveLabel(v, labelOk);
87151    sqlite3ReleaseTempReg(pParse, regCkNull);
87152  }else{
87153
87154    /* If the LHS is NULL, then the result is either false or NULL depending
87155    ** on whether the RHS is empty or not, respectively.
87156    */
87157    if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
87158      if( destIfNull==destIfFalse ){
87159        /* Shortcut for the common case where the false and NULL outcomes are
87160        ** the same. */
87161        sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
87162      }else{
87163        int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
87164        sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
87165        VdbeCoverage(v);
87166        sqlite3VdbeGoto(v, destIfNull);
87167        sqlite3VdbeJumpHere(v, addr1);
87168      }
87169    }
87170
87171    if( eType==IN_INDEX_ROWID ){
87172      /* In this case, the RHS is the ROWID of table b-tree
87173      */
87174      sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
87175      sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
87176      VdbeCoverage(v);
87177    }else{
87178      /* In this case, the RHS is an index b-tree.
87179      */
87180      sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
87181
87182      /* If the set membership test fails, then the result of the
87183      ** "x IN (...)" expression must be either 0 or NULL. If the set
87184      ** contains no NULL values, then the result is 0. If the set
87185      ** contains one or more NULL values, then the result of the
87186      ** expression is also NULL.
87187      */
87188      assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
87189      if( rRhsHasNull==0 ){
87190        /* This branch runs if it is known at compile time that the RHS
87191        ** cannot contain NULL values. This happens as the result
87192        ** of a "NOT NULL" constraint in the database schema.
87193        **
87194        ** Also run this branch if NULL is equivalent to FALSE
87195        ** for this particular IN operator.
87196        */
87197        sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
87198        VdbeCoverage(v);
87199      }else{
87200        /* In this branch, the RHS of the IN might contain a NULL and
87201        ** the presence of a NULL on the RHS makes a difference in the
87202        ** outcome.
87203        */
87204        int addr1;
87205
87206        /* First check to see if the LHS is contained in the RHS.  If so,
87207        ** then the answer is TRUE the presence of NULLs in the RHS does
87208        ** not matter.  If the LHS is not contained in the RHS, then the
87209        ** answer is NULL if the RHS contains NULLs and the answer is
87210        ** FALSE if the RHS is NULL-free.
87211        */
87212        addr1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
87213        VdbeCoverage(v);
87214        sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
87215        VdbeCoverage(v);
87216        sqlite3VdbeGoto(v, destIfFalse);
87217        sqlite3VdbeJumpHere(v, addr1);
87218      }
87219    }
87220  }
87221  sqlite3ReleaseTempReg(pParse, r1);
87222  sqlite3ExprCachePop(pParse);
87223  VdbeComment((v, "end IN expr"));
87224}
87225#endif /* SQLITE_OMIT_SUBQUERY */
87226
87227#ifndef SQLITE_OMIT_FLOATING_POINT
87228/*
87229** Generate an instruction that will put the floating point
87230** value described by z[0..n-1] into register iMem.
87231**
87232** The z[] string will probably not be zero-terminated.  But the
87233** z[n] character is guaranteed to be something that does not look
87234** like the continuation of the number.
87235*/
87236static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
87237  if( ALWAYS(z!=0) ){
87238    double value;
87239    sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
87240    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
87241    if( negateFlag ) value = -value;
87242    sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
87243  }
87244}
87245#endif
87246
87247
87248/*
87249** Generate an instruction that will put the integer describe by
87250** text z[0..n-1] into register iMem.
87251**
87252** Expr.u.zToken is always UTF8 and zero-terminated.
87253*/
87254static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
87255  Vdbe *v = pParse->pVdbe;
87256  if( pExpr->flags & EP_IntValue ){
87257    int i = pExpr->u.iValue;
87258    assert( i>=0 );
87259    if( negFlag ) i = -i;
87260    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
87261  }else{
87262    int c;
87263    i64 value;
87264    const char *z = pExpr->u.zToken;
87265    assert( z!=0 );
87266    c = sqlite3DecOrHexToI64(z, &value);
87267    if( c==0 || (c==2 && negFlag) ){
87268      if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
87269      sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
87270    }else{
87271#ifdef SQLITE_OMIT_FLOATING_POINT
87272      sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
87273#else
87274#ifndef SQLITE_OMIT_HEX_INTEGER
87275      if( sqlite3_strnicmp(z,"0x",2)==0 ){
87276        sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
87277      }else
87278#endif
87279      {
87280        codeReal(v, z, negFlag, iMem);
87281      }
87282#endif
87283    }
87284  }
87285}
87286
87287/*
87288** Clear a cache entry.
87289*/
87290static void cacheEntryClear(Parse *pParse, struct yColCache *p){
87291  if( p->tempReg ){
87292    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
87293      pParse->aTempReg[pParse->nTempReg++] = p->iReg;
87294    }
87295    p->tempReg = 0;
87296  }
87297}
87298
87299
87300/*
87301** Record in the column cache that a particular column from a
87302** particular table is stored in a particular register.
87303*/
87304SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
87305  int i;
87306  int minLru;
87307  int idxLru;
87308  struct yColCache *p;
87309
87310  /* Unless an error has occurred, register numbers are always positive. */
87311  assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
87312  assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
87313
87314  /* The SQLITE_ColumnCache flag disables the column cache.  This is used
87315  ** for testing only - to verify that SQLite always gets the same answer
87316  ** with and without the column cache.
87317  */
87318  if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
87319
87320  /* First replace any existing entry.
87321  **
87322  ** Actually, the way the column cache is currently used, we are guaranteed
87323  ** that the object will never already be in cache.  Verify this guarantee.
87324  */
87325#ifndef NDEBUG
87326  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
87327    assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
87328  }
87329#endif
87330
87331  /* Find an empty slot and replace it */
87332  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
87333    if( p->iReg==0 ){
87334      p->iLevel = pParse->iCacheLevel;
87335      p->iTable = iTab;
87336      p->iColumn = iCol;
87337      p->iReg = iReg;
87338      p->tempReg = 0;
87339      p->lru = pParse->iCacheCnt++;
87340      return;
87341    }
87342  }
87343
87344  /* Replace the last recently used */
87345  minLru = 0x7fffffff;
87346  idxLru = -1;
87347  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
87348    if( p->lru<minLru ){
87349      idxLru = i;
87350      minLru = p->lru;
87351    }
87352  }
87353  if( ALWAYS(idxLru>=0) ){
87354    p = &pParse->aColCache[idxLru];
87355    p->iLevel = pParse->iCacheLevel;
87356    p->iTable = iTab;
87357    p->iColumn = iCol;
87358    p->iReg = iReg;
87359    p->tempReg = 0;
87360    p->lru = pParse->iCacheCnt++;
87361    return;
87362  }
87363}
87364
87365/*
87366** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
87367** Purge the range of registers from the column cache.
87368*/
87369SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
87370  int i;
87371  int iLast = iReg + nReg - 1;
87372  struct yColCache *p;
87373  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
87374    int r = p->iReg;
87375    if( r>=iReg && r<=iLast ){
87376      cacheEntryClear(pParse, p);
87377      p->iReg = 0;
87378    }
87379  }
87380}
87381
87382/*
87383** Remember the current column cache context.  Any new entries added
87384** added to the column cache after this call are removed when the
87385** corresponding pop occurs.
87386*/
87387SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
87388  pParse->iCacheLevel++;
87389#ifdef SQLITE_DEBUG
87390  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
87391    printf("PUSH to %d\n", pParse->iCacheLevel);
87392  }
87393#endif
87394}
87395
87396/*
87397** Remove from the column cache any entries that were added since the
87398** the previous sqlite3ExprCachePush operation.  In other words, restore
87399** the cache to the state it was in prior the most recent Push.
87400*/
87401SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
87402  int i;
87403  struct yColCache *p;
87404  assert( pParse->iCacheLevel>=1 );
87405  pParse->iCacheLevel--;
87406#ifdef SQLITE_DEBUG
87407  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
87408    printf("POP  to %d\n", pParse->iCacheLevel);
87409  }
87410#endif
87411  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
87412    if( p->iReg && p->iLevel>pParse->iCacheLevel ){
87413      cacheEntryClear(pParse, p);
87414      p->iReg = 0;
87415    }
87416  }
87417}
87418
87419/*
87420** When a cached column is reused, make sure that its register is
87421** no longer available as a temp register.  ticket #3879:  that same
87422** register might be in the cache in multiple places, so be sure to
87423** get them all.
87424*/
87425static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
87426  int i;
87427  struct yColCache *p;
87428  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
87429    if( p->iReg==iReg ){
87430      p->tempReg = 0;
87431    }
87432  }
87433}
87434
87435/* Generate code that will load into register regOut a value that is
87436** appropriate for the iIdxCol-th column of index pIdx.
87437*/
87438SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
87439  Parse *pParse,  /* The parsing context */
87440  Index *pIdx,    /* The index whose column is to be loaded */
87441  int iTabCur,    /* Cursor pointing to a table row */
87442  int iIdxCol,    /* The column of the index to be loaded */
87443  int regOut      /* Store the index column value in this register */
87444){
87445  i16 iTabCol = pIdx->aiColumn[iIdxCol];
87446  if( iTabCol==XN_EXPR ){
87447    assert( pIdx->aColExpr );
87448    assert( pIdx->aColExpr->nExpr>iIdxCol );
87449    pParse->iSelfTab = iTabCur;
87450    sqlite3ExprCode(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
87451  }else{
87452    sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
87453                                    iTabCol, regOut);
87454  }
87455}
87456
87457/*
87458** Generate code to extract the value of the iCol-th column of a table.
87459*/
87460SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
87461  Vdbe *v,        /* The VDBE under construction */
87462  Table *pTab,    /* The table containing the value */
87463  int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
87464  int iCol,       /* Index of the column to extract */
87465  int regOut      /* Extract the value into this register */
87466){
87467  if( iCol<0 || iCol==pTab->iPKey ){
87468    sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
87469  }else{
87470    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
87471    int x = iCol;
87472    if( !HasRowid(pTab) ){
87473      x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
87474    }
87475    sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
87476  }
87477  if( iCol>=0 ){
87478    sqlite3ColumnDefault(v, pTab, iCol, regOut);
87479  }
87480}
87481
87482/*
87483** Generate code that will extract the iColumn-th column from
87484** table pTab and store the column value in a register.  An effort
87485** is made to store the column value in register iReg, but this is
87486** not guaranteed.  The location of the column value is returned.
87487**
87488** There must be an open cursor to pTab in iTable when this routine
87489** is called.  If iColumn<0 then code is generated that extracts the rowid.
87490*/
87491SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
87492  Parse *pParse,   /* Parsing and code generating context */
87493  Table *pTab,     /* Description of the table we are reading from */
87494  int iColumn,     /* Index of the table column */
87495  int iTable,      /* The cursor pointing to the table */
87496  int iReg,        /* Store results here */
87497  u8 p5            /* P5 value for OP_Column */
87498){
87499  Vdbe *v = pParse->pVdbe;
87500  int i;
87501  struct yColCache *p;
87502
87503  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
87504    if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
87505      p->lru = pParse->iCacheCnt++;
87506      sqlite3ExprCachePinRegister(pParse, p->iReg);
87507      return p->iReg;
87508    }
87509  }
87510  assert( v!=0 );
87511  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
87512  if( p5 ){
87513    sqlite3VdbeChangeP5(v, p5);
87514  }else{
87515    sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
87516  }
87517  return iReg;
87518}
87519
87520/*
87521** Clear all column cache entries.
87522*/
87523SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
87524  int i;
87525  struct yColCache *p;
87526
87527#if SQLITE_DEBUG
87528  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
87529    printf("CLEAR\n");
87530  }
87531#endif
87532  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
87533    if( p->iReg ){
87534      cacheEntryClear(pParse, p);
87535      p->iReg = 0;
87536    }
87537  }
87538}
87539
87540/*
87541** Record the fact that an affinity change has occurred on iCount
87542** registers starting with iStart.
87543*/
87544SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
87545  sqlite3ExprCacheRemove(pParse, iStart, iCount);
87546}
87547
87548/*
87549** Generate code to move content from registers iFrom...iFrom+nReg-1
87550** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
87551*/
87552SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
87553  assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
87554  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
87555  sqlite3ExprCacheRemove(pParse, iFrom, nReg);
87556}
87557
87558#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
87559/*
87560** Return true if any register in the range iFrom..iTo (inclusive)
87561** is used as part of the column cache.
87562**
87563** This routine is used within assert() and testcase() macros only
87564** and does not appear in a normal build.
87565*/
87566static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
87567  int i;
87568  struct yColCache *p;
87569  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
87570    int r = p->iReg;
87571    if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
87572  }
87573  return 0;
87574}
87575#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
87576
87577/*
87578** Convert an expression node to a TK_REGISTER
87579*/
87580static void exprToRegister(Expr *p, int iReg){
87581  p->op2 = p->op;
87582  p->op = TK_REGISTER;
87583  p->iTable = iReg;
87584  ExprClearProperty(p, EP_Skip);
87585}
87586
87587/*
87588** Generate code into the current Vdbe to evaluate the given
87589** expression.  Attempt to store the results in register "target".
87590** Return the register where results are stored.
87591**
87592** With this routine, there is no guarantee that results will
87593** be stored in target.  The result might be stored in some other
87594** register if it is convenient to do so.  The calling function
87595** must check the return code and move the results to the desired
87596** register.
87597*/
87598SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
87599  Vdbe *v = pParse->pVdbe;  /* The VM under construction */
87600  int op;                   /* The opcode being coded */
87601  int inReg = target;       /* Results stored in register inReg */
87602  int regFree1 = 0;         /* If non-zero free this temporary register */
87603  int regFree2 = 0;         /* If non-zero free this temporary register */
87604  int r1, r2, r3, r4;       /* Various register numbers */
87605  sqlite3 *db = pParse->db; /* The database connection */
87606  Expr tempX;               /* Temporary expression node */
87607
87608  assert( target>0 && target<=pParse->nMem );
87609  if( v==0 ){
87610    assert( pParse->db->mallocFailed );
87611    return 0;
87612  }
87613
87614  if( pExpr==0 ){
87615    op = TK_NULL;
87616  }else{
87617    op = pExpr->op;
87618  }
87619  switch( op ){
87620    case TK_AGG_COLUMN: {
87621      AggInfo *pAggInfo = pExpr->pAggInfo;
87622      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
87623      if( !pAggInfo->directMode ){
87624        assert( pCol->iMem>0 );
87625        inReg = pCol->iMem;
87626        break;
87627      }else if( pAggInfo->useSortingIdx ){
87628        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
87629                              pCol->iSorterColumn, target);
87630        break;
87631      }
87632      /* Otherwise, fall thru into the TK_COLUMN case */
87633    }
87634    case TK_COLUMN: {
87635      int iTab = pExpr->iTable;
87636      if( iTab<0 ){
87637        if( pParse->ckBase>0 ){
87638          /* Generating CHECK constraints or inserting into partial index */
87639          inReg = pExpr->iColumn + pParse->ckBase;
87640          break;
87641        }else{
87642          /* Coding an expression that is part of an index where column names
87643          ** in the index refer to the table to which the index belongs */
87644          iTab = pParse->iSelfTab;
87645        }
87646      }
87647      inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
87648                               pExpr->iColumn, iTab, target,
87649                               pExpr->op2);
87650      break;
87651    }
87652    case TK_INTEGER: {
87653      codeInteger(pParse, pExpr, 0, target);
87654      break;
87655    }
87656#ifndef SQLITE_OMIT_FLOATING_POINT
87657    case TK_FLOAT: {
87658      assert( !ExprHasProperty(pExpr, EP_IntValue) );
87659      codeReal(v, pExpr->u.zToken, 0, target);
87660      break;
87661    }
87662#endif
87663    case TK_STRING: {
87664      assert( !ExprHasProperty(pExpr, EP_IntValue) );
87665      sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
87666      break;
87667    }
87668    case TK_NULL: {
87669      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
87670      break;
87671    }
87672#ifndef SQLITE_OMIT_BLOB_LITERAL
87673    case TK_BLOB: {
87674      int n;
87675      const char *z;
87676      char *zBlob;
87677      assert( !ExprHasProperty(pExpr, EP_IntValue) );
87678      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
87679      assert( pExpr->u.zToken[1]=='\'' );
87680      z = &pExpr->u.zToken[2];
87681      n = sqlite3Strlen30(z) - 1;
87682      assert( z[n]=='\'' );
87683      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
87684      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
87685      break;
87686    }
87687#endif
87688    case TK_VARIABLE: {
87689      assert( !ExprHasProperty(pExpr, EP_IntValue) );
87690      assert( pExpr->u.zToken!=0 );
87691      assert( pExpr->u.zToken[0]!=0 );
87692      sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
87693      if( pExpr->u.zToken[1]!=0 ){
87694        assert( pExpr->u.zToken[0]=='?'
87695             || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
87696        sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
87697      }
87698      break;
87699    }
87700    case TK_REGISTER: {
87701      inReg = pExpr->iTable;
87702      break;
87703    }
87704#ifndef SQLITE_OMIT_CAST
87705    case TK_CAST: {
87706      /* Expressions of the form:   CAST(pLeft AS token) */
87707      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
87708      if( inReg!=target ){
87709        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
87710        inReg = target;
87711      }
87712      sqlite3VdbeAddOp2(v, OP_Cast, target,
87713                        sqlite3AffinityType(pExpr->u.zToken, 0));
87714      testcase( usedAsColumnCache(pParse, inReg, inReg) );
87715      sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
87716      break;
87717    }
87718#endif /* SQLITE_OMIT_CAST */
87719    case TK_LT:
87720    case TK_LE:
87721    case TK_GT:
87722    case TK_GE:
87723    case TK_NE:
87724    case TK_EQ: {
87725      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
87726      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
87727      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
87728                  r1, r2, inReg, SQLITE_STOREP2);
87729      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
87730      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
87731      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
87732      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
87733      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
87734      assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
87735      testcase( regFree1==0 );
87736      testcase( regFree2==0 );
87737      break;
87738    }
87739    case TK_IS:
87740    case TK_ISNOT: {
87741      testcase( op==TK_IS );
87742      testcase( op==TK_ISNOT );
87743      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
87744      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
87745      op = (op==TK_IS) ? TK_EQ : TK_NE;
87746      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
87747                  r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
87748      VdbeCoverageIf(v, op==TK_EQ);
87749      VdbeCoverageIf(v, op==TK_NE);
87750      testcase( regFree1==0 );
87751      testcase( regFree2==0 );
87752      break;
87753    }
87754    case TK_AND:
87755    case TK_OR:
87756    case TK_PLUS:
87757    case TK_STAR:
87758    case TK_MINUS:
87759    case TK_REM:
87760    case TK_BITAND:
87761    case TK_BITOR:
87762    case TK_SLASH:
87763    case TK_LSHIFT:
87764    case TK_RSHIFT:
87765    case TK_CONCAT: {
87766      assert( TK_AND==OP_And );            testcase( op==TK_AND );
87767      assert( TK_OR==OP_Or );              testcase( op==TK_OR );
87768      assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
87769      assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
87770      assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
87771      assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
87772      assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
87773      assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
87774      assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
87775      assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
87776      assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
87777      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
87778      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
87779      sqlite3VdbeAddOp3(v, op, r2, r1, target);
87780      testcase( regFree1==0 );
87781      testcase( regFree2==0 );
87782      break;
87783    }
87784    case TK_UMINUS: {
87785      Expr *pLeft = pExpr->pLeft;
87786      assert( pLeft );
87787      if( pLeft->op==TK_INTEGER ){
87788        codeInteger(pParse, pLeft, 1, target);
87789#ifndef SQLITE_OMIT_FLOATING_POINT
87790      }else if( pLeft->op==TK_FLOAT ){
87791        assert( !ExprHasProperty(pExpr, EP_IntValue) );
87792        codeReal(v, pLeft->u.zToken, 1, target);
87793#endif
87794      }else{
87795        tempX.op = TK_INTEGER;
87796        tempX.flags = EP_IntValue|EP_TokenOnly;
87797        tempX.u.iValue = 0;
87798        r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
87799        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
87800        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
87801        testcase( regFree2==0 );
87802      }
87803      inReg = target;
87804      break;
87805    }
87806    case TK_BITNOT:
87807    case TK_NOT: {
87808      assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
87809      assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
87810      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
87811      testcase( regFree1==0 );
87812      inReg = target;
87813      sqlite3VdbeAddOp2(v, op, r1, inReg);
87814      break;
87815    }
87816    case TK_ISNULL:
87817    case TK_NOTNULL: {
87818      int addr;
87819      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
87820      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
87821      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
87822      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
87823      testcase( regFree1==0 );
87824      addr = sqlite3VdbeAddOp1(v, op, r1);
87825      VdbeCoverageIf(v, op==TK_ISNULL);
87826      VdbeCoverageIf(v, op==TK_NOTNULL);
87827      sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
87828      sqlite3VdbeJumpHere(v, addr);
87829      break;
87830    }
87831    case TK_AGG_FUNCTION: {
87832      AggInfo *pInfo = pExpr->pAggInfo;
87833      if( pInfo==0 ){
87834        assert( !ExprHasProperty(pExpr, EP_IntValue) );
87835        sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
87836      }else{
87837        inReg = pInfo->aFunc[pExpr->iAgg].iMem;
87838      }
87839      break;
87840    }
87841    case TK_FUNCTION: {
87842      ExprList *pFarg;       /* List of function arguments */
87843      int nFarg;             /* Number of function arguments */
87844      FuncDef *pDef;         /* The function definition object */
87845      int nId;               /* Length of the function name in bytes */
87846      const char *zId;       /* The function name */
87847      u32 constMask = 0;     /* Mask of function arguments that are constant */
87848      int i;                 /* Loop counter */
87849      u8 enc = ENC(db);      /* The text encoding used by this database */
87850      CollSeq *pColl = 0;    /* A collating sequence */
87851
87852      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
87853      if( ExprHasProperty(pExpr, EP_TokenOnly) ){
87854        pFarg = 0;
87855      }else{
87856        pFarg = pExpr->x.pList;
87857      }
87858      nFarg = pFarg ? pFarg->nExpr : 0;
87859      assert( !ExprHasProperty(pExpr, EP_IntValue) );
87860      zId = pExpr->u.zToken;
87861      nId = sqlite3Strlen30(zId);
87862      pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
87863      if( pDef==0 || pDef->xFunc==0 ){
87864        sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
87865        break;
87866      }
87867
87868      /* Attempt a direct implementation of the built-in COALESCE() and
87869      ** IFNULL() functions.  This avoids unnecessary evaluation of
87870      ** arguments past the first non-NULL argument.
87871      */
87872      if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
87873        int endCoalesce = sqlite3VdbeMakeLabel(v);
87874        assert( nFarg>=2 );
87875        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
87876        for(i=1; i<nFarg; i++){
87877          sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
87878          VdbeCoverage(v);
87879          sqlite3ExprCacheRemove(pParse, target, 1);
87880          sqlite3ExprCachePush(pParse);
87881          sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
87882          sqlite3ExprCachePop(pParse);
87883        }
87884        sqlite3VdbeResolveLabel(v, endCoalesce);
87885        break;
87886      }
87887
87888      /* The UNLIKELY() function is a no-op.  The result is the value
87889      ** of the first argument.
87890      */
87891      if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
87892        assert( nFarg>=1 );
87893        inReg = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
87894        break;
87895      }
87896
87897      for(i=0; i<nFarg; i++){
87898        if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
87899          testcase( i==31 );
87900          constMask |= MASKBIT32(i);
87901        }
87902        if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
87903          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
87904        }
87905      }
87906      if( pFarg ){
87907        if( constMask ){
87908          r1 = pParse->nMem+1;
87909          pParse->nMem += nFarg;
87910        }else{
87911          r1 = sqlite3GetTempRange(pParse, nFarg);
87912        }
87913
87914        /* For length() and typeof() functions with a column argument,
87915        ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
87916        ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
87917        ** loading.
87918        */
87919        if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
87920          u8 exprOp;
87921          assert( nFarg==1 );
87922          assert( pFarg->a[0].pExpr!=0 );
87923          exprOp = pFarg->a[0].pExpr->op;
87924          if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
87925            assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
87926            assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
87927            testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
87928            pFarg->a[0].pExpr->op2 =
87929                  pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
87930          }
87931        }
87932
87933        sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
87934        sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
87935                                SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
87936        sqlite3ExprCachePop(pParse);      /* Ticket 2ea2425d34be */
87937      }else{
87938        r1 = 0;
87939      }
87940#ifndef SQLITE_OMIT_VIRTUALTABLE
87941      /* Possibly overload the function if the first argument is
87942      ** a virtual table column.
87943      **
87944      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
87945      ** second argument, not the first, as the argument to test to
87946      ** see if it is a column in a virtual table.  This is done because
87947      ** the left operand of infix functions (the operand we want to
87948      ** control overloading) ends up as the second argument to the
87949      ** function.  The expression "A glob B" is equivalent to
87950      ** "glob(B,A).  We want to use the A in "A glob B" to test
87951      ** for function overloading.  But we use the B term in "glob(B,A)".
87952      */
87953      if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
87954        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
87955      }else if( nFarg>0 ){
87956        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
87957      }
87958#endif
87959      if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
87960        if( !pColl ) pColl = db->pDfltColl;
87961        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
87962      }
87963      sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
87964                        (char*)pDef, P4_FUNCDEF);
87965      sqlite3VdbeChangeP5(v, (u8)nFarg);
87966      if( nFarg && constMask==0 ){
87967        sqlite3ReleaseTempRange(pParse, r1, nFarg);
87968      }
87969      break;
87970    }
87971#ifndef SQLITE_OMIT_SUBQUERY
87972    case TK_EXISTS:
87973    case TK_SELECT: {
87974      testcase( op==TK_EXISTS );
87975      testcase( op==TK_SELECT );
87976      inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
87977      break;
87978    }
87979    case TK_IN: {
87980      int destIfFalse = sqlite3VdbeMakeLabel(v);
87981      int destIfNull = sqlite3VdbeMakeLabel(v);
87982      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
87983      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
87984      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
87985      sqlite3VdbeResolveLabel(v, destIfFalse);
87986      sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
87987      sqlite3VdbeResolveLabel(v, destIfNull);
87988      break;
87989    }
87990#endif /* SQLITE_OMIT_SUBQUERY */
87991
87992
87993    /*
87994    **    x BETWEEN y AND z
87995    **
87996    ** This is equivalent to
87997    **
87998    **    x>=y AND x<=z
87999    **
88000    ** X is stored in pExpr->pLeft.
88001    ** Y is stored in pExpr->pList->a[0].pExpr.
88002    ** Z is stored in pExpr->pList->a[1].pExpr.
88003    */
88004    case TK_BETWEEN: {
88005      Expr *pLeft = pExpr->pLeft;
88006      struct ExprList_item *pLItem = pExpr->x.pList->a;
88007      Expr *pRight = pLItem->pExpr;
88008
88009      r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
88010      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
88011      testcase( regFree1==0 );
88012      testcase( regFree2==0 );
88013      r3 = sqlite3GetTempReg(pParse);
88014      r4 = sqlite3GetTempReg(pParse);
88015      codeCompare(pParse, pLeft, pRight, OP_Ge,
88016                  r1, r2, r3, SQLITE_STOREP2);  VdbeCoverage(v);
88017      pLItem++;
88018      pRight = pLItem->pExpr;
88019      sqlite3ReleaseTempReg(pParse, regFree2);
88020      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
88021      testcase( regFree2==0 );
88022      codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
88023      VdbeCoverage(v);
88024      sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
88025      sqlite3ReleaseTempReg(pParse, r3);
88026      sqlite3ReleaseTempReg(pParse, r4);
88027      break;
88028    }
88029    case TK_COLLATE:
88030    case TK_UPLUS: {
88031      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
88032      break;
88033    }
88034
88035    case TK_TRIGGER: {
88036      /* If the opcode is TK_TRIGGER, then the expression is a reference
88037      ** to a column in the new.* or old.* pseudo-tables available to
88038      ** trigger programs. In this case Expr.iTable is set to 1 for the
88039      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
88040      ** is set to the column of the pseudo-table to read, or to -1 to
88041      ** read the rowid field.
88042      **
88043      ** The expression is implemented using an OP_Param opcode. The p1
88044      ** parameter is set to 0 for an old.rowid reference, or to (i+1)
88045      ** to reference another column of the old.* pseudo-table, where
88046      ** i is the index of the column. For a new.rowid reference, p1 is
88047      ** set to (n+1), where n is the number of columns in each pseudo-table.
88048      ** For a reference to any other column in the new.* pseudo-table, p1
88049      ** is set to (n+2+i), where n and i are as defined previously. For
88050      ** example, if the table on which triggers are being fired is
88051      ** declared as:
88052      **
88053      **   CREATE TABLE t1(a, b);
88054      **
88055      ** Then p1 is interpreted as follows:
88056      **
88057      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
88058      **   p1==1   ->    old.a         p1==4   ->    new.a
88059      **   p1==2   ->    old.b         p1==5   ->    new.b
88060      */
88061      Table *pTab = pExpr->pTab;
88062      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
88063
88064      assert( pExpr->iTable==0 || pExpr->iTable==1 );
88065      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
88066      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
88067      assert( p1>=0 && p1<(pTab->nCol*2+2) );
88068
88069      sqlite3VdbeAddOp2(v, OP_Param, p1, target);
88070      VdbeComment((v, "%s.%s -> $%d",
88071        (pExpr->iTable ? "new" : "old"),
88072        (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
88073        target
88074      ));
88075
88076#ifndef SQLITE_OMIT_FLOATING_POINT
88077      /* If the column has REAL affinity, it may currently be stored as an
88078      ** integer. Use OP_RealAffinity to make sure it is really real.
88079      **
88080      ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
88081      ** floating point when extracting it from the record.  */
88082      if( pExpr->iColumn>=0
88083       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
88084      ){
88085        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
88086      }
88087#endif
88088      break;
88089    }
88090
88091
88092    /*
88093    ** Form A:
88094    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
88095    **
88096    ** Form B:
88097    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
88098    **
88099    ** Form A is can be transformed into the equivalent form B as follows:
88100    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
88101    **        WHEN x=eN THEN rN ELSE y END
88102    **
88103    ** X (if it exists) is in pExpr->pLeft.
88104    ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
88105    ** odd.  The Y is also optional.  If the number of elements in x.pList
88106    ** is even, then Y is omitted and the "otherwise" result is NULL.
88107    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
88108    **
88109    ** The result of the expression is the Ri for the first matching Ei,
88110    ** or if there is no matching Ei, the ELSE term Y, or if there is
88111    ** no ELSE term, NULL.
88112    */
88113    default: assert( op==TK_CASE ); {
88114      int endLabel;                     /* GOTO label for end of CASE stmt */
88115      int nextCase;                     /* GOTO label for next WHEN clause */
88116      int nExpr;                        /* 2x number of WHEN terms */
88117      int i;                            /* Loop counter */
88118      ExprList *pEList;                 /* List of WHEN terms */
88119      struct ExprList_item *aListelem;  /* Array of WHEN terms */
88120      Expr opCompare;                   /* The X==Ei expression */
88121      Expr *pX;                         /* The X expression */
88122      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
88123      VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
88124
88125      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
88126      assert(pExpr->x.pList->nExpr > 0);
88127      pEList = pExpr->x.pList;
88128      aListelem = pEList->a;
88129      nExpr = pEList->nExpr;
88130      endLabel = sqlite3VdbeMakeLabel(v);
88131      if( (pX = pExpr->pLeft)!=0 ){
88132        tempX = *pX;
88133        testcase( pX->op==TK_COLUMN );
88134        exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
88135        testcase( regFree1==0 );
88136        opCompare.op = TK_EQ;
88137        opCompare.pLeft = &tempX;
88138        pTest = &opCompare;
88139        /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
88140        ** The value in regFree1 might get SCopy-ed into the file result.
88141        ** So make sure that the regFree1 register is not reused for other
88142        ** purposes and possibly overwritten.  */
88143        regFree1 = 0;
88144      }
88145      for(i=0; i<nExpr-1; i=i+2){
88146        sqlite3ExprCachePush(pParse);
88147        if( pX ){
88148          assert( pTest!=0 );
88149          opCompare.pRight = aListelem[i].pExpr;
88150        }else{
88151          pTest = aListelem[i].pExpr;
88152        }
88153        nextCase = sqlite3VdbeMakeLabel(v);
88154        testcase( pTest->op==TK_COLUMN );
88155        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
88156        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
88157        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
88158        sqlite3VdbeGoto(v, endLabel);
88159        sqlite3ExprCachePop(pParse);
88160        sqlite3VdbeResolveLabel(v, nextCase);
88161      }
88162      if( (nExpr&1)!=0 ){
88163        sqlite3ExprCachePush(pParse);
88164        sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
88165        sqlite3ExprCachePop(pParse);
88166      }else{
88167        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
88168      }
88169      assert( db->mallocFailed || pParse->nErr>0
88170           || pParse->iCacheLevel==iCacheLevel );
88171      sqlite3VdbeResolveLabel(v, endLabel);
88172      break;
88173    }
88174#ifndef SQLITE_OMIT_TRIGGER
88175    case TK_RAISE: {
88176      assert( pExpr->affinity==OE_Rollback
88177           || pExpr->affinity==OE_Abort
88178           || pExpr->affinity==OE_Fail
88179           || pExpr->affinity==OE_Ignore
88180      );
88181      if( !pParse->pTriggerTab ){
88182        sqlite3ErrorMsg(pParse,
88183                       "RAISE() may only be used within a trigger-program");
88184        return 0;
88185      }
88186      if( pExpr->affinity==OE_Abort ){
88187        sqlite3MayAbort(pParse);
88188      }
88189      assert( !ExprHasProperty(pExpr, EP_IntValue) );
88190      if( pExpr->affinity==OE_Ignore ){
88191        sqlite3VdbeAddOp4(
88192            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
88193        VdbeCoverage(v);
88194      }else{
88195        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
88196                              pExpr->affinity, pExpr->u.zToken, 0, 0);
88197      }
88198
88199      break;
88200    }
88201#endif
88202  }
88203  sqlite3ReleaseTempReg(pParse, regFree1);
88204  sqlite3ReleaseTempReg(pParse, regFree2);
88205  return inReg;
88206}
88207
88208/*
88209** Factor out the code of the given expression to initialization time.
88210*/
88211SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
88212  Parse *pParse,    /* Parsing context */
88213  Expr *pExpr,      /* The expression to code when the VDBE initializes */
88214  int regDest,      /* Store the value in this register */
88215  u8 reusable       /* True if this expression is reusable */
88216){
88217  ExprList *p;
88218  assert( ConstFactorOk(pParse) );
88219  p = pParse->pConstExpr;
88220  pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
88221  p = sqlite3ExprListAppend(pParse, p, pExpr);
88222  if( p ){
88223     struct ExprList_item *pItem = &p->a[p->nExpr-1];
88224     pItem->u.iConstExprReg = regDest;
88225     pItem->reusable = reusable;
88226  }
88227  pParse->pConstExpr = p;
88228}
88229
88230/*
88231** Generate code to evaluate an expression and store the results
88232** into a register.  Return the register number where the results
88233** are stored.
88234**
88235** If the register is a temporary register that can be deallocated,
88236** then write its number into *pReg.  If the result register is not
88237** a temporary, then set *pReg to zero.
88238**
88239** If pExpr is a constant, then this routine might generate this
88240** code to fill the register in the initialization section of the
88241** VDBE program, in order to factor it out of the evaluation loop.
88242*/
88243SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
88244  int r2;
88245  pExpr = sqlite3ExprSkipCollate(pExpr);
88246  if( ConstFactorOk(pParse)
88247   && pExpr->op!=TK_REGISTER
88248   && sqlite3ExprIsConstantNotJoin(pExpr)
88249  ){
88250    ExprList *p = pParse->pConstExpr;
88251    int i;
88252    *pReg  = 0;
88253    if( p ){
88254      struct ExprList_item *pItem;
88255      for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
88256        if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
88257          return pItem->u.iConstExprReg;
88258        }
88259      }
88260    }
88261    r2 = ++pParse->nMem;
88262    sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
88263  }else{
88264    int r1 = sqlite3GetTempReg(pParse);
88265    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
88266    if( r2==r1 ){
88267      *pReg = r1;
88268    }else{
88269      sqlite3ReleaseTempReg(pParse, r1);
88270      *pReg = 0;
88271    }
88272  }
88273  return r2;
88274}
88275
88276/*
88277** Generate code that will evaluate expression pExpr and store the
88278** results in register target.  The results are guaranteed to appear
88279** in register target.
88280*/
88281SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
88282  int inReg;
88283
88284  assert( target>0 && target<=pParse->nMem );
88285  if( pExpr && pExpr->op==TK_REGISTER ){
88286    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
88287  }else{
88288    inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
88289    assert( pParse->pVdbe || pParse->db->mallocFailed );
88290    if( inReg!=target && pParse->pVdbe ){
88291      sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
88292    }
88293  }
88294}
88295
88296/*
88297** Generate code that will evaluate expression pExpr and store the
88298** results in register target.  The results are guaranteed to appear
88299** in register target.  If the expression is constant, then this routine
88300** might choose to code the expression at initialization time.
88301*/
88302SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
88303  if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
88304    sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
88305  }else{
88306    sqlite3ExprCode(pParse, pExpr, target);
88307  }
88308}
88309
88310/*
88311** Generate code that evaluates the given expression and puts the result
88312** in register target.
88313**
88314** Also make a copy of the expression results into another "cache" register
88315** and modify the expression so that the next time it is evaluated,
88316** the result is a copy of the cache register.
88317**
88318** This routine is used for expressions that are used multiple
88319** times.  They are evaluated once and the results of the expression
88320** are reused.
88321*/
88322SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
88323  Vdbe *v = pParse->pVdbe;
88324  int iMem;
88325
88326  assert( target>0 );
88327  assert( pExpr->op!=TK_REGISTER );
88328  sqlite3ExprCode(pParse, pExpr, target);
88329  iMem = ++pParse->nMem;
88330  sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
88331  exprToRegister(pExpr, iMem);
88332}
88333
88334/*
88335** Generate code that pushes the value of every element of the given
88336** expression list into a sequence of registers beginning at target.
88337**
88338** Return the number of elements evaluated.
88339**
88340** The SQLITE_ECEL_DUP flag prevents the arguments from being
88341** filled using OP_SCopy.  OP_Copy must be used instead.
88342**
88343** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
88344** factored out into initialization code.
88345*/
88346SQLITE_PRIVATE int sqlite3ExprCodeExprList(
88347  Parse *pParse,     /* Parsing context */
88348  ExprList *pList,   /* The expression list to be coded */
88349  int target,        /* Where to write results */
88350  int srcReg,        /* Source registers if SQLITE_ECEL_REF */
88351  u8 flags           /* SQLITE_ECEL_* flags */
88352){
88353  struct ExprList_item *pItem;
88354  int i, j, n;
88355  u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
88356  Vdbe *v = pParse->pVdbe;
88357  assert( pList!=0 );
88358  assert( target>0 );
88359  assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
88360  n = pList->nExpr;
88361  if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
88362  for(pItem=pList->a, i=0; i<n; i++, pItem++){
88363    Expr *pExpr = pItem->pExpr;
88364    if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){
88365      sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
88366    }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
88367      sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
88368    }else{
88369      int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
88370      if( inReg!=target+i ){
88371        VdbeOp *pOp;
88372        if( copyOp==OP_Copy
88373         && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
88374         && pOp->p1+pOp->p3+1==inReg
88375         && pOp->p2+pOp->p3+1==target+i
88376        ){
88377          pOp->p3++;
88378        }else{
88379          sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
88380        }
88381      }
88382    }
88383  }
88384  return n;
88385}
88386
88387/*
88388** Generate code for a BETWEEN operator.
88389**
88390**    x BETWEEN y AND z
88391**
88392** The above is equivalent to
88393**
88394**    x>=y AND x<=z
88395**
88396** Code it as such, taking care to do the common subexpression
88397** elimination of x.
88398*/
88399static void exprCodeBetween(
88400  Parse *pParse,    /* Parsing and code generating context */
88401  Expr *pExpr,      /* The BETWEEN expression */
88402  int dest,         /* Jump here if the jump is taken */
88403  int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
88404  int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
88405){
88406  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
88407  Expr compLeft;    /* The  x>=y  term */
88408  Expr compRight;   /* The  x<=z  term */
88409  Expr exprX;       /* The  x  subexpression */
88410  int regFree1 = 0; /* Temporary use register */
88411
88412  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
88413  exprX = *pExpr->pLeft;
88414  exprAnd.op = TK_AND;
88415  exprAnd.pLeft = &compLeft;
88416  exprAnd.pRight = &compRight;
88417  compLeft.op = TK_GE;
88418  compLeft.pLeft = &exprX;
88419  compLeft.pRight = pExpr->x.pList->a[0].pExpr;
88420  compRight.op = TK_LE;
88421  compRight.pLeft = &exprX;
88422  compRight.pRight = pExpr->x.pList->a[1].pExpr;
88423  exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
88424  if( jumpIfTrue ){
88425    sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
88426  }else{
88427    sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
88428  }
88429  sqlite3ReleaseTempReg(pParse, regFree1);
88430
88431  /* Ensure adequate test coverage */
88432  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
88433  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
88434  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
88435  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
88436  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
88437  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
88438  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
88439  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
88440}
88441
88442/*
88443** Generate code for a boolean expression such that a jump is made
88444** to the label "dest" if the expression is true but execution
88445** continues straight thru if the expression is false.
88446**
88447** If the expression evaluates to NULL (neither true nor false), then
88448** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
88449**
88450** This code depends on the fact that certain token values (ex: TK_EQ)
88451** are the same as opcode values (ex: OP_Eq) that implement the corresponding
88452** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
88453** the make process cause these values to align.  Assert()s in the code
88454** below verify that the numbers are aligned correctly.
88455*/
88456SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
88457  Vdbe *v = pParse->pVdbe;
88458  int op = 0;
88459  int regFree1 = 0;
88460  int regFree2 = 0;
88461  int r1, r2;
88462
88463  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
88464  if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
88465  if( NEVER(pExpr==0) ) return;  /* No way this can happen */
88466  op = pExpr->op;
88467  switch( op ){
88468    case TK_AND: {
88469      int d2 = sqlite3VdbeMakeLabel(v);
88470      testcase( jumpIfNull==0 );
88471      sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
88472      sqlite3ExprCachePush(pParse);
88473      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
88474      sqlite3VdbeResolveLabel(v, d2);
88475      sqlite3ExprCachePop(pParse);
88476      break;
88477    }
88478    case TK_OR: {
88479      testcase( jumpIfNull==0 );
88480      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
88481      sqlite3ExprCachePush(pParse);
88482      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
88483      sqlite3ExprCachePop(pParse);
88484      break;
88485    }
88486    case TK_NOT: {
88487      testcase( jumpIfNull==0 );
88488      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
88489      break;
88490    }
88491    case TK_LT:
88492    case TK_LE:
88493    case TK_GT:
88494    case TK_GE:
88495    case TK_NE:
88496    case TK_EQ: {
88497      testcase( jumpIfNull==0 );
88498      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
88499      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
88500      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
88501                  r1, r2, dest, jumpIfNull);
88502      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
88503      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
88504      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
88505      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
88506      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
88507      assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
88508      testcase( regFree1==0 );
88509      testcase( regFree2==0 );
88510      break;
88511    }
88512    case TK_IS:
88513    case TK_ISNOT: {
88514      testcase( op==TK_IS );
88515      testcase( op==TK_ISNOT );
88516      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
88517      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
88518      op = (op==TK_IS) ? TK_EQ : TK_NE;
88519      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
88520                  r1, r2, dest, SQLITE_NULLEQ);
88521      VdbeCoverageIf(v, op==TK_EQ);
88522      VdbeCoverageIf(v, op==TK_NE);
88523      testcase( regFree1==0 );
88524      testcase( regFree2==0 );
88525      break;
88526    }
88527    case TK_ISNULL:
88528    case TK_NOTNULL: {
88529      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
88530      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
88531      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
88532      sqlite3VdbeAddOp2(v, op, r1, dest);
88533      VdbeCoverageIf(v, op==TK_ISNULL);
88534      VdbeCoverageIf(v, op==TK_NOTNULL);
88535      testcase( regFree1==0 );
88536      break;
88537    }
88538    case TK_BETWEEN: {
88539      testcase( jumpIfNull==0 );
88540      exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
88541      break;
88542    }
88543#ifndef SQLITE_OMIT_SUBQUERY
88544    case TK_IN: {
88545      int destIfFalse = sqlite3VdbeMakeLabel(v);
88546      int destIfNull = jumpIfNull ? dest : destIfFalse;
88547      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
88548      sqlite3VdbeGoto(v, dest);
88549      sqlite3VdbeResolveLabel(v, destIfFalse);
88550      break;
88551    }
88552#endif
88553    default: {
88554      if( exprAlwaysTrue(pExpr) ){
88555        sqlite3VdbeGoto(v, dest);
88556      }else if( exprAlwaysFalse(pExpr) ){
88557        /* No-op */
88558      }else{
88559        r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
88560        sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
88561        VdbeCoverage(v);
88562        testcase( regFree1==0 );
88563        testcase( jumpIfNull==0 );
88564      }
88565      break;
88566    }
88567  }
88568  sqlite3ReleaseTempReg(pParse, regFree1);
88569  sqlite3ReleaseTempReg(pParse, regFree2);
88570}
88571
88572/*
88573** Generate code for a boolean expression such that a jump is made
88574** to the label "dest" if the expression is false but execution
88575** continues straight thru if the expression is true.
88576**
88577** If the expression evaluates to NULL (neither true nor false) then
88578** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
88579** is 0.
88580*/
88581SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
88582  Vdbe *v = pParse->pVdbe;
88583  int op = 0;
88584  int regFree1 = 0;
88585  int regFree2 = 0;
88586  int r1, r2;
88587
88588  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
88589  if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
88590  if( pExpr==0 )    return;
88591
88592  /* The value of pExpr->op and op are related as follows:
88593  **
88594  **       pExpr->op            op
88595  **       ---------          ----------
88596  **       TK_ISNULL          OP_NotNull
88597  **       TK_NOTNULL         OP_IsNull
88598  **       TK_NE              OP_Eq
88599  **       TK_EQ              OP_Ne
88600  **       TK_GT              OP_Le
88601  **       TK_LE              OP_Gt
88602  **       TK_GE              OP_Lt
88603  **       TK_LT              OP_Ge
88604  **
88605  ** For other values of pExpr->op, op is undefined and unused.
88606  ** The value of TK_ and OP_ constants are arranged such that we
88607  ** can compute the mapping above using the following expression.
88608  ** Assert()s verify that the computation is correct.
88609  */
88610  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
88611
88612  /* Verify correct alignment of TK_ and OP_ constants
88613  */
88614  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
88615  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
88616  assert( pExpr->op!=TK_NE || op==OP_Eq );
88617  assert( pExpr->op!=TK_EQ || op==OP_Ne );
88618  assert( pExpr->op!=TK_LT || op==OP_Ge );
88619  assert( pExpr->op!=TK_LE || op==OP_Gt );
88620  assert( pExpr->op!=TK_GT || op==OP_Le );
88621  assert( pExpr->op!=TK_GE || op==OP_Lt );
88622
88623  switch( pExpr->op ){
88624    case TK_AND: {
88625      testcase( jumpIfNull==0 );
88626      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
88627      sqlite3ExprCachePush(pParse);
88628      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
88629      sqlite3ExprCachePop(pParse);
88630      break;
88631    }
88632    case TK_OR: {
88633      int d2 = sqlite3VdbeMakeLabel(v);
88634      testcase( jumpIfNull==0 );
88635      sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
88636      sqlite3ExprCachePush(pParse);
88637      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
88638      sqlite3VdbeResolveLabel(v, d2);
88639      sqlite3ExprCachePop(pParse);
88640      break;
88641    }
88642    case TK_NOT: {
88643      testcase( jumpIfNull==0 );
88644      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
88645      break;
88646    }
88647    case TK_LT:
88648    case TK_LE:
88649    case TK_GT:
88650    case TK_GE:
88651    case TK_NE:
88652    case TK_EQ: {
88653      testcase( jumpIfNull==0 );
88654      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
88655      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
88656      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
88657                  r1, r2, dest, jumpIfNull);
88658      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
88659      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
88660      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
88661      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
88662      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
88663      assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
88664      testcase( regFree1==0 );
88665      testcase( regFree2==0 );
88666      break;
88667    }
88668    case TK_IS:
88669    case TK_ISNOT: {
88670      testcase( pExpr->op==TK_IS );
88671      testcase( pExpr->op==TK_ISNOT );
88672      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
88673      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
88674      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
88675      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
88676                  r1, r2, dest, SQLITE_NULLEQ);
88677      VdbeCoverageIf(v, op==TK_EQ);
88678      VdbeCoverageIf(v, op==TK_NE);
88679      testcase( regFree1==0 );
88680      testcase( regFree2==0 );
88681      break;
88682    }
88683    case TK_ISNULL:
88684    case TK_NOTNULL: {
88685      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
88686      sqlite3VdbeAddOp2(v, op, r1, dest);
88687      testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
88688      testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
88689      testcase( regFree1==0 );
88690      break;
88691    }
88692    case TK_BETWEEN: {
88693      testcase( jumpIfNull==0 );
88694      exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
88695      break;
88696    }
88697#ifndef SQLITE_OMIT_SUBQUERY
88698    case TK_IN: {
88699      if( jumpIfNull ){
88700        sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
88701      }else{
88702        int destIfNull = sqlite3VdbeMakeLabel(v);
88703        sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
88704        sqlite3VdbeResolveLabel(v, destIfNull);
88705      }
88706      break;
88707    }
88708#endif
88709    default: {
88710      if( exprAlwaysFalse(pExpr) ){
88711        sqlite3VdbeGoto(v, dest);
88712      }else if( exprAlwaysTrue(pExpr) ){
88713        /* no-op */
88714      }else{
88715        r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
88716        sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
88717        VdbeCoverage(v);
88718        testcase( regFree1==0 );
88719        testcase( jumpIfNull==0 );
88720      }
88721      break;
88722    }
88723  }
88724  sqlite3ReleaseTempReg(pParse, regFree1);
88725  sqlite3ReleaseTempReg(pParse, regFree2);
88726}
88727
88728/*
88729** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
88730** code generation, and that copy is deleted after code generation. This
88731** ensures that the original pExpr is unchanged.
88732*/
88733SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
88734  sqlite3 *db = pParse->db;
88735  Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
88736  if( db->mallocFailed==0 ){
88737    sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
88738  }
88739  sqlite3ExprDelete(db, pCopy);
88740}
88741
88742
88743/*
88744** Do a deep comparison of two expression trees.  Return 0 if the two
88745** expressions are completely identical.  Return 1 if they differ only
88746** by a COLLATE operator at the top level.  Return 2 if there are differences
88747** other than the top-level COLLATE operator.
88748**
88749** If any subelement of pB has Expr.iTable==(-1) then it is allowed
88750** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
88751**
88752** The pA side might be using TK_REGISTER.  If that is the case and pB is
88753** not using TK_REGISTER but is otherwise equivalent, then still return 0.
88754**
88755** Sometimes this routine will return 2 even if the two expressions
88756** really are equivalent.  If we cannot prove that the expressions are
88757** identical, we return 2 just to be safe.  So if this routine
88758** returns 2, then you do not really know for certain if the two
88759** expressions are the same.  But if you get a 0 or 1 return, then you
88760** can be sure the expressions are the same.  In the places where
88761** this routine is used, it does not hurt to get an extra 2 - that
88762** just might result in some slightly slower code.  But returning
88763** an incorrect 0 or 1 could lead to a malfunction.
88764*/
88765SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
88766  u32 combinedFlags;
88767  if( pA==0 || pB==0 ){
88768    return pB==pA ? 0 : 2;
88769  }
88770  combinedFlags = pA->flags | pB->flags;
88771  if( combinedFlags & EP_IntValue ){
88772    if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
88773      return 0;
88774    }
88775    return 2;
88776  }
88777  if( pA->op!=pB->op ){
88778    if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
88779      return 1;
88780    }
88781    if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
88782      return 1;
88783    }
88784    return 2;
88785  }
88786  if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken ){
88787    if( pA->op==TK_FUNCTION ){
88788      if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
88789    }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
88790      return pA->op==TK_COLLATE ? 1 : 2;
88791    }
88792  }
88793  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
88794  if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
88795    if( combinedFlags & EP_xIsSelect ) return 2;
88796    if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
88797    if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
88798    if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
88799    if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
88800      if( pA->iColumn!=pB->iColumn ) return 2;
88801      if( pA->iTable!=pB->iTable
88802       && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
88803    }
88804  }
88805  return 0;
88806}
88807
88808/*
88809** Compare two ExprList objects.  Return 0 if they are identical and
88810** non-zero if they differ in any way.
88811**
88812** If any subelement of pB has Expr.iTable==(-1) then it is allowed
88813** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
88814**
88815** This routine might return non-zero for equivalent ExprLists.  The
88816** only consequence will be disabled optimizations.  But this routine
88817** must never return 0 if the two ExprList objects are different, or
88818** a malfunction will result.
88819**
88820** Two NULL pointers are considered to be the same.  But a NULL pointer
88821** always differs from a non-NULL pointer.
88822*/
88823SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
88824  int i;
88825  if( pA==0 && pB==0 ) return 0;
88826  if( pA==0 || pB==0 ) return 1;
88827  if( pA->nExpr!=pB->nExpr ) return 1;
88828  for(i=0; i<pA->nExpr; i++){
88829    Expr *pExprA = pA->a[i].pExpr;
88830    Expr *pExprB = pB->a[i].pExpr;
88831    if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
88832    if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
88833  }
88834  return 0;
88835}
88836
88837/*
88838** Return true if we can prove the pE2 will always be true if pE1 is
88839** true.  Return false if we cannot complete the proof or if pE2 might
88840** be false.  Examples:
88841**
88842**     pE1: x==5       pE2: x==5             Result: true
88843**     pE1: x>0        pE2: x==5             Result: false
88844**     pE1: x=21       pE2: x=21 OR y=43     Result: true
88845**     pE1: x!=123     pE2: x IS NOT NULL    Result: true
88846**     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
88847**     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
88848**     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
88849**
88850** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
88851** Expr.iTable<0 then assume a table number given by iTab.
88852**
88853** When in doubt, return false.  Returning true might give a performance
88854** improvement.  Returning false might cause a performance reduction, but
88855** it will always give the correct answer and is hence always safe.
88856*/
88857SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
88858  if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
88859    return 1;
88860  }
88861  if( pE2->op==TK_OR
88862   && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
88863             || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
88864  ){
88865    return 1;
88866  }
88867  if( pE2->op==TK_NOTNULL
88868   && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
88869   && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
88870  ){
88871    return 1;
88872  }
88873  return 0;
88874}
88875
88876/*
88877** An instance of the following structure is used by the tree walker
88878** to count references to table columns in the arguments of an
88879** aggregate function, in order to implement the
88880** sqlite3FunctionThisSrc() routine.
88881*/
88882struct SrcCount {
88883  SrcList *pSrc;   /* One particular FROM clause in a nested query */
88884  int nThis;       /* Number of references to columns in pSrcList */
88885  int nOther;      /* Number of references to columns in other FROM clauses */
88886};
88887
88888/*
88889** Count the number of references to columns.
88890*/
88891static int exprSrcCount(Walker *pWalker, Expr *pExpr){
88892  /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
88893  ** is always called before sqlite3ExprAnalyzeAggregates() and so the
88894  ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
88895  ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
88896  ** NEVER() will need to be removed. */
88897  if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
88898    int i;
88899    struct SrcCount *p = pWalker->u.pSrcCount;
88900    SrcList *pSrc = p->pSrc;
88901    int nSrc = pSrc ? pSrc->nSrc : 0;
88902    for(i=0; i<nSrc; i++){
88903      if( pExpr->iTable==pSrc->a[i].iCursor ) break;
88904    }
88905    if( i<nSrc ){
88906      p->nThis++;
88907    }else{
88908      p->nOther++;
88909    }
88910  }
88911  return WRC_Continue;
88912}
88913
88914/*
88915** Determine if any of the arguments to the pExpr Function reference
88916** pSrcList.  Return true if they do.  Also return true if the function
88917** has no arguments or has only constant arguments.  Return false if pExpr
88918** references columns but not columns of tables found in pSrcList.
88919*/
88920SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
88921  Walker w;
88922  struct SrcCount cnt;
88923  assert( pExpr->op==TK_AGG_FUNCTION );
88924  memset(&w, 0, sizeof(w));
88925  w.xExprCallback = exprSrcCount;
88926  w.u.pSrcCount = &cnt;
88927  cnt.pSrc = pSrcList;
88928  cnt.nThis = 0;
88929  cnt.nOther = 0;
88930  sqlite3WalkExprList(&w, pExpr->x.pList);
88931  return cnt.nThis>0 || cnt.nOther==0;
88932}
88933
88934/*
88935** Add a new element to the pAggInfo->aCol[] array.  Return the index of
88936** the new element.  Return a negative number if malloc fails.
88937*/
88938static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
88939  int i;
88940  pInfo->aCol = sqlite3ArrayAllocate(
88941       db,
88942       pInfo->aCol,
88943       sizeof(pInfo->aCol[0]),
88944       &pInfo->nColumn,
88945       &i
88946  );
88947  return i;
88948}
88949
88950/*
88951** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
88952** the new element.  Return a negative number if malloc fails.
88953*/
88954static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
88955  int i;
88956  pInfo->aFunc = sqlite3ArrayAllocate(
88957       db,
88958       pInfo->aFunc,
88959       sizeof(pInfo->aFunc[0]),
88960       &pInfo->nFunc,
88961       &i
88962  );
88963  return i;
88964}
88965
88966/*
88967** This is the xExprCallback for a tree walker.  It is used to
88968** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
88969** for additional information.
88970*/
88971static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
88972  int i;
88973  NameContext *pNC = pWalker->u.pNC;
88974  Parse *pParse = pNC->pParse;
88975  SrcList *pSrcList = pNC->pSrcList;
88976  AggInfo *pAggInfo = pNC->pAggInfo;
88977
88978  switch( pExpr->op ){
88979    case TK_AGG_COLUMN:
88980    case TK_COLUMN: {
88981      testcase( pExpr->op==TK_AGG_COLUMN );
88982      testcase( pExpr->op==TK_COLUMN );
88983      /* Check to see if the column is in one of the tables in the FROM
88984      ** clause of the aggregate query */
88985      if( ALWAYS(pSrcList!=0) ){
88986        struct SrcList_item *pItem = pSrcList->a;
88987        for(i=0; i<pSrcList->nSrc; i++, pItem++){
88988          struct AggInfo_col *pCol;
88989          assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
88990          if( pExpr->iTable==pItem->iCursor ){
88991            /* If we reach this point, it means that pExpr refers to a table
88992            ** that is in the FROM clause of the aggregate query.
88993            **
88994            ** Make an entry for the column in pAggInfo->aCol[] if there
88995            ** is not an entry there already.
88996            */
88997            int k;
88998            pCol = pAggInfo->aCol;
88999            for(k=0; k<pAggInfo->nColumn; k++, pCol++){
89000              if( pCol->iTable==pExpr->iTable &&
89001                  pCol->iColumn==pExpr->iColumn ){
89002                break;
89003              }
89004            }
89005            if( (k>=pAggInfo->nColumn)
89006             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
89007            ){
89008              pCol = &pAggInfo->aCol[k];
89009              pCol->pTab = pExpr->pTab;
89010              pCol->iTable = pExpr->iTable;
89011              pCol->iColumn = pExpr->iColumn;
89012              pCol->iMem = ++pParse->nMem;
89013              pCol->iSorterColumn = -1;
89014              pCol->pExpr = pExpr;
89015              if( pAggInfo->pGroupBy ){
89016                int j, n;
89017                ExprList *pGB = pAggInfo->pGroupBy;
89018                struct ExprList_item *pTerm = pGB->a;
89019                n = pGB->nExpr;
89020                for(j=0; j<n; j++, pTerm++){
89021                  Expr *pE = pTerm->pExpr;
89022                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
89023                      pE->iColumn==pExpr->iColumn ){
89024                    pCol->iSorterColumn = j;
89025                    break;
89026                  }
89027                }
89028              }
89029              if( pCol->iSorterColumn<0 ){
89030                pCol->iSorterColumn = pAggInfo->nSortingColumn++;
89031              }
89032            }
89033            /* There is now an entry for pExpr in pAggInfo->aCol[] (either
89034            ** because it was there before or because we just created it).
89035            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
89036            ** pAggInfo->aCol[] entry.
89037            */
89038            ExprSetVVAProperty(pExpr, EP_NoReduce);
89039            pExpr->pAggInfo = pAggInfo;
89040            pExpr->op = TK_AGG_COLUMN;
89041            pExpr->iAgg = (i16)k;
89042            break;
89043          } /* endif pExpr->iTable==pItem->iCursor */
89044        } /* end loop over pSrcList */
89045      }
89046      return WRC_Prune;
89047    }
89048    case TK_AGG_FUNCTION: {
89049      if( (pNC->ncFlags & NC_InAggFunc)==0
89050       && pWalker->walkerDepth==pExpr->op2
89051      ){
89052        /* Check to see if pExpr is a duplicate of another aggregate
89053        ** function that is already in the pAggInfo structure
89054        */
89055        struct AggInfo_func *pItem = pAggInfo->aFunc;
89056        for(i=0; i<pAggInfo->nFunc; i++, pItem++){
89057          if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
89058            break;
89059          }
89060        }
89061        if( i>=pAggInfo->nFunc ){
89062          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
89063          */
89064          u8 enc = ENC(pParse->db);
89065          i = addAggInfoFunc(pParse->db, pAggInfo);
89066          if( i>=0 ){
89067            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
89068            pItem = &pAggInfo->aFunc[i];
89069            pItem->pExpr = pExpr;
89070            pItem->iMem = ++pParse->nMem;
89071            assert( !ExprHasProperty(pExpr, EP_IntValue) );
89072            pItem->pFunc = sqlite3FindFunction(pParse->db,
89073                   pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
89074                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
89075            if( pExpr->flags & EP_Distinct ){
89076              pItem->iDistinct = pParse->nTab++;
89077            }else{
89078              pItem->iDistinct = -1;
89079            }
89080          }
89081        }
89082        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
89083        */
89084        assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
89085        ExprSetVVAProperty(pExpr, EP_NoReduce);
89086        pExpr->iAgg = (i16)i;
89087        pExpr->pAggInfo = pAggInfo;
89088        return WRC_Prune;
89089      }else{
89090        return WRC_Continue;
89091      }
89092    }
89093  }
89094  return WRC_Continue;
89095}
89096static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
89097  UNUSED_PARAMETER(pWalker);
89098  UNUSED_PARAMETER(pSelect);
89099  return WRC_Continue;
89100}
89101
89102/*
89103** Analyze the pExpr expression looking for aggregate functions and
89104** for variables that need to be added to AggInfo object that pNC->pAggInfo
89105** points to.  Additional entries are made on the AggInfo object as
89106** necessary.
89107**
89108** This routine should only be called after the expression has been
89109** analyzed by sqlite3ResolveExprNames().
89110*/
89111SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
89112  Walker w;
89113  memset(&w, 0, sizeof(w));
89114  w.xExprCallback = analyzeAggregate;
89115  w.xSelectCallback = analyzeAggregatesInSelect;
89116  w.u.pNC = pNC;
89117  assert( pNC->pSrcList!=0 );
89118  sqlite3WalkExpr(&w, pExpr);
89119}
89120
89121/*
89122** Call sqlite3ExprAnalyzeAggregates() for every expression in an
89123** expression list.  Return the number of errors.
89124**
89125** If an error is found, the analysis is cut short.
89126*/
89127SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
89128  struct ExprList_item *pItem;
89129  int i;
89130  if( pList ){
89131    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
89132      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
89133    }
89134  }
89135}
89136
89137/*
89138** Allocate a single new register for use to hold some intermediate result.
89139*/
89140SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
89141  if( pParse->nTempReg==0 ){
89142    return ++pParse->nMem;
89143  }
89144  return pParse->aTempReg[--pParse->nTempReg];
89145}
89146
89147/*
89148** Deallocate a register, making available for reuse for some other
89149** purpose.
89150**
89151** If a register is currently being used by the column cache, then
89152** the deallocation is deferred until the column cache line that uses
89153** the register becomes stale.
89154*/
89155SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
89156  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
89157    int i;
89158    struct yColCache *p;
89159    for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
89160      if( p->iReg==iReg ){
89161        p->tempReg = 1;
89162        return;
89163      }
89164    }
89165    pParse->aTempReg[pParse->nTempReg++] = iReg;
89166  }
89167}
89168
89169/*
89170** Allocate or deallocate a block of nReg consecutive registers
89171*/
89172SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
89173  int i, n;
89174  i = pParse->iRangeReg;
89175  n = pParse->nRangeReg;
89176  if( nReg<=n ){
89177    assert( !usedAsColumnCache(pParse, i, i+n-1) );
89178    pParse->iRangeReg += nReg;
89179    pParse->nRangeReg -= nReg;
89180  }else{
89181    i = pParse->nMem+1;
89182    pParse->nMem += nReg;
89183  }
89184  return i;
89185}
89186SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
89187  sqlite3ExprCacheRemove(pParse, iReg, nReg);
89188  if( nReg>pParse->nRangeReg ){
89189    pParse->nRangeReg = nReg;
89190    pParse->iRangeReg = iReg;
89191  }
89192}
89193
89194/*
89195** Mark all temporary registers as being unavailable for reuse.
89196*/
89197SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
89198  pParse->nTempReg = 0;
89199  pParse->nRangeReg = 0;
89200}
89201
89202/************** End of expr.c ************************************************/
89203/************** Begin file alter.c *******************************************/
89204/*
89205** 2005 February 15
89206**
89207** The author disclaims copyright to this source code.  In place of
89208** a legal notice, here is a blessing:
89209**
89210**    May you do good and not evil.
89211**    May you find forgiveness for yourself and forgive others.
89212**    May you share freely, never taking more than you give.
89213**
89214*************************************************************************
89215** This file contains C code routines that used to generate VDBE code
89216** that implements the ALTER TABLE command.
89217*/
89218/* #include "sqliteInt.h" */
89219
89220/*
89221** The code in this file only exists if we are not omitting the
89222** ALTER TABLE logic from the build.
89223*/
89224#ifndef SQLITE_OMIT_ALTERTABLE
89225
89226
89227/*
89228** This function is used by SQL generated to implement the
89229** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
89230** CREATE INDEX command. The second is a table name. The table name in
89231** the CREATE TABLE or CREATE INDEX statement is replaced with the third
89232** argument and the result returned. Examples:
89233**
89234** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
89235**     -> 'CREATE TABLE def(a, b, c)'
89236**
89237** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
89238**     -> 'CREATE INDEX i ON def(a, b, c)'
89239*/
89240static void renameTableFunc(
89241  sqlite3_context *context,
89242  int NotUsed,
89243  sqlite3_value **argv
89244){
89245  unsigned char const *zSql = sqlite3_value_text(argv[0]);
89246  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
89247
89248  int token;
89249  Token tname;
89250  unsigned char const *zCsr = zSql;
89251  int len = 0;
89252  char *zRet;
89253
89254  sqlite3 *db = sqlite3_context_db_handle(context);
89255
89256  UNUSED_PARAMETER(NotUsed);
89257
89258  /* The principle used to locate the table name in the CREATE TABLE
89259  ** statement is that the table name is the first non-space token that
89260  ** is immediately followed by a TK_LP or TK_USING token.
89261  */
89262  if( zSql ){
89263    do {
89264      if( !*zCsr ){
89265        /* Ran out of input before finding an opening bracket. Return NULL. */
89266        return;
89267      }
89268
89269      /* Store the token that zCsr points to in tname. */
89270      tname.z = (char*)zCsr;
89271      tname.n = len;
89272
89273      /* Advance zCsr to the next token. Store that token type in 'token',
89274      ** and its length in 'len' (to be used next iteration of this loop).
89275      */
89276      do {
89277        zCsr += len;
89278        len = sqlite3GetToken(zCsr, &token);
89279      } while( token==TK_SPACE );
89280      assert( len>0 );
89281    } while( token!=TK_LP && token!=TK_USING );
89282
89283    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
89284       zSql, zTableName, tname.z+tname.n);
89285    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
89286  }
89287}
89288
89289/*
89290** This C function implements an SQL user function that is used by SQL code
89291** generated by the ALTER TABLE ... RENAME command to modify the definition
89292** of any foreign key constraints that use the table being renamed as the
89293** parent table. It is passed three arguments:
89294**
89295**   1) The complete text of the CREATE TABLE statement being modified,
89296**   2) The old name of the table being renamed, and
89297**   3) The new name of the table being renamed.
89298**
89299** It returns the new CREATE TABLE statement. For example:
89300**
89301**   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
89302**       -> 'CREATE TABLE t1(a REFERENCES t3)'
89303*/
89304#ifndef SQLITE_OMIT_FOREIGN_KEY
89305static void renameParentFunc(
89306  sqlite3_context *context,
89307  int NotUsed,
89308  sqlite3_value **argv
89309){
89310  sqlite3 *db = sqlite3_context_db_handle(context);
89311  char *zOutput = 0;
89312  char *zResult;
89313  unsigned char const *zInput = sqlite3_value_text(argv[0]);
89314  unsigned char const *zOld = sqlite3_value_text(argv[1]);
89315  unsigned char const *zNew = sqlite3_value_text(argv[2]);
89316
89317  unsigned const char *z;         /* Pointer to token */
89318  int n;                          /* Length of token z */
89319  int token;                      /* Type of token */
89320
89321  UNUSED_PARAMETER(NotUsed);
89322  if( zInput==0 || zOld==0 ) return;
89323  for(z=zInput; *z; z=z+n){
89324    n = sqlite3GetToken(z, &token);
89325    if( token==TK_REFERENCES ){
89326      char *zParent;
89327      do {
89328        z += n;
89329        n = sqlite3GetToken(z, &token);
89330      }while( token==TK_SPACE );
89331
89332      if( token==TK_ILLEGAL ) break;
89333      zParent = sqlite3DbStrNDup(db, (const char *)z, n);
89334      if( zParent==0 ) break;
89335      sqlite3Dequote(zParent);
89336      if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
89337        char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
89338            (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
89339        );
89340        sqlite3DbFree(db, zOutput);
89341        zOutput = zOut;
89342        zInput = &z[n];
89343      }
89344      sqlite3DbFree(db, zParent);
89345    }
89346  }
89347
89348  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
89349  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
89350  sqlite3DbFree(db, zOutput);
89351}
89352#endif
89353
89354#ifndef SQLITE_OMIT_TRIGGER
89355/* This function is used by SQL generated to implement the
89356** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
89357** statement. The second is a table name. The table name in the CREATE
89358** TRIGGER statement is replaced with the third argument and the result
89359** returned. This is analagous to renameTableFunc() above, except for CREATE
89360** TRIGGER, not CREATE INDEX and CREATE TABLE.
89361*/
89362static void renameTriggerFunc(
89363  sqlite3_context *context,
89364  int NotUsed,
89365  sqlite3_value **argv
89366){
89367  unsigned char const *zSql = sqlite3_value_text(argv[0]);
89368  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
89369
89370  int token;
89371  Token tname;
89372  int dist = 3;
89373  unsigned char const *zCsr = zSql;
89374  int len = 0;
89375  char *zRet;
89376  sqlite3 *db = sqlite3_context_db_handle(context);
89377
89378  UNUSED_PARAMETER(NotUsed);
89379
89380  /* The principle used to locate the table name in the CREATE TRIGGER
89381  ** statement is that the table name is the first token that is immediately
89382  ** preceded by either TK_ON or TK_DOT and immediately followed by one
89383  ** of TK_WHEN, TK_BEGIN or TK_FOR.
89384  */
89385  if( zSql ){
89386    do {
89387
89388      if( !*zCsr ){
89389        /* Ran out of input before finding the table name. Return NULL. */
89390        return;
89391      }
89392
89393      /* Store the token that zCsr points to in tname. */
89394      tname.z = (char*)zCsr;
89395      tname.n = len;
89396
89397      /* Advance zCsr to the next token. Store that token type in 'token',
89398      ** and its length in 'len' (to be used next iteration of this loop).
89399      */
89400      do {
89401        zCsr += len;
89402        len = sqlite3GetToken(zCsr, &token);
89403      }while( token==TK_SPACE );
89404      assert( len>0 );
89405
89406      /* Variable 'dist' stores the number of tokens read since the most
89407      ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
89408      ** token is read and 'dist' equals 2, the condition stated above
89409      ** to be met.
89410      **
89411      ** Note that ON cannot be a database, table or column name, so
89412      ** there is no need to worry about syntax like
89413      ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
89414      */
89415      dist++;
89416      if( token==TK_DOT || token==TK_ON ){
89417        dist = 0;
89418      }
89419    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
89420
89421    /* Variable tname now contains the token that is the old table-name
89422    ** in the CREATE TRIGGER statement.
89423    */
89424    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
89425       zSql, zTableName, tname.z+tname.n);
89426    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
89427  }
89428}
89429#endif   /* !SQLITE_OMIT_TRIGGER */
89430
89431/*
89432** Register built-in functions used to help implement ALTER TABLE
89433*/
89434SQLITE_PRIVATE void sqlite3AlterFunctions(void){
89435  static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
89436    FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
89437#ifndef SQLITE_OMIT_TRIGGER
89438    FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
89439#endif
89440#ifndef SQLITE_OMIT_FOREIGN_KEY
89441    FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
89442#endif
89443  };
89444  int i;
89445  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
89446  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
89447
89448  for(i=0; i<ArraySize(aAlterTableFuncs); i++){
89449    sqlite3FuncDefInsert(pHash, &aFunc[i]);
89450  }
89451}
89452
89453/*
89454** This function is used to create the text of expressions of the form:
89455**
89456**   name=<constant1> OR name=<constant2> OR ...
89457**
89458** If argument zWhere is NULL, then a pointer string containing the text
89459** "name=<constant>" is returned, where <constant> is the quoted version
89460** of the string passed as argument zConstant. The returned buffer is
89461** allocated using sqlite3DbMalloc(). It is the responsibility of the
89462** caller to ensure that it is eventually freed.
89463**
89464** If argument zWhere is not NULL, then the string returned is
89465** "<where> OR name=<constant>", where <where> is the contents of zWhere.
89466** In this case zWhere is passed to sqlite3DbFree() before returning.
89467**
89468*/
89469static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
89470  char *zNew;
89471  if( !zWhere ){
89472    zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
89473  }else{
89474    zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
89475    sqlite3DbFree(db, zWhere);
89476  }
89477  return zNew;
89478}
89479
89480#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
89481/*
89482** Generate the text of a WHERE expression which can be used to select all
89483** tables that have foreign key constraints that refer to table pTab (i.e.
89484** constraints for which pTab is the parent table) from the sqlite_master
89485** table.
89486*/
89487static char *whereForeignKeys(Parse *pParse, Table *pTab){
89488  FKey *p;
89489  char *zWhere = 0;
89490  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
89491    zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
89492  }
89493  return zWhere;
89494}
89495#endif
89496
89497/*
89498** Generate the text of a WHERE expression which can be used to select all
89499** temporary triggers on table pTab from the sqlite_temp_master table. If
89500** table pTab has no temporary triggers, or is itself stored in the
89501** temporary database, NULL is returned.
89502*/
89503static char *whereTempTriggers(Parse *pParse, Table *pTab){
89504  Trigger *pTrig;
89505  char *zWhere = 0;
89506  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
89507
89508  /* If the table is not located in the temp-db (in which case NULL is
89509  ** returned, loop through the tables list of triggers. For each trigger
89510  ** that is not part of the temp-db schema, add a clause to the WHERE
89511  ** expression being built up in zWhere.
89512  */
89513  if( pTab->pSchema!=pTempSchema ){
89514    sqlite3 *db = pParse->db;
89515    for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
89516      if( pTrig->pSchema==pTempSchema ){
89517        zWhere = whereOrName(db, zWhere, pTrig->zName);
89518      }
89519    }
89520  }
89521  if( zWhere ){
89522    char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
89523    sqlite3DbFree(pParse->db, zWhere);
89524    zWhere = zNew;
89525  }
89526  return zWhere;
89527}
89528
89529/*
89530** Generate code to drop and reload the internal representation of table
89531** pTab from the database, including triggers and temporary triggers.
89532** Argument zName is the name of the table in the database schema at
89533** the time the generated code is executed. This can be different from
89534** pTab->zName if this function is being called to code part of an
89535** "ALTER TABLE RENAME TO" statement.
89536*/
89537static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
89538  Vdbe *v;
89539  char *zWhere;
89540  int iDb;                   /* Index of database containing pTab */
89541#ifndef SQLITE_OMIT_TRIGGER
89542  Trigger *pTrig;
89543#endif
89544
89545  v = sqlite3GetVdbe(pParse);
89546  if( NEVER(v==0) ) return;
89547  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
89548  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
89549  assert( iDb>=0 );
89550
89551#ifndef SQLITE_OMIT_TRIGGER
89552  /* Drop any table triggers from the internal schema. */
89553  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
89554    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
89555    assert( iTrigDb==iDb || iTrigDb==1 );
89556    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
89557  }
89558#endif
89559
89560  /* Drop the table and index from the internal schema.  */
89561  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
89562
89563  /* Reload the table, index and permanent trigger schemas. */
89564  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
89565  if( !zWhere ) return;
89566  sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
89567
89568#ifndef SQLITE_OMIT_TRIGGER
89569  /* Now, if the table is not stored in the temp database, reload any temp
89570  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
89571  */
89572  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
89573    sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
89574  }
89575#endif
89576}
89577
89578/*
89579** Parameter zName is the name of a table that is about to be altered
89580** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
89581** If the table is a system table, this function leaves an error message
89582** in pParse->zErr (system tables may not be altered) and returns non-zero.
89583**
89584** Or, if zName is not a system table, zero is returned.
89585*/
89586static int isSystemTable(Parse *pParse, const char *zName){
89587  if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
89588    sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
89589    return 1;
89590  }
89591  return 0;
89592}
89593
89594/*
89595** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
89596** command.
89597*/
89598SQLITE_PRIVATE void sqlite3AlterRenameTable(
89599  Parse *pParse,            /* Parser context. */
89600  SrcList *pSrc,            /* The table to rename. */
89601  Token *pName              /* The new table name. */
89602){
89603  int iDb;                  /* Database that contains the table */
89604  char *zDb;                /* Name of database iDb */
89605  Table *pTab;              /* Table being renamed */
89606  char *zName = 0;          /* NULL-terminated version of pName */
89607  sqlite3 *db = pParse->db; /* Database connection */
89608  int nTabName;             /* Number of UTF-8 characters in zTabName */
89609  const char *zTabName;     /* Original name of the table */
89610  Vdbe *v;
89611#ifndef SQLITE_OMIT_TRIGGER
89612  char *zWhere = 0;         /* Where clause to locate temp triggers */
89613#endif
89614  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
89615  int savedDbFlags;         /* Saved value of db->flags */
89616
89617  savedDbFlags = db->flags;
89618  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
89619  assert( pSrc->nSrc==1 );
89620  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
89621
89622  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
89623  if( !pTab ) goto exit_rename_table;
89624  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
89625  zDb = db->aDb[iDb].zName;
89626  db->flags |= SQLITE_PreferBuiltin;
89627
89628  /* Get a NULL terminated version of the new table name. */
89629  zName = sqlite3NameFromToken(db, pName);
89630  if( !zName ) goto exit_rename_table;
89631
89632  /* Check that a table or index named 'zName' does not already exist
89633  ** in database iDb. If so, this is an error.
89634  */
89635  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
89636    sqlite3ErrorMsg(pParse,
89637        "there is already another table or index with this name: %s", zName);
89638    goto exit_rename_table;
89639  }
89640
89641  /* Make sure it is not a system table being altered, or a reserved name
89642  ** that the table is being renamed to.
89643  */
89644  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
89645    goto exit_rename_table;
89646  }
89647  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
89648    exit_rename_table;
89649  }
89650
89651#ifndef SQLITE_OMIT_VIEW
89652  if( pTab->pSelect ){
89653    sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
89654    goto exit_rename_table;
89655  }
89656#endif
89657
89658#ifndef SQLITE_OMIT_AUTHORIZATION
89659  /* Invoke the authorization callback. */
89660  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
89661    goto exit_rename_table;
89662  }
89663#endif
89664
89665#ifndef SQLITE_OMIT_VIRTUALTABLE
89666  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
89667    goto exit_rename_table;
89668  }
89669  if( IsVirtual(pTab) ){
89670    pVTab = sqlite3GetVTable(db, pTab);
89671    if( pVTab->pVtab->pModule->xRename==0 ){
89672      pVTab = 0;
89673    }
89674  }
89675#endif
89676
89677  /* Begin a transaction for database iDb.
89678  ** Then modify the schema cookie (since the ALTER TABLE modifies the
89679  ** schema). Open a statement transaction if the table is a virtual
89680  ** table.
89681  */
89682  v = sqlite3GetVdbe(pParse);
89683  if( v==0 ){
89684    goto exit_rename_table;
89685  }
89686  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
89687  sqlite3ChangeCookie(pParse, iDb);
89688
89689  /* If this is a virtual table, invoke the xRename() function if
89690  ** one is defined. The xRename() callback will modify the names
89691  ** of any resources used by the v-table implementation (including other
89692  ** SQLite tables) that are identified by the name of the virtual table.
89693  */
89694#ifndef SQLITE_OMIT_VIRTUALTABLE
89695  if( pVTab ){
89696    int i = ++pParse->nMem;
89697    sqlite3VdbeLoadString(v, i, zName);
89698    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
89699    sqlite3MayAbort(pParse);
89700  }
89701#endif
89702
89703  /* figure out how many UTF-8 characters are in zName */
89704  zTabName = pTab->zName;
89705  nTabName = sqlite3Utf8CharLen(zTabName, -1);
89706
89707#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
89708  if( db->flags&SQLITE_ForeignKeys ){
89709    /* If foreign-key support is enabled, rewrite the CREATE TABLE
89710    ** statements corresponding to all child tables of foreign key constraints
89711    ** for which the renamed table is the parent table.  */
89712    if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
89713      sqlite3NestedParse(pParse,
89714          "UPDATE \"%w\".%s SET "
89715              "sql = sqlite_rename_parent(sql, %Q, %Q) "
89716              "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
89717      sqlite3DbFree(db, zWhere);
89718    }
89719  }
89720#endif
89721
89722  /* Modify the sqlite_master table to use the new table name. */
89723  sqlite3NestedParse(pParse,
89724      "UPDATE %Q.%s SET "
89725#ifdef SQLITE_OMIT_TRIGGER
89726          "sql = sqlite_rename_table(sql, %Q), "
89727#else
89728          "sql = CASE "
89729            "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
89730            "ELSE sqlite_rename_table(sql, %Q) END, "
89731#endif
89732          "tbl_name = %Q, "
89733          "name = CASE "
89734            "WHEN type='table' THEN %Q "
89735            "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
89736             "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
89737            "ELSE name END "
89738      "WHERE tbl_name=%Q COLLATE nocase AND "
89739          "(type='table' OR type='index' OR type='trigger');",
89740      zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
89741#ifndef SQLITE_OMIT_TRIGGER
89742      zName,
89743#endif
89744      zName, nTabName, zTabName
89745  );
89746
89747#ifndef SQLITE_OMIT_AUTOINCREMENT
89748  /* If the sqlite_sequence table exists in this database, then update
89749  ** it with the new table name.
89750  */
89751  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
89752    sqlite3NestedParse(pParse,
89753        "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
89754        zDb, zName, pTab->zName);
89755  }
89756#endif
89757
89758#ifndef SQLITE_OMIT_TRIGGER
89759  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
89760  ** table. Don't do this if the table being ALTERed is itself located in
89761  ** the temp database.
89762  */
89763  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
89764    sqlite3NestedParse(pParse,
89765        "UPDATE sqlite_temp_master SET "
89766            "sql = sqlite_rename_trigger(sql, %Q), "
89767            "tbl_name = %Q "
89768            "WHERE %s;", zName, zName, zWhere);
89769    sqlite3DbFree(db, zWhere);
89770  }
89771#endif
89772
89773#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
89774  if( db->flags&SQLITE_ForeignKeys ){
89775    FKey *p;
89776    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
89777      Table *pFrom = p->pFrom;
89778      if( pFrom!=pTab ){
89779        reloadTableSchema(pParse, p->pFrom, pFrom->zName);
89780      }
89781    }
89782  }
89783#endif
89784
89785  /* Drop and reload the internal table schema. */
89786  reloadTableSchema(pParse, pTab, zName);
89787
89788exit_rename_table:
89789  sqlite3SrcListDelete(db, pSrc);
89790  sqlite3DbFree(db, zName);
89791  db->flags = savedDbFlags;
89792}
89793
89794
89795/*
89796** Generate code to make sure the file format number is at least minFormat.
89797** The generated code will increase the file format number if necessary.
89798*/
89799SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
89800  Vdbe *v;
89801  v = sqlite3GetVdbe(pParse);
89802  /* The VDBE should have been allocated before this routine is called.
89803  ** If that allocation failed, we would have quit before reaching this
89804  ** point */
89805  if( ALWAYS(v) ){
89806    int r1 = sqlite3GetTempReg(pParse);
89807    int r2 = sqlite3GetTempReg(pParse);
89808    int addr1;
89809    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
89810    sqlite3VdbeUsesBtree(v, iDb);
89811    sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
89812    addr1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
89813    sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v);
89814    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
89815    sqlite3VdbeJumpHere(v, addr1);
89816    sqlite3ReleaseTempReg(pParse, r1);
89817    sqlite3ReleaseTempReg(pParse, r2);
89818  }
89819}
89820
89821/*
89822** This function is called after an "ALTER TABLE ... ADD" statement
89823** has been parsed. Argument pColDef contains the text of the new
89824** column definition.
89825**
89826** The Table structure pParse->pNewTable was extended to include
89827** the new column during parsing.
89828*/
89829SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
89830  Table *pNew;              /* Copy of pParse->pNewTable */
89831  Table *pTab;              /* Table being altered */
89832  int iDb;                  /* Database number */
89833  const char *zDb;          /* Database name */
89834  const char *zTab;         /* Table name */
89835  char *zCol;               /* Null-terminated column definition */
89836  Column *pCol;             /* The new column */
89837  Expr *pDflt;              /* Default value for the new column */
89838  sqlite3 *db;              /* The database connection; */
89839
89840  db = pParse->db;
89841  if( pParse->nErr || db->mallocFailed ) return;
89842  pNew = pParse->pNewTable;
89843  assert( pNew );
89844
89845  assert( sqlite3BtreeHoldsAllMutexes(db) );
89846  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
89847  zDb = db->aDb[iDb].zName;
89848  zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
89849  pCol = &pNew->aCol[pNew->nCol-1];
89850  pDflt = pCol->pDflt;
89851  pTab = sqlite3FindTable(db, zTab, zDb);
89852  assert( pTab );
89853
89854#ifndef SQLITE_OMIT_AUTHORIZATION
89855  /* Invoke the authorization callback. */
89856  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
89857    return;
89858  }
89859#endif
89860
89861  /* If the default value for the new column was specified with a
89862  ** literal NULL, then set pDflt to 0. This simplifies checking
89863  ** for an SQL NULL default below.
89864  */
89865  if( pDflt && pDflt->op==TK_NULL ){
89866    pDflt = 0;
89867  }
89868
89869  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
89870  ** If there is a NOT NULL constraint, then the default value for the
89871  ** column must not be NULL.
89872  */
89873  if( pCol->colFlags & COLFLAG_PRIMKEY ){
89874    sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
89875    return;
89876  }
89877  if( pNew->pIndex ){
89878    sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
89879    return;
89880  }
89881  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
89882    sqlite3ErrorMsg(pParse,
89883        "Cannot add a REFERENCES column with non-NULL default value");
89884    return;
89885  }
89886  if( pCol->notNull && !pDflt ){
89887    sqlite3ErrorMsg(pParse,
89888        "Cannot add a NOT NULL column with default value NULL");
89889    return;
89890  }
89891
89892  /* Ensure the default expression is something that sqlite3ValueFromExpr()
89893  ** can handle (i.e. not CURRENT_TIME etc.)
89894  */
89895  if( pDflt ){
89896    sqlite3_value *pVal = 0;
89897    int rc;
89898    rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
89899    assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
89900    if( rc!=SQLITE_OK ){
89901      db->mallocFailed = 1;
89902      return;
89903    }
89904    if( !pVal ){
89905      sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
89906      return;
89907    }
89908    sqlite3ValueFree(pVal);
89909  }
89910
89911  /* Modify the CREATE TABLE statement. */
89912  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
89913  if( zCol ){
89914    char *zEnd = &zCol[pColDef->n-1];
89915    int savedDbFlags = db->flags;
89916    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
89917      *zEnd-- = '\0';
89918    }
89919    db->flags |= SQLITE_PreferBuiltin;
89920    sqlite3NestedParse(pParse,
89921        "UPDATE \"%w\".%s SET "
89922          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
89923        "WHERE type = 'table' AND name = %Q",
89924      zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
89925      zTab
89926    );
89927    sqlite3DbFree(db, zCol);
89928    db->flags = savedDbFlags;
89929  }
89930
89931  /* If the default value of the new column is NULL, then set the file
89932  ** format to 2. If the default value of the new column is not NULL,
89933  ** the file format becomes 3.
89934  */
89935  sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
89936
89937  /* Reload the schema of the modified table. */
89938  reloadTableSchema(pParse, pTab, pTab->zName);
89939}
89940
89941/*
89942** This function is called by the parser after the table-name in
89943** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
89944** pSrc is the full-name of the table being altered.
89945**
89946** This routine makes a (partial) copy of the Table structure
89947** for the table being altered and sets Parse.pNewTable to point
89948** to it. Routines called by the parser as the column definition
89949** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
89950** the copy. The copy of the Table structure is deleted by tokenize.c
89951** after parsing is finished.
89952**
89953** Routine sqlite3AlterFinishAddColumn() will be called to complete
89954** coding the "ALTER TABLE ... ADD" statement.
89955*/
89956SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
89957  Table *pNew;
89958  Table *pTab;
89959  Vdbe *v;
89960  int iDb;
89961  int i;
89962  int nAlloc;
89963  sqlite3 *db = pParse->db;
89964
89965  /* Look up the table being altered. */
89966  assert( pParse->pNewTable==0 );
89967  assert( sqlite3BtreeHoldsAllMutexes(db) );
89968  if( db->mallocFailed ) goto exit_begin_add_column;
89969  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
89970  if( !pTab ) goto exit_begin_add_column;
89971
89972#ifndef SQLITE_OMIT_VIRTUALTABLE
89973  if( IsVirtual(pTab) ){
89974    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
89975    goto exit_begin_add_column;
89976  }
89977#endif
89978
89979  /* Make sure this is not an attempt to ALTER a view. */
89980  if( pTab->pSelect ){
89981    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
89982    goto exit_begin_add_column;
89983  }
89984  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
89985    goto exit_begin_add_column;
89986  }
89987
89988  assert( pTab->addColOffset>0 );
89989  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
89990
89991  /* Put a copy of the Table struct in Parse.pNewTable for the
89992  ** sqlite3AddColumn() function and friends to modify.  But modify
89993  ** the name by adding an "sqlite_altertab_" prefix.  By adding this
89994  ** prefix, we insure that the name will not collide with an existing
89995  ** table because user table are not allowed to have the "sqlite_"
89996  ** prefix on their name.
89997  */
89998  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
89999  if( !pNew ) goto exit_begin_add_column;
90000  pParse->pNewTable = pNew;
90001  pNew->nRef = 1;
90002  pNew->nCol = pTab->nCol;
90003  assert( pNew->nCol>0 );
90004  nAlloc = (((pNew->nCol-1)/8)*8)+8;
90005  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
90006  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
90007  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
90008  if( !pNew->aCol || !pNew->zName ){
90009    db->mallocFailed = 1;
90010    goto exit_begin_add_column;
90011  }
90012  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
90013  for(i=0; i<pNew->nCol; i++){
90014    Column *pCol = &pNew->aCol[i];
90015    pCol->zName = sqlite3DbStrDup(db, pCol->zName);
90016    pCol->zColl = 0;
90017    pCol->zType = 0;
90018    pCol->pDflt = 0;
90019    pCol->zDflt = 0;
90020  }
90021  pNew->pSchema = db->aDb[iDb].pSchema;
90022  pNew->addColOffset = pTab->addColOffset;
90023  pNew->nRef = 1;
90024
90025  /* Begin a transaction and increment the schema cookie.  */
90026  sqlite3BeginWriteOperation(pParse, 0, iDb);
90027  v = sqlite3GetVdbe(pParse);
90028  if( !v ) goto exit_begin_add_column;
90029  sqlite3ChangeCookie(pParse, iDb);
90030
90031exit_begin_add_column:
90032  sqlite3SrcListDelete(db, pSrc);
90033  return;
90034}
90035#endif  /* SQLITE_ALTER_TABLE */
90036
90037/************** End of alter.c ***********************************************/
90038/************** Begin file analyze.c *****************************************/
90039/*
90040** 2005-07-08
90041**
90042** The author disclaims copyright to this source code.  In place of
90043** a legal notice, here is a blessing:
90044**
90045**    May you do good and not evil.
90046**    May you find forgiveness for yourself and forgive others.
90047**    May you share freely, never taking more than you give.
90048**
90049*************************************************************************
90050** This file contains code associated with the ANALYZE command.
90051**
90052** The ANALYZE command gather statistics about the content of tables
90053** and indices.  These statistics are made available to the query planner
90054** to help it make better decisions about how to perform queries.
90055**
90056** The following system tables are or have been supported:
90057**
90058**    CREATE TABLE sqlite_stat1(tbl, idx, stat);
90059**    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
90060**    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
90061**    CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
90062**
90063** Additional tables might be added in future releases of SQLite.
90064** The sqlite_stat2 table is not created or used unless the SQLite version
90065** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
90066** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
90067** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
90068** created and used by SQLite versions 3.7.9 and later and with
90069** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3
90070** is a superset of sqlite_stat2.  The sqlite_stat4 is an enhanced
90071** version of sqlite_stat3 and is only available when compiled with
90072** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later.  It is
90073** not possible to enable both STAT3 and STAT4 at the same time.  If they
90074** are both enabled, then STAT4 takes precedence.
90075**
90076** For most applications, sqlite_stat1 provides all the statistics required
90077** for the query planner to make good choices.
90078**
90079** Format of sqlite_stat1:
90080**
90081** There is normally one row per index, with the index identified by the
90082** name in the idx column.  The tbl column is the name of the table to
90083** which the index belongs.  In each such row, the stat column will be
90084** a string consisting of a list of integers.  The first integer in this
90085** list is the number of rows in the index.  (This is the same as the
90086** number of rows in the table, except for partial indices.)  The second
90087** integer is the average number of rows in the index that have the same
90088** value in the first column of the index.  The third integer is the average
90089** number of rows in the index that have the same value for the first two
90090** columns.  The N-th integer (for N>1) is the average number of rows in
90091** the index which have the same value for the first N-1 columns.  For
90092** a K-column index, there will be K+1 integers in the stat column.  If
90093** the index is unique, then the last integer will be 1.
90094**
90095** The list of integers in the stat column can optionally be followed
90096** by the keyword "unordered".  The "unordered" keyword, if it is present,
90097** must be separated from the last integer by a single space.  If the
90098** "unordered" keyword is present, then the query planner assumes that
90099** the index is unordered and will not use the index for a range query.
90100**
90101** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
90102** column contains a single integer which is the (estimated) number of
90103** rows in the table identified by sqlite_stat1.tbl.
90104**
90105** Format of sqlite_stat2:
90106**
90107** The sqlite_stat2 is only created and is only used if SQLite is compiled
90108** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
90109** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
90110** about the distribution of keys within an index.  The index is identified by
90111** the "idx" column and the "tbl" column is the name of the table to which
90112** the index belongs.  There are usually 10 rows in the sqlite_stat2
90113** table for each index.
90114**
90115** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
90116** inclusive are samples of the left-most key value in the index taken at
90117** evenly spaced points along the index.  Let the number of samples be S
90118** (10 in the standard build) and let C be the number of rows in the index.
90119** Then the sampled rows are given by:
90120**
90121**     rownumber = (i*C*2 + C)/(S*2)
90122**
90123** For i between 0 and S-1.  Conceptually, the index space is divided into
90124** S uniform buckets and the samples are the middle row from each bucket.
90125**
90126** The format for sqlite_stat2 is recorded here for legacy reference.  This
90127** version of SQLite does not support sqlite_stat2.  It neither reads nor
90128** writes the sqlite_stat2 table.  This version of SQLite only supports
90129** sqlite_stat3.
90130**
90131** Format for sqlite_stat3:
90132**
90133** The sqlite_stat3 format is a subset of sqlite_stat4.  Hence, the
90134** sqlite_stat4 format will be described first.  Further information
90135** about sqlite_stat3 follows the sqlite_stat4 description.
90136**
90137** Format for sqlite_stat4:
90138**
90139** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
90140** to aid the query planner in choosing good indices based on the values
90141** that indexed columns are compared against in the WHERE clauses of
90142** queries.
90143**
90144** The sqlite_stat4 table contains multiple entries for each index.
90145** The idx column names the index and the tbl column is the table of the
90146** index.  If the idx and tbl columns are the same, then the sample is
90147** of the INTEGER PRIMARY KEY.  The sample column is a blob which is the
90148** binary encoding of a key from the index.  The nEq column is a
90149** list of integers.  The first integer is the approximate number
90150** of entries in the index whose left-most column exactly matches
90151** the left-most column of the sample.  The second integer in nEq
90152** is the approximate number of entries in the index where the
90153** first two columns match the first two columns of the sample.
90154** And so forth.  nLt is another list of integers that show the approximate
90155** number of entries that are strictly less than the sample.  The first
90156** integer in nLt contains the number of entries in the index where the
90157** left-most column is less than the left-most column of the sample.
90158** The K-th integer in the nLt entry is the number of index entries
90159** where the first K columns are less than the first K columns of the
90160** sample.  The nDLt column is like nLt except that it contains the
90161** number of distinct entries in the index that are less than the
90162** sample.
90163**
90164** There can be an arbitrary number of sqlite_stat4 entries per index.
90165** The ANALYZE command will typically generate sqlite_stat4 tables
90166** that contain between 10 and 40 samples which are distributed across
90167** the key space, though not uniformly, and which include samples with
90168** large nEq values.
90169**
90170** Format for sqlite_stat3 redux:
90171**
90172** The sqlite_stat3 table is like sqlite_stat4 except that it only
90173** looks at the left-most column of the index.  The sqlite_stat3.sample
90174** column contains the actual value of the left-most column instead
90175** of a blob encoding of the complete index key as is found in
90176** sqlite_stat4.sample.  The nEq, nLt, and nDLt entries of sqlite_stat3
90177** all contain just a single integer which is the same as the first
90178** integer in the equivalent columns in sqlite_stat4.
90179*/
90180#ifndef SQLITE_OMIT_ANALYZE
90181/* #include "sqliteInt.h" */
90182
90183#if defined(SQLITE_ENABLE_STAT4)
90184# define IsStat4     1
90185# define IsStat3     0
90186#elif defined(SQLITE_ENABLE_STAT3)
90187# define IsStat4     0
90188# define IsStat3     1
90189#else
90190# define IsStat4     0
90191# define IsStat3     0
90192# undef SQLITE_STAT4_SAMPLES
90193# define SQLITE_STAT4_SAMPLES 1
90194#endif
90195#define IsStat34    (IsStat3+IsStat4)  /* 1 for STAT3 or STAT4. 0 otherwise */
90196
90197/*
90198** This routine generates code that opens the sqlite_statN tables.
90199** The sqlite_stat1 table is always relevant.  sqlite_stat2 is now
90200** obsolete.  sqlite_stat3 and sqlite_stat4 are only opened when
90201** appropriate compile-time options are provided.
90202**
90203** If the sqlite_statN tables do not previously exist, it is created.
90204**
90205** Argument zWhere may be a pointer to a buffer containing a table name,
90206** or it may be a NULL pointer. If it is not NULL, then all entries in
90207** the sqlite_statN tables associated with the named table are deleted.
90208** If zWhere==0, then code is generated to delete all stat table entries.
90209*/
90210static void openStatTable(
90211  Parse *pParse,          /* Parsing context */
90212  int iDb,                /* The database we are looking in */
90213  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
90214  const char *zWhere,     /* Delete entries for this table or index */
90215  const char *zWhereType  /* Either "tbl" or "idx" */
90216){
90217  static const struct {
90218    const char *zName;
90219    const char *zCols;
90220  } aTable[] = {
90221    { "sqlite_stat1", "tbl,idx,stat" },
90222#if defined(SQLITE_ENABLE_STAT4)
90223    { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
90224    { "sqlite_stat3", 0 },
90225#elif defined(SQLITE_ENABLE_STAT3)
90226    { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
90227    { "sqlite_stat4", 0 },
90228#else
90229    { "sqlite_stat3", 0 },
90230    { "sqlite_stat4", 0 },
90231#endif
90232  };
90233  int i;
90234  sqlite3 *db = pParse->db;
90235  Db *pDb;
90236  Vdbe *v = sqlite3GetVdbe(pParse);
90237  int aRoot[ArraySize(aTable)];
90238  u8 aCreateTbl[ArraySize(aTable)];
90239
90240  if( v==0 ) return;
90241  assert( sqlite3BtreeHoldsAllMutexes(db) );
90242  assert( sqlite3VdbeDb(v)==db );
90243  pDb = &db->aDb[iDb];
90244
90245  /* Create new statistic tables if they do not exist, or clear them
90246  ** if they do already exist.
90247  */
90248  for(i=0; i<ArraySize(aTable); i++){
90249    const char *zTab = aTable[i].zName;
90250    Table *pStat;
90251    if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
90252      if( aTable[i].zCols ){
90253        /* The sqlite_statN table does not exist. Create it. Note that a
90254        ** side-effect of the CREATE TABLE statement is to leave the rootpage
90255        ** of the new table in register pParse->regRoot. This is important
90256        ** because the OpenWrite opcode below will be needing it. */
90257        sqlite3NestedParse(pParse,
90258            "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
90259        );
90260        aRoot[i] = pParse->regRoot;
90261        aCreateTbl[i] = OPFLAG_P2ISREG;
90262      }
90263    }else{
90264      /* The table already exists. If zWhere is not NULL, delete all entries
90265      ** associated with the table zWhere. If zWhere is NULL, delete the
90266      ** entire contents of the table. */
90267      aRoot[i] = pStat->tnum;
90268      aCreateTbl[i] = 0;
90269      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
90270      if( zWhere ){
90271        sqlite3NestedParse(pParse,
90272           "DELETE FROM %Q.%s WHERE %s=%Q",
90273           pDb->zName, zTab, zWhereType, zWhere
90274        );
90275      }else{
90276        /* The sqlite_stat[134] table already exists.  Delete all rows. */
90277        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
90278      }
90279    }
90280  }
90281
90282  /* Open the sqlite_stat[134] tables for writing. */
90283  for(i=0; aTable[i].zCols; i++){
90284    assert( i<ArraySize(aTable) );
90285    sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
90286    sqlite3VdbeChangeP5(v, aCreateTbl[i]);
90287    VdbeComment((v, aTable[i].zName));
90288  }
90289}
90290
90291/*
90292** Recommended number of samples for sqlite_stat4
90293*/
90294#ifndef SQLITE_STAT4_SAMPLES
90295# define SQLITE_STAT4_SAMPLES 24
90296#endif
90297
90298/*
90299** Three SQL functions - stat_init(), stat_push(), and stat_get() -
90300** share an instance of the following structure to hold their state
90301** information.
90302*/
90303typedef struct Stat4Accum Stat4Accum;
90304typedef struct Stat4Sample Stat4Sample;
90305struct Stat4Sample {
90306  tRowcnt *anEq;                  /* sqlite_stat4.nEq */
90307  tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */
90308#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90309  tRowcnt *anLt;                  /* sqlite_stat4.nLt */
90310  union {
90311    i64 iRowid;                     /* Rowid in main table of the key */
90312    u8 *aRowid;                     /* Key for WITHOUT ROWID tables */
90313  } u;
90314  u32 nRowid;                     /* Sizeof aRowid[] */
90315  u8 isPSample;                   /* True if a periodic sample */
90316  int iCol;                       /* If !isPSample, the reason for inclusion */
90317  u32 iHash;                      /* Tiebreaker hash */
90318#endif
90319};
90320struct Stat4Accum {
90321  tRowcnt nRow;             /* Number of rows in the entire table */
90322  tRowcnt nPSample;         /* How often to do a periodic sample */
90323  int nCol;                 /* Number of columns in index + pk/rowid */
90324  int nKeyCol;              /* Number of index columns w/o the pk/rowid */
90325  int mxSample;             /* Maximum number of samples to accumulate */
90326  Stat4Sample current;      /* Current row as a Stat4Sample */
90327  u32 iPrn;                 /* Pseudo-random number used for sampling */
90328  Stat4Sample *aBest;       /* Array of nCol best samples */
90329  int iMin;                 /* Index in a[] of entry with minimum score */
90330  int nSample;              /* Current number of samples */
90331  int iGet;                 /* Index of current sample accessed by stat_get() */
90332  Stat4Sample *a;           /* Array of mxSample Stat4Sample objects */
90333  sqlite3 *db;              /* Database connection, for malloc() */
90334};
90335
90336/* Reclaim memory used by a Stat4Sample
90337*/
90338#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90339static void sampleClear(sqlite3 *db, Stat4Sample *p){
90340  assert( db!=0 );
90341  if( p->nRowid ){
90342    sqlite3DbFree(db, p->u.aRowid);
90343    p->nRowid = 0;
90344  }
90345}
90346#endif
90347
90348/* Initialize the BLOB value of a ROWID
90349*/
90350#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90351static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
90352  assert( db!=0 );
90353  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
90354  p->u.aRowid = sqlite3DbMallocRaw(db, n);
90355  if( p->u.aRowid ){
90356    p->nRowid = n;
90357    memcpy(p->u.aRowid, pData, n);
90358  }else{
90359    p->nRowid = 0;
90360  }
90361}
90362#endif
90363
90364/* Initialize the INTEGER value of a ROWID.
90365*/
90366#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90367static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
90368  assert( db!=0 );
90369  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
90370  p->nRowid = 0;
90371  p->u.iRowid = iRowid;
90372}
90373#endif
90374
90375
90376/*
90377** Copy the contents of object (*pFrom) into (*pTo).
90378*/
90379#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90380static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
90381  pTo->isPSample = pFrom->isPSample;
90382  pTo->iCol = pFrom->iCol;
90383  pTo->iHash = pFrom->iHash;
90384  memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
90385  memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
90386  memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
90387  if( pFrom->nRowid ){
90388    sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
90389  }else{
90390    sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
90391  }
90392}
90393#endif
90394
90395/*
90396** Reclaim all memory of a Stat4Accum structure.
90397*/
90398static void stat4Destructor(void *pOld){
90399  Stat4Accum *p = (Stat4Accum*)pOld;
90400#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90401  int i;
90402  for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
90403  for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
90404  sampleClear(p->db, &p->current);
90405#endif
90406  sqlite3DbFree(p->db, p);
90407}
90408
90409/*
90410** Implementation of the stat_init(N,K,C) SQL function. The three parameters
90411** are:
90412**     N:    The number of columns in the index including the rowid/pk (note 1)
90413**     K:    The number of columns in the index excluding the rowid/pk.
90414**     C:    The number of rows in the index (note 2)
90415**
90416** Note 1:  In the special case of the covering index that implements a
90417** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
90418** total number of columns in the table.
90419**
90420** Note 2:  C is only used for STAT3 and STAT4.
90421**
90422** For indexes on ordinary rowid tables, N==K+1.  But for indexes on
90423** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
90424** PRIMARY KEY of the table.  The covering index that implements the
90425** original WITHOUT ROWID table as N==K as a special case.
90426**
90427** This routine allocates the Stat4Accum object in heap memory. The return
90428** value is a pointer to the Stat4Accum object.  The datatype of the
90429** return value is BLOB, but it is really just a pointer to the Stat4Accum
90430** object.
90431*/
90432static void statInit(
90433  sqlite3_context *context,
90434  int argc,
90435  sqlite3_value **argv
90436){
90437  Stat4Accum *p;
90438  int nCol;                       /* Number of columns in index being sampled */
90439  int nKeyCol;                    /* Number of key columns */
90440  int nColUp;                     /* nCol rounded up for alignment */
90441  int n;                          /* Bytes of space to allocate */
90442  sqlite3 *db;                    /* Database connection */
90443#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90444  int mxSample = SQLITE_STAT4_SAMPLES;
90445#endif
90446
90447  /* Decode the three function arguments */
90448  UNUSED_PARAMETER(argc);
90449  nCol = sqlite3_value_int(argv[0]);
90450  assert( nCol>0 );
90451  nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
90452  nKeyCol = sqlite3_value_int(argv[1]);
90453  assert( nKeyCol<=nCol );
90454  assert( nKeyCol>0 );
90455
90456  /* Allocate the space required for the Stat4Accum object */
90457  n = sizeof(*p)
90458    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anEq */
90459    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anDLt */
90460#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90461    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anLt */
90462    + sizeof(Stat4Sample)*(nCol+mxSample)     /* Stat4Accum.aBest[], a[] */
90463    + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
90464#endif
90465  ;
90466  db = sqlite3_context_db_handle(context);
90467  p = sqlite3DbMallocZero(db, n);
90468  if( p==0 ){
90469    sqlite3_result_error_nomem(context);
90470    return;
90471  }
90472
90473  p->db = db;
90474  p->nRow = 0;
90475  p->nCol = nCol;
90476  p->nKeyCol = nKeyCol;
90477  p->current.anDLt = (tRowcnt*)&p[1];
90478  p->current.anEq = &p->current.anDLt[nColUp];
90479
90480#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90481  {
90482    u8 *pSpace;                     /* Allocated space not yet assigned */
90483    int i;                          /* Used to iterate through p->aSample[] */
90484
90485    p->iGet = -1;
90486    p->mxSample = mxSample;
90487    p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
90488    p->current.anLt = &p->current.anEq[nColUp];
90489    p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
90490
90491    /* Set up the Stat4Accum.a[] and aBest[] arrays */
90492    p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
90493    p->aBest = &p->a[mxSample];
90494    pSpace = (u8*)(&p->a[mxSample+nCol]);
90495    for(i=0; i<(mxSample+nCol); i++){
90496      p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
90497      p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
90498      p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
90499    }
90500    assert( (pSpace - (u8*)p)==n );
90501
90502    for(i=0; i<nCol; i++){
90503      p->aBest[i].iCol = i;
90504    }
90505  }
90506#endif
90507
90508  /* Return a pointer to the allocated object to the caller.  Note that
90509  ** only the pointer (the 2nd parameter) matters.  The size of the object
90510  ** (given by the 3rd parameter) is never used and can be any positive
90511  ** value. */
90512  sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
90513}
90514static const FuncDef statInitFuncdef = {
90515  2+IsStat34,      /* nArg */
90516  SQLITE_UTF8,     /* funcFlags */
90517  0,               /* pUserData */
90518  0,               /* pNext */
90519  statInit,        /* xFunc */
90520  0,               /* xStep */
90521  0,               /* xFinalize */
90522  "stat_init",     /* zName */
90523  0,               /* pHash */
90524  0                /* pDestructor */
90525};
90526
90527#ifdef SQLITE_ENABLE_STAT4
90528/*
90529** pNew and pOld are both candidate non-periodic samples selected for
90530** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
90531** considering only any trailing columns and the sample hash value, this
90532** function returns true if sample pNew is to be preferred over pOld.
90533** In other words, if we assume that the cardinalities of the selected
90534** column for pNew and pOld are equal, is pNew to be preferred over pOld.
90535**
90536** This function assumes that for each argument sample, the contents of
90537** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
90538*/
90539static int sampleIsBetterPost(
90540  Stat4Accum *pAccum,
90541  Stat4Sample *pNew,
90542  Stat4Sample *pOld
90543){
90544  int nCol = pAccum->nCol;
90545  int i;
90546  assert( pNew->iCol==pOld->iCol );
90547  for(i=pNew->iCol+1; i<nCol; i++){
90548    if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
90549    if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
90550  }
90551  if( pNew->iHash>pOld->iHash ) return 1;
90552  return 0;
90553}
90554#endif
90555
90556#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90557/*
90558** Return true if pNew is to be preferred over pOld.
90559**
90560** This function assumes that for each argument sample, the contents of
90561** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
90562*/
90563static int sampleIsBetter(
90564  Stat4Accum *pAccum,
90565  Stat4Sample *pNew,
90566  Stat4Sample *pOld
90567){
90568  tRowcnt nEqNew = pNew->anEq[pNew->iCol];
90569  tRowcnt nEqOld = pOld->anEq[pOld->iCol];
90570
90571  assert( pOld->isPSample==0 && pNew->isPSample==0 );
90572  assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
90573
90574  if( (nEqNew>nEqOld) ) return 1;
90575#ifdef SQLITE_ENABLE_STAT4
90576  if( nEqNew==nEqOld ){
90577    if( pNew->iCol<pOld->iCol ) return 1;
90578    return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
90579  }
90580  return 0;
90581#else
90582  return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
90583#endif
90584}
90585
90586/*
90587** Copy the contents of sample *pNew into the p->a[] array. If necessary,
90588** remove the least desirable sample from p->a[] to make room.
90589*/
90590static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
90591  Stat4Sample *pSample = 0;
90592  int i;
90593
90594  assert( IsStat4 || nEqZero==0 );
90595
90596#ifdef SQLITE_ENABLE_STAT4
90597  if( pNew->isPSample==0 ){
90598    Stat4Sample *pUpgrade = 0;
90599    assert( pNew->anEq[pNew->iCol]>0 );
90600
90601    /* This sample is being added because the prefix that ends in column
90602    ** iCol occurs many times in the table. However, if we have already
90603    ** added a sample that shares this prefix, there is no need to add
90604    ** this one. Instead, upgrade the priority of the highest priority
90605    ** existing sample that shares this prefix.  */
90606    for(i=p->nSample-1; i>=0; i--){
90607      Stat4Sample *pOld = &p->a[i];
90608      if( pOld->anEq[pNew->iCol]==0 ){
90609        if( pOld->isPSample ) return;
90610        assert( pOld->iCol>pNew->iCol );
90611        assert( sampleIsBetter(p, pNew, pOld) );
90612        if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
90613          pUpgrade = pOld;
90614        }
90615      }
90616    }
90617    if( pUpgrade ){
90618      pUpgrade->iCol = pNew->iCol;
90619      pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
90620      goto find_new_min;
90621    }
90622  }
90623#endif
90624
90625  /* If necessary, remove sample iMin to make room for the new sample. */
90626  if( p->nSample>=p->mxSample ){
90627    Stat4Sample *pMin = &p->a[p->iMin];
90628    tRowcnt *anEq = pMin->anEq;
90629    tRowcnt *anLt = pMin->anLt;
90630    tRowcnt *anDLt = pMin->anDLt;
90631    sampleClear(p->db, pMin);
90632    memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
90633    pSample = &p->a[p->nSample-1];
90634    pSample->nRowid = 0;
90635    pSample->anEq = anEq;
90636    pSample->anDLt = anDLt;
90637    pSample->anLt = anLt;
90638    p->nSample = p->mxSample-1;
90639  }
90640
90641  /* The "rows less-than" for the rowid column must be greater than that
90642  ** for the last sample in the p->a[] array. Otherwise, the samples would
90643  ** be out of order. */
90644#ifdef SQLITE_ENABLE_STAT4
90645  assert( p->nSample==0
90646       || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
90647#endif
90648
90649  /* Insert the new sample */
90650  pSample = &p->a[p->nSample];
90651  sampleCopy(p, pSample, pNew);
90652  p->nSample++;
90653
90654  /* Zero the first nEqZero entries in the anEq[] array. */
90655  memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
90656
90657#ifdef SQLITE_ENABLE_STAT4
90658 find_new_min:
90659#endif
90660  if( p->nSample>=p->mxSample ){
90661    int iMin = -1;
90662    for(i=0; i<p->mxSample; i++){
90663      if( p->a[i].isPSample ) continue;
90664      if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
90665        iMin = i;
90666      }
90667    }
90668    assert( iMin>=0 );
90669    p->iMin = iMin;
90670  }
90671}
90672#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
90673
90674/*
90675** Field iChng of the index being scanned has changed. So at this point
90676** p->current contains a sample that reflects the previous row of the
90677** index. The value of anEq[iChng] and subsequent anEq[] elements are
90678** correct at this point.
90679*/
90680static void samplePushPrevious(Stat4Accum *p, int iChng){
90681#ifdef SQLITE_ENABLE_STAT4
90682  int i;
90683
90684  /* Check if any samples from the aBest[] array should be pushed
90685  ** into IndexSample.a[] at this point.  */
90686  for(i=(p->nCol-2); i>=iChng; i--){
90687    Stat4Sample *pBest = &p->aBest[i];
90688    pBest->anEq[i] = p->current.anEq[i];
90689    if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
90690      sampleInsert(p, pBest, i);
90691    }
90692  }
90693
90694  /* Update the anEq[] fields of any samples already collected. */
90695  for(i=p->nSample-1; i>=0; i--){
90696    int j;
90697    for(j=iChng; j<p->nCol; j++){
90698      if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
90699    }
90700  }
90701#endif
90702
90703#if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
90704  if( iChng==0 ){
90705    tRowcnt nLt = p->current.anLt[0];
90706    tRowcnt nEq = p->current.anEq[0];
90707
90708    /* Check if this is to be a periodic sample. If so, add it. */
90709    if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
90710      p->current.isPSample = 1;
90711      sampleInsert(p, &p->current, 0);
90712      p->current.isPSample = 0;
90713    }else
90714
90715    /* Or if it is a non-periodic sample. Add it in this case too. */
90716    if( p->nSample<p->mxSample
90717     || sampleIsBetter(p, &p->current, &p->a[p->iMin])
90718    ){
90719      sampleInsert(p, &p->current, 0);
90720    }
90721  }
90722#endif
90723
90724#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
90725  UNUSED_PARAMETER( p );
90726  UNUSED_PARAMETER( iChng );
90727#endif
90728}
90729
90730/*
90731** Implementation of the stat_push SQL function:  stat_push(P,C,R)
90732** Arguments:
90733**
90734**    P     Pointer to the Stat4Accum object created by stat_init()
90735**    C     Index of left-most column to differ from previous row
90736**    R     Rowid for the current row.  Might be a key record for
90737**          WITHOUT ROWID tables.
90738**
90739** This SQL function always returns NULL.  It's purpose it to accumulate
90740** statistical data and/or samples in the Stat4Accum object about the
90741** index being analyzed.  The stat_get() SQL function will later be used to
90742** extract relevant information for constructing the sqlite_statN tables.
90743**
90744** The R parameter is only used for STAT3 and STAT4
90745*/
90746static void statPush(
90747  sqlite3_context *context,
90748  int argc,
90749  sqlite3_value **argv
90750){
90751  int i;
90752
90753  /* The three function arguments */
90754  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
90755  int iChng = sqlite3_value_int(argv[1]);
90756
90757  UNUSED_PARAMETER( argc );
90758  UNUSED_PARAMETER( context );
90759  assert( p->nCol>0 );
90760  assert( iChng<p->nCol );
90761
90762  if( p->nRow==0 ){
90763    /* This is the first call to this function. Do initialization. */
90764    for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
90765  }else{
90766    /* Second and subsequent calls get processed here */
90767    samplePushPrevious(p, iChng);
90768
90769    /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
90770    ** to the current row of the index. */
90771    for(i=0; i<iChng; i++){
90772      p->current.anEq[i]++;
90773    }
90774    for(i=iChng; i<p->nCol; i++){
90775      p->current.anDLt[i]++;
90776#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90777      p->current.anLt[i] += p->current.anEq[i];
90778#endif
90779      p->current.anEq[i] = 1;
90780    }
90781  }
90782  p->nRow++;
90783#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90784  if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
90785    sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
90786  }else{
90787    sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
90788                                       sqlite3_value_blob(argv[2]));
90789  }
90790  p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
90791#endif
90792
90793#ifdef SQLITE_ENABLE_STAT4
90794  {
90795    tRowcnt nLt = p->current.anLt[p->nCol-1];
90796
90797    /* Check if this is to be a periodic sample. If so, add it. */
90798    if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
90799      p->current.isPSample = 1;
90800      p->current.iCol = 0;
90801      sampleInsert(p, &p->current, p->nCol-1);
90802      p->current.isPSample = 0;
90803    }
90804
90805    /* Update the aBest[] array. */
90806    for(i=0; i<(p->nCol-1); i++){
90807      p->current.iCol = i;
90808      if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
90809        sampleCopy(p, &p->aBest[i], &p->current);
90810      }
90811    }
90812  }
90813#endif
90814}
90815static const FuncDef statPushFuncdef = {
90816  2+IsStat34,      /* nArg */
90817  SQLITE_UTF8,     /* funcFlags */
90818  0,               /* pUserData */
90819  0,               /* pNext */
90820  statPush,        /* xFunc */
90821  0,               /* xStep */
90822  0,               /* xFinalize */
90823  "stat_push",     /* zName */
90824  0,               /* pHash */
90825  0                /* pDestructor */
90826};
90827
90828#define STAT_GET_STAT1 0          /* "stat" column of stat1 table */
90829#define STAT_GET_ROWID 1          /* "rowid" column of stat[34] entry */
90830#define STAT_GET_NEQ   2          /* "neq" column of stat[34] entry */
90831#define STAT_GET_NLT   3          /* "nlt" column of stat[34] entry */
90832#define STAT_GET_NDLT  4          /* "ndlt" column of stat[34] entry */
90833
90834/*
90835** Implementation of the stat_get(P,J) SQL function.  This routine is
90836** used to query statistical information that has been gathered into
90837** the Stat4Accum object by prior calls to stat_push().  The P parameter
90838** has type BLOB but it is really just a pointer to the Stat4Accum object.
90839** The content to returned is determined by the parameter J
90840** which is one of the STAT_GET_xxxx values defined above.
90841**
90842** If neither STAT3 nor STAT4 are enabled, then J is always
90843** STAT_GET_STAT1 and is hence omitted and this routine becomes
90844** a one-parameter function, stat_get(P), that always returns the
90845** stat1 table entry information.
90846*/
90847static void statGet(
90848  sqlite3_context *context,
90849  int argc,
90850  sqlite3_value **argv
90851){
90852  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
90853#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90854  /* STAT3 and STAT4 have a parameter on this routine. */
90855  int eCall = sqlite3_value_int(argv[1]);
90856  assert( argc==2 );
90857  assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
90858       || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
90859       || eCall==STAT_GET_NDLT
90860  );
90861  if( eCall==STAT_GET_STAT1 )
90862#else
90863  assert( argc==1 );
90864#endif
90865  {
90866    /* Return the value to store in the "stat" column of the sqlite_stat1
90867    ** table for this index.
90868    **
90869    ** The value is a string composed of a list of integers describing
90870    ** the index. The first integer in the list is the total number of
90871    ** entries in the index. There is one additional integer in the list
90872    ** for each indexed column. This additional integer is an estimate of
90873    ** the number of rows matched by a stabbing query on the index using
90874    ** a key with the corresponding number of fields. In other words,
90875    ** if the index is on columns (a,b) and the sqlite_stat1 value is
90876    ** "100 10 2", then SQLite estimates that:
90877    **
90878    **   * the index contains 100 rows,
90879    **   * "WHERE a=?" matches 10 rows, and
90880    **   * "WHERE a=? AND b=?" matches 2 rows.
90881    **
90882    ** If D is the count of distinct values and K is the total number of
90883    ** rows, then each estimate is computed as:
90884    **
90885    **        I = (K+D-1)/D
90886    */
90887    char *z;
90888    int i;
90889
90890    char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
90891    if( zRet==0 ){
90892      sqlite3_result_error_nomem(context);
90893      return;
90894    }
90895
90896    sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
90897    z = zRet + sqlite3Strlen30(zRet);
90898    for(i=0; i<p->nKeyCol; i++){
90899      u64 nDistinct = p->current.anDLt[i] + 1;
90900      u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
90901      sqlite3_snprintf(24, z, " %llu", iVal);
90902      z += sqlite3Strlen30(z);
90903      assert( p->current.anEq[i] );
90904    }
90905    assert( z[0]=='\0' && z>zRet );
90906
90907    sqlite3_result_text(context, zRet, -1, sqlite3_free);
90908  }
90909#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90910  else if( eCall==STAT_GET_ROWID ){
90911    if( p->iGet<0 ){
90912      samplePushPrevious(p, 0);
90913      p->iGet = 0;
90914    }
90915    if( p->iGet<p->nSample ){
90916      Stat4Sample *pS = p->a + p->iGet;
90917      if( pS->nRowid==0 ){
90918        sqlite3_result_int64(context, pS->u.iRowid);
90919      }else{
90920        sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
90921                            SQLITE_TRANSIENT);
90922      }
90923    }
90924  }else{
90925    tRowcnt *aCnt = 0;
90926
90927    assert( p->iGet<p->nSample );
90928    switch( eCall ){
90929      case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;
90930      case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;
90931      default: {
90932        aCnt = p->a[p->iGet].anDLt;
90933        p->iGet++;
90934        break;
90935      }
90936    }
90937
90938    if( IsStat3 ){
90939      sqlite3_result_int64(context, (i64)aCnt[0]);
90940    }else{
90941      char *zRet = sqlite3MallocZero(p->nCol * 25);
90942      if( zRet==0 ){
90943        sqlite3_result_error_nomem(context);
90944      }else{
90945        int i;
90946        char *z = zRet;
90947        for(i=0; i<p->nCol; i++){
90948          sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
90949          z += sqlite3Strlen30(z);
90950        }
90951        assert( z[0]=='\0' && z>zRet );
90952        z[-1] = '\0';
90953        sqlite3_result_text(context, zRet, -1, sqlite3_free);
90954      }
90955    }
90956  }
90957#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
90958#ifndef SQLITE_DEBUG
90959  UNUSED_PARAMETER( argc );
90960#endif
90961}
90962static const FuncDef statGetFuncdef = {
90963  1+IsStat34,      /* nArg */
90964  SQLITE_UTF8,     /* funcFlags */
90965  0,               /* pUserData */
90966  0,               /* pNext */
90967  statGet,         /* xFunc */
90968  0,               /* xStep */
90969  0,               /* xFinalize */
90970  "stat_get",      /* zName */
90971  0,               /* pHash */
90972  0                /* pDestructor */
90973};
90974
90975static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
90976  assert( regOut!=regStat4 && regOut!=regStat4+1 );
90977#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90978  sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
90979#elif SQLITE_DEBUG
90980  assert( iParam==STAT_GET_STAT1 );
90981#else
90982  UNUSED_PARAMETER( iParam );
90983#endif
90984  sqlite3VdbeAddOp3(v, OP_Function0, 0, regStat4, regOut);
90985  sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
90986  sqlite3VdbeChangeP5(v, 1 + IsStat34);
90987}
90988
90989/*
90990** Generate code to do an analysis of all indices associated with
90991** a single table.
90992*/
90993static void analyzeOneTable(
90994  Parse *pParse,   /* Parser context */
90995  Table *pTab,     /* Table whose indices are to be analyzed */
90996  Index *pOnlyIdx, /* If not NULL, only analyze this one index */
90997  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
90998  int iMem,        /* Available memory locations begin here */
90999  int iTab         /* Next available cursor */
91000){
91001  sqlite3 *db = pParse->db;    /* Database handle */
91002  Index *pIdx;                 /* An index to being analyzed */
91003  int iIdxCur;                 /* Cursor open on index being analyzed */
91004  int iTabCur;                 /* Table cursor */
91005  Vdbe *v;                     /* The virtual machine being built up */
91006  int i;                       /* Loop counter */
91007  int jZeroRows = -1;          /* Jump from here if number of rows is zero */
91008  int iDb;                     /* Index of database containing pTab */
91009  u8 needTableCnt = 1;         /* True to count the table */
91010  int regNewRowid = iMem++;    /* Rowid for the inserted record */
91011  int regStat4 = iMem++;       /* Register to hold Stat4Accum object */
91012  int regChng = iMem++;        /* Index of changed index field */
91013#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91014  int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
91015#endif
91016  int regTemp = iMem++;        /* Temporary use register */
91017  int regTabname = iMem++;     /* Register containing table name */
91018  int regIdxname = iMem++;     /* Register containing index name */
91019  int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
91020  int regPrev = iMem;          /* MUST BE LAST (see below) */
91021
91022  pParse->nMem = MAX(pParse->nMem, iMem);
91023  v = sqlite3GetVdbe(pParse);
91024  if( v==0 || NEVER(pTab==0) ){
91025    return;
91026  }
91027  if( pTab->tnum==0 ){
91028    /* Do not gather statistics on views or virtual tables */
91029    return;
91030  }
91031  if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
91032    /* Do not gather statistics on system tables */
91033    return;
91034  }
91035  assert( sqlite3BtreeHoldsAllMutexes(db) );
91036  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
91037  assert( iDb>=0 );
91038  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91039#ifndef SQLITE_OMIT_AUTHORIZATION
91040  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
91041      db->aDb[iDb].zName ) ){
91042    return;
91043  }
91044#endif
91045
91046  /* Establish a read-lock on the table at the shared-cache level.
91047  ** Open a read-only cursor on the table. Also allocate a cursor number
91048  ** to use for scanning indexes (iIdxCur). No index cursor is opened at
91049  ** this time though.  */
91050  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
91051  iTabCur = iTab++;
91052  iIdxCur = iTab++;
91053  pParse->nTab = MAX(pParse->nTab, iTab);
91054  sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
91055  sqlite3VdbeLoadString(v, regTabname, pTab->zName);
91056
91057  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
91058    int nCol;                     /* Number of columns in pIdx. "N" */
91059    int addrRewind;               /* Address of "OP_Rewind iIdxCur" */
91060    int addrNextRow;              /* Address of "next_row:" */
91061    const char *zIdxName;         /* Name of the index */
91062    int nColTest;                 /* Number of columns to test for changes */
91063
91064    if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
91065    if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
91066    if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
91067      nCol = pIdx->nKeyCol;
91068      zIdxName = pTab->zName;
91069      nColTest = nCol - 1;
91070    }else{
91071      nCol = pIdx->nColumn;
91072      zIdxName = pIdx->zName;
91073      nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
91074    }
91075
91076    /* Populate the register containing the index name. */
91077    sqlite3VdbeLoadString(v, regIdxname, zIdxName);
91078    VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
91079
91080    /*
91081    ** Pseudo-code for loop that calls stat_push():
91082    **
91083    **   Rewind csr
91084    **   if eof(csr) goto end_of_scan;
91085    **   regChng = 0
91086    **   goto chng_addr_0;
91087    **
91088    **  next_row:
91089    **   regChng = 0
91090    **   if( idx(0) != regPrev(0) ) goto chng_addr_0
91091    **   regChng = 1
91092    **   if( idx(1) != regPrev(1) ) goto chng_addr_1
91093    **   ...
91094    **   regChng = N
91095    **   goto chng_addr_N
91096    **
91097    **  chng_addr_0:
91098    **   regPrev(0) = idx(0)
91099    **  chng_addr_1:
91100    **   regPrev(1) = idx(1)
91101    **  ...
91102    **
91103    **  endDistinctTest:
91104    **   regRowid = idx(rowid)
91105    **   stat_push(P, regChng, regRowid)
91106    **   Next csr
91107    **   if !eof(csr) goto next_row;
91108    **
91109    **  end_of_scan:
91110    */
91111
91112    /* Make sure there are enough memory cells allocated to accommodate
91113    ** the regPrev array and a trailing rowid (the rowid slot is required
91114    ** when building a record to insert into the sample column of
91115    ** the sqlite_stat4 table.  */
91116    pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
91117
91118    /* Open a read-only cursor on the index being analyzed. */
91119    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
91120    sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
91121    sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
91122    VdbeComment((v, "%s", pIdx->zName));
91123
91124    /* Invoke the stat_init() function. The arguments are:
91125    **
91126    **    (1) the number of columns in the index including the rowid
91127    **        (or for a WITHOUT ROWID table, the number of PK columns),
91128    **    (2) the number of columns in the key without the rowid/pk
91129    **    (3) the number of rows in the index,
91130    **
91131    **
91132    ** The third argument is only used for STAT3 and STAT4
91133    */
91134#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91135    sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
91136#endif
91137    sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
91138    sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
91139    sqlite3VdbeAddOp3(v, OP_Function0, 0, regStat4+1, regStat4);
91140    sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
91141    sqlite3VdbeChangeP5(v, 2+IsStat34);
91142
91143    /* Implementation of the following:
91144    **
91145    **   Rewind csr
91146    **   if eof(csr) goto end_of_scan;
91147    **   regChng = 0
91148    **   goto next_push_0;
91149    **
91150    */
91151    addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
91152    VdbeCoverage(v);
91153    sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
91154    addrNextRow = sqlite3VdbeCurrentAddr(v);
91155
91156    if( nColTest>0 ){
91157      int endDistinctTest = sqlite3VdbeMakeLabel(v);
91158      int *aGotoChng;               /* Array of jump instruction addresses */
91159      aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*nColTest);
91160      if( aGotoChng==0 ) continue;
91161
91162      /*
91163      **  next_row:
91164      **   regChng = 0
91165      **   if( idx(0) != regPrev(0) ) goto chng_addr_0
91166      **   regChng = 1
91167      **   if( idx(1) != regPrev(1) ) goto chng_addr_1
91168      **   ...
91169      **   regChng = N
91170      **   goto endDistinctTest
91171      */
91172      sqlite3VdbeAddOp0(v, OP_Goto);
91173      addrNextRow = sqlite3VdbeCurrentAddr(v);
91174      if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
91175        /* For a single-column UNIQUE index, once we have found a non-NULL
91176        ** row, we know that all the rest will be distinct, so skip
91177        ** subsequent distinctness tests. */
91178        sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
91179        VdbeCoverage(v);
91180      }
91181      for(i=0; i<nColTest; i++){
91182        char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
91183        sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
91184        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
91185        aGotoChng[i] =
91186        sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
91187        sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
91188        VdbeCoverage(v);
91189      }
91190      sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
91191      sqlite3VdbeGoto(v, endDistinctTest);
91192
91193
91194      /*
91195      **  chng_addr_0:
91196      **   regPrev(0) = idx(0)
91197      **  chng_addr_1:
91198      **   regPrev(1) = idx(1)
91199      **  ...
91200      */
91201      sqlite3VdbeJumpHere(v, addrNextRow-1);
91202      for(i=0; i<nColTest; i++){
91203        sqlite3VdbeJumpHere(v, aGotoChng[i]);
91204        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
91205      }
91206      sqlite3VdbeResolveLabel(v, endDistinctTest);
91207      sqlite3DbFree(db, aGotoChng);
91208    }
91209
91210    /*
91211    **  chng_addr_N:
91212    **   regRowid = idx(rowid)            // STAT34 only
91213    **   stat_push(P, regChng, regRowid)  // 3rd parameter STAT34 only
91214    **   Next csr
91215    **   if !eof(csr) goto next_row;
91216    */
91217#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91218    assert( regRowid==(regStat4+2) );
91219    if( HasRowid(pTab) ){
91220      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
91221    }else{
91222      Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
91223      int j, k, regKey;
91224      regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
91225      for(j=0; j<pPk->nKeyCol; j++){
91226        k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
91227        assert( k>=0 && k<pTab->nCol );
91228        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
91229        VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
91230      }
91231      sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
91232      sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
91233    }
91234#endif
91235    assert( regChng==(regStat4+1) );
91236    sqlite3VdbeAddOp3(v, OP_Function0, 1, regStat4, regTemp);
91237    sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
91238    sqlite3VdbeChangeP5(v, 2+IsStat34);
91239    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
91240
91241    /* Add the entry to the stat1 table. */
91242    callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
91243    assert( "BBB"[0]==SQLITE_AFF_TEXT );
91244    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
91245    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
91246    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
91247    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
91248
91249    /* Add the entries to the stat3 or stat4 table. */
91250#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91251    {
91252      int regEq = regStat1;
91253      int regLt = regStat1+1;
91254      int regDLt = regStat1+2;
91255      int regSample = regStat1+3;
91256      int regCol = regStat1+4;
91257      int regSampleRowid = regCol + nCol;
91258      int addrNext;
91259      int addrIsNull;
91260      u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
91261
91262      pParse->nMem = MAX(pParse->nMem, regCol+nCol);
91263
91264      addrNext = sqlite3VdbeCurrentAddr(v);
91265      callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
91266      addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
91267      VdbeCoverage(v);
91268      callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
91269      callStatGet(v, regStat4, STAT_GET_NLT, regLt);
91270      callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
91271      sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
91272      /* We know that the regSampleRowid row exists because it was read by
91273      ** the previous loop.  Thus the not-found jump of seekOp will never
91274      ** be taken */
91275      VdbeCoverageNeverTaken(v);
91276#ifdef SQLITE_ENABLE_STAT3
91277      sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
91278#else
91279      for(i=0; i<nCol; i++){
91280        sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
91281      }
91282      sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
91283#endif
91284      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
91285      sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
91286      sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
91287      sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
91288      sqlite3VdbeJumpHere(v, addrIsNull);
91289    }
91290#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
91291
91292    /* End of analysis */
91293    sqlite3VdbeJumpHere(v, addrRewind);
91294  }
91295
91296
91297  /* Create a single sqlite_stat1 entry containing NULL as the index
91298  ** name and the row count as the content.
91299  */
91300  if( pOnlyIdx==0 && needTableCnt ){
91301    VdbeComment((v, "%s", pTab->zName));
91302    sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
91303    jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
91304    sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
91305    assert( "BBB"[0]==SQLITE_AFF_TEXT );
91306    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
91307    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
91308    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
91309    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
91310    sqlite3VdbeJumpHere(v, jZeroRows);
91311  }
91312}
91313
91314
91315/*
91316** Generate code that will cause the most recent index analysis to
91317** be loaded into internal hash tables where is can be used.
91318*/
91319static void loadAnalysis(Parse *pParse, int iDb){
91320  Vdbe *v = sqlite3GetVdbe(pParse);
91321  if( v ){
91322    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
91323  }
91324}
91325
91326/*
91327** Generate code that will do an analysis of an entire database
91328*/
91329static void analyzeDatabase(Parse *pParse, int iDb){
91330  sqlite3 *db = pParse->db;
91331  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
91332  HashElem *k;
91333  int iStatCur;
91334  int iMem;
91335  int iTab;
91336
91337  sqlite3BeginWriteOperation(pParse, 0, iDb);
91338  iStatCur = pParse->nTab;
91339  pParse->nTab += 3;
91340  openStatTable(pParse, iDb, iStatCur, 0, 0);
91341  iMem = pParse->nMem+1;
91342  iTab = pParse->nTab;
91343  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91344  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
91345    Table *pTab = (Table*)sqliteHashData(k);
91346    analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
91347  }
91348  loadAnalysis(pParse, iDb);
91349}
91350
91351/*
91352** Generate code that will do an analysis of a single table in
91353** a database.  If pOnlyIdx is not NULL then it is a single index
91354** in pTab that should be analyzed.
91355*/
91356static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
91357  int iDb;
91358  int iStatCur;
91359
91360  assert( pTab!=0 );
91361  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
91362  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
91363  sqlite3BeginWriteOperation(pParse, 0, iDb);
91364  iStatCur = pParse->nTab;
91365  pParse->nTab += 3;
91366  if( pOnlyIdx ){
91367    openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
91368  }else{
91369    openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
91370  }
91371  analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
91372  loadAnalysis(pParse, iDb);
91373}
91374
91375/*
91376** Generate code for the ANALYZE command.  The parser calls this routine
91377** when it recognizes an ANALYZE command.
91378**
91379**        ANALYZE                            -- 1
91380**        ANALYZE  <database>                -- 2
91381**        ANALYZE  ?<database>.?<tablename>  -- 3
91382**
91383** Form 1 causes all indices in all attached databases to be analyzed.
91384** Form 2 analyzes all indices the single database named.
91385** Form 3 analyzes all indices associated with the named table.
91386*/
91387SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
91388  sqlite3 *db = pParse->db;
91389  int iDb;
91390  int i;
91391  char *z, *zDb;
91392  Table *pTab;
91393  Index *pIdx;
91394  Token *pTableName;
91395  Vdbe *v;
91396
91397  /* Read the database schema. If an error occurs, leave an error message
91398  ** and code in pParse and return NULL. */
91399  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
91400  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
91401    return;
91402  }
91403
91404  assert( pName2!=0 || pName1==0 );
91405  if( pName1==0 ){
91406    /* Form 1:  Analyze everything */
91407    for(i=0; i<db->nDb; i++){
91408      if( i==1 ) continue;  /* Do not analyze the TEMP database */
91409      analyzeDatabase(pParse, i);
91410    }
91411  }else if( pName2->n==0 ){
91412    /* Form 2:  Analyze the database or table named */
91413    iDb = sqlite3FindDb(db, pName1);
91414    if( iDb>=0 ){
91415      analyzeDatabase(pParse, iDb);
91416    }else{
91417      z = sqlite3NameFromToken(db, pName1);
91418      if( z ){
91419        if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
91420          analyzeTable(pParse, pIdx->pTable, pIdx);
91421        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
91422          analyzeTable(pParse, pTab, 0);
91423        }
91424        sqlite3DbFree(db, z);
91425      }
91426    }
91427  }else{
91428    /* Form 3: Analyze the fully qualified table name */
91429    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
91430    if( iDb>=0 ){
91431      zDb = db->aDb[iDb].zName;
91432      z = sqlite3NameFromToken(db, pTableName);
91433      if( z ){
91434        if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
91435          analyzeTable(pParse, pIdx->pTable, pIdx);
91436        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
91437          analyzeTable(pParse, pTab, 0);
91438        }
91439        sqlite3DbFree(db, z);
91440      }
91441    }
91442  }
91443  v = sqlite3GetVdbe(pParse);
91444  if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
91445}
91446
91447/*
91448** Used to pass information from the analyzer reader through to the
91449** callback routine.
91450*/
91451typedef struct analysisInfo analysisInfo;
91452struct analysisInfo {
91453  sqlite3 *db;
91454  const char *zDatabase;
91455};
91456
91457/*
91458** The first argument points to a nul-terminated string containing a
91459** list of space separated integers. Read the first nOut of these into
91460** the array aOut[].
91461*/
91462static void decodeIntArray(
91463  char *zIntArray,       /* String containing int array to decode */
91464  int nOut,              /* Number of slots in aOut[] */
91465  tRowcnt *aOut,         /* Store integers here */
91466  LogEst *aLog,          /* Or, if aOut==0, here */
91467  Index *pIndex          /* Handle extra flags for this index, if not NULL */
91468){
91469  char *z = zIntArray;
91470  int c;
91471  int i;
91472  tRowcnt v;
91473
91474#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91475  if( z==0 ) z = "";
91476#else
91477  assert( z!=0 );
91478#endif
91479  for(i=0; *z && i<nOut; i++){
91480    v = 0;
91481    while( (c=z[0])>='0' && c<='9' ){
91482      v = v*10 + c - '0';
91483      z++;
91484    }
91485#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91486    if( aOut ) aOut[i] = v;
91487    if( aLog ) aLog[i] = sqlite3LogEst(v);
91488#else
91489    assert( aOut==0 );
91490    UNUSED_PARAMETER(aOut);
91491    assert( aLog!=0 );
91492    aLog[i] = sqlite3LogEst(v);
91493#endif
91494    if( *z==' ' ) z++;
91495  }
91496#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
91497  assert( pIndex!=0 ); {
91498#else
91499  if( pIndex ){
91500#endif
91501    pIndex->bUnordered = 0;
91502    pIndex->noSkipScan = 0;
91503    while( z[0] ){
91504      if( sqlite3_strglob("unordered*", z)==0 ){
91505        pIndex->bUnordered = 1;
91506      }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
91507        pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
91508      }else if( sqlite3_strglob("noskipscan*", z)==0 ){
91509        pIndex->noSkipScan = 1;
91510      }
91511#ifdef SQLITE_ENABLE_COSTMULT
91512      else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
91513        pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
91514      }
91515#endif
91516      while( z[0]!=0 && z[0]!=' ' ) z++;
91517      while( z[0]==' ' ) z++;
91518    }
91519  }
91520}
91521
91522/*
91523** This callback is invoked once for each index when reading the
91524** sqlite_stat1 table.
91525**
91526**     argv[0] = name of the table
91527**     argv[1] = name of the index (might be NULL)
91528**     argv[2] = results of analysis - on integer for each column
91529**
91530** Entries for which argv[1]==NULL simply record the number of rows in
91531** the table.
91532*/
91533static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
91534  analysisInfo *pInfo = (analysisInfo*)pData;
91535  Index *pIndex;
91536  Table *pTable;
91537  const char *z;
91538
91539  assert( argc==3 );
91540  UNUSED_PARAMETER2(NotUsed, argc);
91541
91542  if( argv==0 || argv[0]==0 || argv[2]==0 ){
91543    return 0;
91544  }
91545  pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
91546  if( pTable==0 ){
91547    return 0;
91548  }
91549  if( argv[1]==0 ){
91550    pIndex = 0;
91551  }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
91552    pIndex = sqlite3PrimaryKeyIndex(pTable);
91553  }else{
91554    pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
91555  }
91556  z = argv[2];
91557
91558  if( pIndex ){
91559    tRowcnt *aiRowEst = 0;
91560    int nCol = pIndex->nKeyCol+1;
91561#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91562    /* Index.aiRowEst may already be set here if there are duplicate
91563    ** sqlite_stat1 entries for this index. In that case just clobber
91564    ** the old data with the new instead of allocating a new array.  */
91565    if( pIndex->aiRowEst==0 ){
91566      pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
91567      if( pIndex->aiRowEst==0 ) pInfo->db->mallocFailed = 1;
91568    }
91569    aiRowEst = pIndex->aiRowEst;
91570#endif
91571    pIndex->bUnordered = 0;
91572    decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
91573    if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
91574  }else{
91575    Index fakeIdx;
91576    fakeIdx.szIdxRow = pTable->szTabRow;
91577#ifdef SQLITE_ENABLE_COSTMULT
91578    fakeIdx.pTable = pTable;
91579#endif
91580    decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
91581    pTable->szTabRow = fakeIdx.szIdxRow;
91582  }
91583
91584  return 0;
91585}
91586
91587/*
91588** If the Index.aSample variable is not NULL, delete the aSample[] array
91589** and its contents.
91590*/
91591SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
91592#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91593  if( pIdx->aSample ){
91594    int j;
91595    for(j=0; j<pIdx->nSample; j++){
91596      IndexSample *p = &pIdx->aSample[j];
91597      sqlite3DbFree(db, p->p);
91598    }
91599    sqlite3DbFree(db, pIdx->aSample);
91600  }
91601  if( db && db->pnBytesFreed==0 ){
91602    pIdx->nSample = 0;
91603    pIdx->aSample = 0;
91604  }
91605#else
91606  UNUSED_PARAMETER(db);
91607  UNUSED_PARAMETER(pIdx);
91608#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
91609}
91610
91611#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91612/*
91613** Populate the pIdx->aAvgEq[] array based on the samples currently
91614** stored in pIdx->aSample[].
91615*/
91616static void initAvgEq(Index *pIdx){
91617  if( pIdx ){
91618    IndexSample *aSample = pIdx->aSample;
91619    IndexSample *pFinal = &aSample[pIdx->nSample-1];
91620    int iCol;
91621    int nCol = 1;
91622    if( pIdx->nSampleCol>1 ){
91623      /* If this is stat4 data, then calculate aAvgEq[] values for all
91624      ** sample columns except the last. The last is always set to 1, as
91625      ** once the trailing PK fields are considered all index keys are
91626      ** unique.  */
91627      nCol = pIdx->nSampleCol-1;
91628      pIdx->aAvgEq[nCol] = 1;
91629    }
91630    for(iCol=0; iCol<nCol; iCol++){
91631      int nSample = pIdx->nSample;
91632      int i;                    /* Used to iterate through samples */
91633      tRowcnt sumEq = 0;        /* Sum of the nEq values */
91634      tRowcnt avgEq = 0;
91635      tRowcnt nRow;             /* Number of rows in index */
91636      i64 nSum100 = 0;          /* Number of terms contributing to sumEq */
91637      i64 nDist100;             /* Number of distinct values in index */
91638
91639      if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
91640        nRow = pFinal->anLt[iCol];
91641        nDist100 = (i64)100 * pFinal->anDLt[iCol];
91642        nSample--;
91643      }else{
91644        nRow = pIdx->aiRowEst[0];
91645        nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
91646      }
91647      pIdx->nRowEst0 = nRow;
91648
91649      /* Set nSum to the number of distinct (iCol+1) field prefixes that
91650      ** occur in the stat4 table for this index. Set sumEq to the sum of
91651      ** the nEq values for column iCol for the same set (adding the value
91652      ** only once where there exist duplicate prefixes).  */
91653      for(i=0; i<nSample; i++){
91654        if( i==(pIdx->nSample-1)
91655         || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
91656        ){
91657          sumEq += aSample[i].anEq[iCol];
91658          nSum100 += 100;
91659        }
91660      }
91661
91662      if( nDist100>nSum100 ){
91663        avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
91664      }
91665      if( avgEq==0 ) avgEq = 1;
91666      pIdx->aAvgEq[iCol] = avgEq;
91667    }
91668  }
91669}
91670
91671/*
91672** Look up an index by name.  Or, if the name of a WITHOUT ROWID table
91673** is supplied instead, find the PRIMARY KEY index for that table.
91674*/
91675static Index *findIndexOrPrimaryKey(
91676  sqlite3 *db,
91677  const char *zName,
91678  const char *zDb
91679){
91680  Index *pIdx = sqlite3FindIndex(db, zName, zDb);
91681  if( pIdx==0 ){
91682    Table *pTab = sqlite3FindTable(db, zName, zDb);
91683    if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
91684  }
91685  return pIdx;
91686}
91687
91688/*
91689** Load the content from either the sqlite_stat4 or sqlite_stat3 table
91690** into the relevant Index.aSample[] arrays.
91691**
91692** Arguments zSql1 and zSql2 must point to SQL statements that return
91693** data equivalent to the following (statements are different for stat3,
91694** see the caller of this function for details):
91695**
91696**    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
91697**    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
91698**
91699** where %Q is replaced with the database name before the SQL is executed.
91700*/
91701static int loadStatTbl(
91702  sqlite3 *db,                  /* Database handle */
91703  int bStat3,                   /* Assume single column records only */
91704  const char *zSql1,            /* SQL statement 1 (see above) */
91705  const char *zSql2,            /* SQL statement 2 (see above) */
91706  const char *zDb               /* Database name (e.g. "main") */
91707){
91708  int rc;                       /* Result codes from subroutines */
91709  sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
91710  char *zSql;                   /* Text of the SQL statement */
91711  Index *pPrevIdx = 0;          /* Previous index in the loop */
91712  IndexSample *pSample;         /* A slot in pIdx->aSample[] */
91713
91714  assert( db->lookaside.bEnabled==0 );
91715  zSql = sqlite3MPrintf(db, zSql1, zDb);
91716  if( !zSql ){
91717    return SQLITE_NOMEM;
91718  }
91719  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
91720  sqlite3DbFree(db, zSql);
91721  if( rc ) return rc;
91722
91723  while( sqlite3_step(pStmt)==SQLITE_ROW ){
91724    int nIdxCol = 1;              /* Number of columns in stat4 records */
91725
91726    char *zIndex;   /* Index name */
91727    Index *pIdx;    /* Pointer to the index object */
91728    int nSample;    /* Number of samples */
91729    int nByte;      /* Bytes of space required */
91730    int i;          /* Bytes of space required */
91731    tRowcnt *pSpace;
91732
91733    zIndex = (char *)sqlite3_column_text(pStmt, 0);
91734    if( zIndex==0 ) continue;
91735    nSample = sqlite3_column_int(pStmt, 1);
91736    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
91737    assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
91738    /* Index.nSample is non-zero at this point if data has already been
91739    ** loaded from the stat4 table. In this case ignore stat3 data.  */
91740    if( pIdx==0 || pIdx->nSample ) continue;
91741    if( bStat3==0 ){
91742      assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
91743      if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
91744        nIdxCol = pIdx->nKeyCol;
91745      }else{
91746        nIdxCol = pIdx->nColumn;
91747      }
91748    }
91749    pIdx->nSampleCol = nIdxCol;
91750    nByte = sizeof(IndexSample) * nSample;
91751    nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
91752    nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */
91753
91754    pIdx->aSample = sqlite3DbMallocZero(db, nByte);
91755    if( pIdx->aSample==0 ){
91756      sqlite3_finalize(pStmt);
91757      return SQLITE_NOMEM;
91758    }
91759    pSpace = (tRowcnt*)&pIdx->aSample[nSample];
91760    pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
91761    for(i=0; i<nSample; i++){
91762      pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
91763      pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
91764      pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
91765    }
91766    assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
91767  }
91768  rc = sqlite3_finalize(pStmt);
91769  if( rc ) return rc;
91770
91771  zSql = sqlite3MPrintf(db, zSql2, zDb);
91772  if( !zSql ){
91773    return SQLITE_NOMEM;
91774  }
91775  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
91776  sqlite3DbFree(db, zSql);
91777  if( rc ) return rc;
91778
91779  while( sqlite3_step(pStmt)==SQLITE_ROW ){
91780    char *zIndex;                 /* Index name */
91781    Index *pIdx;                  /* Pointer to the index object */
91782    int nCol = 1;                 /* Number of columns in index */
91783
91784    zIndex = (char *)sqlite3_column_text(pStmt, 0);
91785    if( zIndex==0 ) continue;
91786    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
91787    if( pIdx==0 ) continue;
91788    /* This next condition is true if data has already been loaded from
91789    ** the sqlite_stat4 table. In this case ignore stat3 data.  */
91790    nCol = pIdx->nSampleCol;
91791    if( bStat3 && nCol>1 ) continue;
91792    if( pIdx!=pPrevIdx ){
91793      initAvgEq(pPrevIdx);
91794      pPrevIdx = pIdx;
91795    }
91796    pSample = &pIdx->aSample[pIdx->nSample];
91797    decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
91798    decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
91799    decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
91800
91801    /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
91802    ** This is in case the sample record is corrupted. In that case, the
91803    ** sqlite3VdbeRecordCompare() may read up to two varints past the
91804    ** end of the allocated buffer before it realizes it is dealing with
91805    ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
91806    ** a buffer overread.  */
91807    pSample->n = sqlite3_column_bytes(pStmt, 4);
91808    pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
91809    if( pSample->p==0 ){
91810      sqlite3_finalize(pStmt);
91811      return SQLITE_NOMEM;
91812    }
91813    memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
91814    pIdx->nSample++;
91815  }
91816  rc = sqlite3_finalize(pStmt);
91817  if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
91818  return rc;
91819}
91820
91821/*
91822** Load content from the sqlite_stat4 and sqlite_stat3 tables into
91823** the Index.aSample[] arrays of all indices.
91824*/
91825static int loadStat4(sqlite3 *db, const char *zDb){
91826  int rc = SQLITE_OK;             /* Result codes from subroutines */
91827
91828  assert( db->lookaside.bEnabled==0 );
91829  if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
91830    rc = loadStatTbl(db, 0,
91831      "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
91832      "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
91833      zDb
91834    );
91835  }
91836
91837  if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
91838    rc = loadStatTbl(db, 1,
91839      "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
91840      "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
91841      zDb
91842    );
91843  }
91844
91845  return rc;
91846}
91847#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
91848
91849/*
91850** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
91851** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
91852** arrays. The contents of sqlite_stat3/4 are used to populate the
91853** Index.aSample[] arrays.
91854**
91855** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
91856** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
91857** during compilation and the sqlite_stat3/4 table is present, no data is
91858** read from it.
91859**
91860** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
91861** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
91862** returned. However, in this case, data is read from the sqlite_stat1
91863** table (if it is present) before returning.
91864**
91865** If an OOM error occurs, this function always sets db->mallocFailed.
91866** This means if the caller does not care about other errors, the return
91867** code may be ignored.
91868*/
91869SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
91870  analysisInfo sInfo;
91871  HashElem *i;
91872  char *zSql;
91873  int rc;
91874
91875  assert( iDb>=0 && iDb<db->nDb );
91876  assert( db->aDb[iDb].pBt!=0 );
91877
91878  /* Clear any prior statistics */
91879  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91880  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
91881    Index *pIdx = sqliteHashData(i);
91882    sqlite3DefaultRowEst(pIdx);
91883#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91884    sqlite3DeleteIndexSamples(db, pIdx);
91885    pIdx->aSample = 0;
91886#endif
91887  }
91888
91889  /* Check to make sure the sqlite_stat1 table exists */
91890  sInfo.db = db;
91891  sInfo.zDatabase = db->aDb[iDb].zName;
91892  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
91893    return SQLITE_ERROR;
91894  }
91895
91896  /* Load new statistics out of the sqlite_stat1 table */
91897  zSql = sqlite3MPrintf(db,
91898      "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
91899  if( zSql==0 ){
91900    rc = SQLITE_NOMEM;
91901  }else{
91902    rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
91903    sqlite3DbFree(db, zSql);
91904  }
91905
91906
91907  /* Load the statistics from the sqlite_stat4 table. */
91908#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91909  if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
91910    int lookasideEnabled = db->lookaside.bEnabled;
91911    db->lookaside.bEnabled = 0;
91912    rc = loadStat4(db, sInfo.zDatabase);
91913    db->lookaside.bEnabled = lookasideEnabled;
91914  }
91915  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
91916    Index *pIdx = sqliteHashData(i);
91917    sqlite3_free(pIdx->aiRowEst);
91918    pIdx->aiRowEst = 0;
91919  }
91920#endif
91921
91922  if( rc==SQLITE_NOMEM ){
91923    db->mallocFailed = 1;
91924  }
91925  return rc;
91926}
91927
91928
91929#endif /* SQLITE_OMIT_ANALYZE */
91930
91931/************** End of analyze.c *********************************************/
91932/************** Begin file attach.c ******************************************/
91933/*
91934** 2003 April 6
91935**
91936** The author disclaims copyright to this source code.  In place of
91937** a legal notice, here is a blessing:
91938**
91939**    May you do good and not evil.
91940**    May you find forgiveness for yourself and forgive others.
91941**    May you share freely, never taking more than you give.
91942**
91943*************************************************************************
91944** This file contains code used to implement the ATTACH and DETACH commands.
91945*/
91946/* #include "sqliteInt.h" */
91947
91948#ifndef SQLITE_OMIT_ATTACH
91949/*
91950** Resolve an expression that was part of an ATTACH or DETACH statement. This
91951** is slightly different from resolving a normal SQL expression, because simple
91952** identifiers are treated as strings, not possible column names or aliases.
91953**
91954** i.e. if the parser sees:
91955**
91956**     ATTACH DATABASE abc AS def
91957**
91958** it treats the two expressions as literal strings 'abc' and 'def' instead of
91959** looking for columns of the same name.
91960**
91961** This only applies to the root node of pExpr, so the statement:
91962**
91963**     ATTACH DATABASE abc||def AS 'db2'
91964**
91965** will fail because neither abc or def can be resolved.
91966*/
91967static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
91968{
91969  int rc = SQLITE_OK;
91970  if( pExpr ){
91971    if( pExpr->op!=TK_ID ){
91972      rc = sqlite3ResolveExprNames(pName, pExpr);
91973    }else{
91974      pExpr->op = TK_STRING;
91975    }
91976  }
91977  return rc;
91978}
91979
91980/*
91981** An SQL user-function registered to do the work of an ATTACH statement. The
91982** three arguments to the function come directly from an attach statement:
91983**
91984**     ATTACH DATABASE x AS y KEY z
91985**
91986**     SELECT sqlite_attach(x, y, z)
91987**
91988** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
91989** third argument.
91990*/
91991static void attachFunc(
91992  sqlite3_context *context,
91993  int NotUsed,
91994  sqlite3_value **argv
91995){
91996  int i;
91997  int rc = 0;
91998  sqlite3 *db = sqlite3_context_db_handle(context);
91999  const char *zName;
92000  const char *zFile;
92001  char *zPath = 0;
92002  char *zErr = 0;
92003  unsigned int flags;
92004  Db *aNew;
92005  char *zErrDyn = 0;
92006  sqlite3_vfs *pVfs;
92007
92008  UNUSED_PARAMETER(NotUsed);
92009
92010  zFile = (const char *)sqlite3_value_text(argv[0]);
92011  zName = (const char *)sqlite3_value_text(argv[1]);
92012  if( zFile==0 ) zFile = "";
92013  if( zName==0 ) zName = "";
92014
92015  /* Check for the following errors:
92016  **
92017  **     * Too many attached databases,
92018  **     * Transaction currently open
92019  **     * Specified database name already being used.
92020  */
92021  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
92022    zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
92023      db->aLimit[SQLITE_LIMIT_ATTACHED]
92024    );
92025    goto attach_error;
92026  }
92027  if( !db->autoCommit ){
92028    zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
92029    goto attach_error;
92030  }
92031  for(i=0; i<db->nDb; i++){
92032    char *z = db->aDb[i].zName;
92033    assert( z && zName );
92034    if( sqlite3StrICmp(z, zName)==0 ){
92035      zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
92036      goto attach_error;
92037    }
92038  }
92039
92040  /* Allocate the new entry in the db->aDb[] array and initialize the schema
92041  ** hash tables.
92042  */
92043  if( db->aDb==db->aDbStatic ){
92044    aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
92045    if( aNew==0 ) return;
92046    memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
92047  }else{
92048    aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
92049    if( aNew==0 ) return;
92050  }
92051  db->aDb = aNew;
92052  aNew = &db->aDb[db->nDb];
92053  memset(aNew, 0, sizeof(*aNew));
92054
92055  /* Open the database file. If the btree is successfully opened, use
92056  ** it to obtain the database schema. At this point the schema may
92057  ** or may not be initialized.
92058  */
92059  flags = db->openFlags;
92060  rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
92061  if( rc!=SQLITE_OK ){
92062    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
92063    sqlite3_result_error(context, zErr, -1);
92064    sqlite3_free(zErr);
92065    return;
92066  }
92067  assert( pVfs );
92068  flags |= SQLITE_OPEN_MAIN_DB;
92069  rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
92070  sqlite3_free( zPath );
92071  db->nDb++;
92072  if( rc==SQLITE_CONSTRAINT ){
92073    rc = SQLITE_ERROR;
92074    zErrDyn = sqlite3MPrintf(db, "database is already attached");
92075  }else if( rc==SQLITE_OK ){
92076    Pager *pPager;
92077    aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
92078    if( !aNew->pSchema ){
92079      rc = SQLITE_NOMEM;
92080    }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
92081      zErrDyn = sqlite3MPrintf(db,
92082        "attached databases must use the same text encoding as main database");
92083      rc = SQLITE_ERROR;
92084    }
92085    sqlite3BtreeEnter(aNew->pBt);
92086    pPager = sqlite3BtreePager(aNew->pBt);
92087    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
92088    sqlite3BtreeSecureDelete(aNew->pBt,
92089                             sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
92090#ifndef SQLITE_OMIT_PAGER_PRAGMAS
92091    sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
92092#endif
92093    sqlite3BtreeLeave(aNew->pBt);
92094  }
92095  aNew->safety_level = 3;
92096  aNew->zName = sqlite3DbStrDup(db, zName);
92097  if( rc==SQLITE_OK && aNew->zName==0 ){
92098    rc = SQLITE_NOMEM;
92099  }
92100
92101
92102#ifdef SQLITE_HAS_CODEC
92103  if( rc==SQLITE_OK ){
92104    extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
92105    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
92106    int nKey;
92107    char *zKey;
92108    int t = sqlite3_value_type(argv[2]);
92109    switch( t ){
92110      case SQLITE_INTEGER:
92111      case SQLITE_FLOAT:
92112        zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
92113        rc = SQLITE_ERROR;
92114        break;
92115
92116      case SQLITE_TEXT:
92117      case SQLITE_BLOB:
92118        nKey = sqlite3_value_bytes(argv[2]);
92119        zKey = (char *)sqlite3_value_blob(argv[2]);
92120        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
92121        break;
92122
92123      case SQLITE_NULL:
92124        /* No key specified.  Use the key from the main database */
92125        sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
92126        if( nKey>0 || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
92127          rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
92128        }
92129        break;
92130    }
92131  }
92132#endif
92133
92134  /* If the file was opened successfully, read the schema for the new database.
92135  ** If this fails, or if opening the file failed, then close the file and
92136  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
92137  ** we found it.
92138  */
92139  if( rc==SQLITE_OK ){
92140    sqlite3BtreeEnterAll(db);
92141    rc = sqlite3Init(db, &zErrDyn);
92142    sqlite3BtreeLeaveAll(db);
92143  }
92144#ifdef SQLITE_USER_AUTHENTICATION
92145  if( rc==SQLITE_OK ){
92146    u8 newAuth = 0;
92147    rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
92148    if( newAuth<db->auth.authLevel ){
92149      rc = SQLITE_AUTH_USER;
92150    }
92151  }
92152#endif
92153  if( rc ){
92154    int iDb = db->nDb - 1;
92155    assert( iDb>=2 );
92156    if( db->aDb[iDb].pBt ){
92157      sqlite3BtreeClose(db->aDb[iDb].pBt);
92158      db->aDb[iDb].pBt = 0;
92159      db->aDb[iDb].pSchema = 0;
92160    }
92161    sqlite3ResetAllSchemasOfConnection(db);
92162    db->nDb = iDb;
92163    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
92164      db->mallocFailed = 1;
92165      sqlite3DbFree(db, zErrDyn);
92166      zErrDyn = sqlite3MPrintf(db, "out of memory");
92167    }else if( zErrDyn==0 ){
92168      zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
92169    }
92170    goto attach_error;
92171  }
92172
92173  return;
92174
92175attach_error:
92176  /* Return an error if we get here */
92177  if( zErrDyn ){
92178    sqlite3_result_error(context, zErrDyn, -1);
92179    sqlite3DbFree(db, zErrDyn);
92180  }
92181  if( rc ) sqlite3_result_error_code(context, rc);
92182}
92183
92184/*
92185** An SQL user-function registered to do the work of an DETACH statement. The
92186** three arguments to the function come directly from a detach statement:
92187**
92188**     DETACH DATABASE x
92189**
92190**     SELECT sqlite_detach(x)
92191*/
92192static void detachFunc(
92193  sqlite3_context *context,
92194  int NotUsed,
92195  sqlite3_value **argv
92196){
92197  const char *zName = (const char *)sqlite3_value_text(argv[0]);
92198  sqlite3 *db = sqlite3_context_db_handle(context);
92199  int i;
92200  Db *pDb = 0;
92201  char zErr[128];
92202
92203  UNUSED_PARAMETER(NotUsed);
92204
92205  if( zName==0 ) zName = "";
92206  for(i=0; i<db->nDb; i++){
92207    pDb = &db->aDb[i];
92208    if( pDb->pBt==0 ) continue;
92209    if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
92210  }
92211
92212  if( i>=db->nDb ){
92213    sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
92214    goto detach_error;
92215  }
92216  if( i<2 ){
92217    sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
92218    goto detach_error;
92219  }
92220  if( !db->autoCommit ){
92221    sqlite3_snprintf(sizeof(zErr), zErr,
92222                     "cannot DETACH database within transaction");
92223    goto detach_error;
92224  }
92225  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
92226    sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
92227    goto detach_error;
92228  }
92229
92230  sqlite3BtreeClose(pDb->pBt);
92231  pDb->pBt = 0;
92232  pDb->pSchema = 0;
92233  sqlite3CollapseDatabaseArray(db);
92234  return;
92235
92236detach_error:
92237  sqlite3_result_error(context, zErr, -1);
92238}
92239
92240/*
92241** This procedure generates VDBE code for a single invocation of either the
92242** sqlite_detach() or sqlite_attach() SQL user functions.
92243*/
92244static void codeAttach(
92245  Parse *pParse,       /* The parser context */
92246  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
92247  FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
92248  Expr *pAuthArg,      /* Expression to pass to authorization callback */
92249  Expr *pFilename,     /* Name of database file */
92250  Expr *pDbname,       /* Name of the database to use internally */
92251  Expr *pKey           /* Database key for encryption extension */
92252){
92253  int rc;
92254  NameContext sName;
92255  Vdbe *v;
92256  sqlite3* db = pParse->db;
92257  int regArgs;
92258
92259  memset(&sName, 0, sizeof(NameContext));
92260  sName.pParse = pParse;
92261
92262  if(
92263      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
92264      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
92265      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
92266  ){
92267    goto attach_end;
92268  }
92269
92270#ifndef SQLITE_OMIT_AUTHORIZATION
92271  if( pAuthArg ){
92272    char *zAuthArg;
92273    if( pAuthArg->op==TK_STRING ){
92274      zAuthArg = pAuthArg->u.zToken;
92275    }else{
92276      zAuthArg = 0;
92277    }
92278    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
92279    if(rc!=SQLITE_OK ){
92280      goto attach_end;
92281    }
92282  }
92283#endif /* SQLITE_OMIT_AUTHORIZATION */
92284
92285
92286  v = sqlite3GetVdbe(pParse);
92287  regArgs = sqlite3GetTempRange(pParse, 4);
92288  sqlite3ExprCode(pParse, pFilename, regArgs);
92289  sqlite3ExprCode(pParse, pDbname, regArgs+1);
92290  sqlite3ExprCode(pParse, pKey, regArgs+2);
92291
92292  assert( v || db->mallocFailed );
92293  if( v ){
92294    sqlite3VdbeAddOp3(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3);
92295    assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
92296    sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
92297    sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
92298
92299    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
92300    ** statement only). For DETACH, set it to false (expire all existing
92301    ** statements).
92302    */
92303    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
92304  }
92305
92306attach_end:
92307  sqlite3ExprDelete(db, pFilename);
92308  sqlite3ExprDelete(db, pDbname);
92309  sqlite3ExprDelete(db, pKey);
92310}
92311
92312/*
92313** Called by the parser to compile a DETACH statement.
92314**
92315**     DETACH pDbname
92316*/
92317SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
92318  static const FuncDef detach_func = {
92319    1,                /* nArg */
92320    SQLITE_UTF8,      /* funcFlags */
92321    0,                /* pUserData */
92322    0,                /* pNext */
92323    detachFunc,       /* xFunc */
92324    0,                /* xStep */
92325    0,                /* xFinalize */
92326    "sqlite_detach",  /* zName */
92327    0,                /* pHash */
92328    0                 /* pDestructor */
92329  };
92330  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
92331}
92332
92333/*
92334** Called by the parser to compile an ATTACH statement.
92335**
92336**     ATTACH p AS pDbname KEY pKey
92337*/
92338SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
92339  static const FuncDef attach_func = {
92340    3,                /* nArg */
92341    SQLITE_UTF8,      /* funcFlags */
92342    0,                /* pUserData */
92343    0,                /* pNext */
92344    attachFunc,       /* xFunc */
92345    0,                /* xStep */
92346    0,                /* xFinalize */
92347    "sqlite_attach",  /* zName */
92348    0,                /* pHash */
92349    0                 /* pDestructor */
92350  };
92351  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
92352}
92353#endif /* SQLITE_OMIT_ATTACH */
92354
92355/*
92356** Initialize a DbFixer structure.  This routine must be called prior
92357** to passing the structure to one of the sqliteFixAAAA() routines below.
92358*/
92359SQLITE_PRIVATE void sqlite3FixInit(
92360  DbFixer *pFix,      /* The fixer to be initialized */
92361  Parse *pParse,      /* Error messages will be written here */
92362  int iDb,            /* This is the database that must be used */
92363  const char *zType,  /* "view", "trigger", or "index" */
92364  const Token *pName  /* Name of the view, trigger, or index */
92365){
92366  sqlite3 *db;
92367
92368  db = pParse->db;
92369  assert( db->nDb>iDb );
92370  pFix->pParse = pParse;
92371  pFix->zDb = db->aDb[iDb].zName;
92372  pFix->pSchema = db->aDb[iDb].pSchema;
92373  pFix->zType = zType;
92374  pFix->pName = pName;
92375  pFix->bVarOnly = (iDb==1);
92376}
92377
92378/*
92379** The following set of routines walk through the parse tree and assign
92380** a specific database to all table references where the database name
92381** was left unspecified in the original SQL statement.  The pFix structure
92382** must have been initialized by a prior call to sqlite3FixInit().
92383**
92384** These routines are used to make sure that an index, trigger, or
92385** view in one database does not refer to objects in a different database.
92386** (Exception: indices, triggers, and views in the TEMP database are
92387** allowed to refer to anything.)  If a reference is explicitly made
92388** to an object in a different database, an error message is added to
92389** pParse->zErrMsg and these routines return non-zero.  If everything
92390** checks out, these routines return 0.
92391*/
92392SQLITE_PRIVATE int sqlite3FixSrcList(
92393  DbFixer *pFix,       /* Context of the fixation */
92394  SrcList *pList       /* The Source list to check and modify */
92395){
92396  int i;
92397  const char *zDb;
92398  struct SrcList_item *pItem;
92399
92400  if( NEVER(pList==0) ) return 0;
92401  zDb = pFix->zDb;
92402  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
92403    if( pFix->bVarOnly==0 ){
92404      if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
92405        sqlite3ErrorMsg(pFix->pParse,
92406            "%s %T cannot reference objects in database %s",
92407            pFix->zType, pFix->pName, pItem->zDatabase);
92408        return 1;
92409      }
92410      sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
92411      pItem->zDatabase = 0;
92412      pItem->pSchema = pFix->pSchema;
92413    }
92414#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
92415    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
92416    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
92417#endif
92418  }
92419  return 0;
92420}
92421#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
92422SQLITE_PRIVATE int sqlite3FixSelect(
92423  DbFixer *pFix,       /* Context of the fixation */
92424  Select *pSelect      /* The SELECT statement to be fixed to one database */
92425){
92426  while( pSelect ){
92427    if( sqlite3FixExprList(pFix, pSelect->pEList) ){
92428      return 1;
92429    }
92430    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
92431      return 1;
92432    }
92433    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
92434      return 1;
92435    }
92436    if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
92437      return 1;
92438    }
92439    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
92440      return 1;
92441    }
92442    if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
92443      return 1;
92444    }
92445    if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
92446      return 1;
92447    }
92448    if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
92449      return 1;
92450    }
92451    pSelect = pSelect->pPrior;
92452  }
92453  return 0;
92454}
92455SQLITE_PRIVATE int sqlite3FixExpr(
92456  DbFixer *pFix,     /* Context of the fixation */
92457  Expr *pExpr        /* The expression to be fixed to one database */
92458){
92459  while( pExpr ){
92460    if( pExpr->op==TK_VARIABLE ){
92461      if( pFix->pParse->db->init.busy ){
92462        pExpr->op = TK_NULL;
92463      }else{
92464        sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
92465        return 1;
92466      }
92467    }
92468    if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
92469    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
92470      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
92471    }else{
92472      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
92473    }
92474    if( sqlite3FixExpr(pFix, pExpr->pRight) ){
92475      return 1;
92476    }
92477    pExpr = pExpr->pLeft;
92478  }
92479  return 0;
92480}
92481SQLITE_PRIVATE int sqlite3FixExprList(
92482  DbFixer *pFix,     /* Context of the fixation */
92483  ExprList *pList    /* The expression to be fixed to one database */
92484){
92485  int i;
92486  struct ExprList_item *pItem;
92487  if( pList==0 ) return 0;
92488  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
92489    if( sqlite3FixExpr(pFix, pItem->pExpr) ){
92490      return 1;
92491    }
92492  }
92493  return 0;
92494}
92495#endif
92496
92497#ifndef SQLITE_OMIT_TRIGGER
92498SQLITE_PRIVATE int sqlite3FixTriggerStep(
92499  DbFixer *pFix,     /* Context of the fixation */
92500  TriggerStep *pStep /* The trigger step be fixed to one database */
92501){
92502  while( pStep ){
92503    if( sqlite3FixSelect(pFix, pStep->pSelect) ){
92504      return 1;
92505    }
92506    if( sqlite3FixExpr(pFix, pStep->pWhere) ){
92507      return 1;
92508    }
92509    if( sqlite3FixExprList(pFix, pStep->pExprList) ){
92510      return 1;
92511    }
92512    pStep = pStep->pNext;
92513  }
92514  return 0;
92515}
92516#endif
92517
92518/************** End of attach.c **********************************************/
92519/************** Begin file auth.c ********************************************/
92520/*
92521** 2003 January 11
92522**
92523** The author disclaims copyright to this source code.  In place of
92524** a legal notice, here is a blessing:
92525**
92526**    May you do good and not evil.
92527**    May you find forgiveness for yourself and forgive others.
92528**    May you share freely, never taking more than you give.
92529**
92530*************************************************************************
92531** This file contains code used to implement the sqlite3_set_authorizer()
92532** API.  This facility is an optional feature of the library.  Embedded
92533** systems that do not need this facility may omit it by recompiling
92534** the library with -DSQLITE_OMIT_AUTHORIZATION=1
92535*/
92536/* #include "sqliteInt.h" */
92537
92538/*
92539** All of the code in this file may be omitted by defining a single
92540** macro.
92541*/
92542#ifndef SQLITE_OMIT_AUTHORIZATION
92543
92544/*
92545** Set or clear the access authorization function.
92546**
92547** The access authorization function is be called during the compilation
92548** phase to verify that the user has read and/or write access permission on
92549** various fields of the database.  The first argument to the auth function
92550** is a copy of the 3rd argument to this routine.  The second argument
92551** to the auth function is one of these constants:
92552**
92553**       SQLITE_CREATE_INDEX
92554**       SQLITE_CREATE_TABLE
92555**       SQLITE_CREATE_TEMP_INDEX
92556**       SQLITE_CREATE_TEMP_TABLE
92557**       SQLITE_CREATE_TEMP_TRIGGER
92558**       SQLITE_CREATE_TEMP_VIEW
92559**       SQLITE_CREATE_TRIGGER
92560**       SQLITE_CREATE_VIEW
92561**       SQLITE_DELETE
92562**       SQLITE_DROP_INDEX
92563**       SQLITE_DROP_TABLE
92564**       SQLITE_DROP_TEMP_INDEX
92565**       SQLITE_DROP_TEMP_TABLE
92566**       SQLITE_DROP_TEMP_TRIGGER
92567**       SQLITE_DROP_TEMP_VIEW
92568**       SQLITE_DROP_TRIGGER
92569**       SQLITE_DROP_VIEW
92570**       SQLITE_INSERT
92571**       SQLITE_PRAGMA
92572**       SQLITE_READ
92573**       SQLITE_SELECT
92574**       SQLITE_TRANSACTION
92575**       SQLITE_UPDATE
92576**
92577** The third and fourth arguments to the auth function are the name of
92578** the table and the column that are being accessed.  The auth function
92579** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
92580** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
92581** means that the SQL statement will never-run - the sqlite3_exec() call
92582** will return with an error.  SQLITE_IGNORE means that the SQL statement
92583** should run but attempts to read the specified column will return NULL
92584** and attempts to write the column will be ignored.
92585**
92586** Setting the auth function to NULL disables this hook.  The default
92587** setting of the auth function is NULL.
92588*/
92589SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
92590  sqlite3 *db,
92591  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
92592  void *pArg
92593){
92594#ifdef SQLITE_ENABLE_API_ARMOR
92595  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
92596#endif
92597  sqlite3_mutex_enter(db->mutex);
92598  db->xAuth = (sqlite3_xauth)xAuth;
92599  db->pAuthArg = pArg;
92600  sqlite3ExpirePreparedStatements(db);
92601  sqlite3_mutex_leave(db->mutex);
92602  return SQLITE_OK;
92603}
92604
92605/*
92606** Write an error message into pParse->zErrMsg that explains that the
92607** user-supplied authorization function returned an illegal value.
92608*/
92609static void sqliteAuthBadReturnCode(Parse *pParse){
92610  sqlite3ErrorMsg(pParse, "authorizer malfunction");
92611  pParse->rc = SQLITE_ERROR;
92612}
92613
92614/*
92615** Invoke the authorization callback for permission to read column zCol from
92616** table zTab in database zDb. This function assumes that an authorization
92617** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
92618**
92619** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
92620** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
92621** is treated as SQLITE_DENY. In this case an error is left in pParse.
92622*/
92623SQLITE_PRIVATE int sqlite3AuthReadCol(
92624  Parse *pParse,                  /* The parser context */
92625  const char *zTab,               /* Table name */
92626  const char *zCol,               /* Column name */
92627  int iDb                         /* Index of containing database. */
92628){
92629  sqlite3 *db = pParse->db;       /* Database handle */
92630  char *zDb = db->aDb[iDb].zName; /* Name of attached database */
92631  int rc;                         /* Auth callback return code */
92632
92633  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
92634#ifdef SQLITE_USER_AUTHENTICATION
92635                 ,db->auth.zAuthUser
92636#endif
92637                );
92638  if( rc==SQLITE_DENY ){
92639    if( db->nDb>2 || iDb!=0 ){
92640      sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
92641    }else{
92642      sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
92643    }
92644    pParse->rc = SQLITE_AUTH;
92645  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
92646    sqliteAuthBadReturnCode(pParse);
92647  }
92648  return rc;
92649}
92650
92651/*
92652** The pExpr should be a TK_COLUMN expression.  The table referred to
92653** is in pTabList or else it is the NEW or OLD table of a trigger.
92654** Check to see if it is OK to read this particular column.
92655**
92656** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
92657** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
92658** then generate an error.
92659*/
92660SQLITE_PRIVATE void sqlite3AuthRead(
92661  Parse *pParse,        /* The parser context */
92662  Expr *pExpr,          /* The expression to check authorization on */
92663  Schema *pSchema,      /* The schema of the expression */
92664  SrcList *pTabList     /* All table that pExpr might refer to */
92665){
92666  sqlite3 *db = pParse->db;
92667  Table *pTab = 0;      /* The table being read */
92668  const char *zCol;     /* Name of the column of the table */
92669  int iSrc;             /* Index in pTabList->a[] of table being read */
92670  int iDb;              /* The index of the database the expression refers to */
92671  int iCol;             /* Index of column in table */
92672
92673  if( db->xAuth==0 ) return;
92674  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
92675  if( iDb<0 ){
92676    /* An attempt to read a column out of a subquery or other
92677    ** temporary table. */
92678    return;
92679  }
92680
92681  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
92682  if( pExpr->op==TK_TRIGGER ){
92683    pTab = pParse->pTriggerTab;
92684  }else{
92685    assert( pTabList );
92686    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
92687      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
92688        pTab = pTabList->a[iSrc].pTab;
92689        break;
92690      }
92691    }
92692  }
92693  iCol = pExpr->iColumn;
92694  if( NEVER(pTab==0) ) return;
92695
92696  if( iCol>=0 ){
92697    assert( iCol<pTab->nCol );
92698    zCol = pTab->aCol[iCol].zName;
92699  }else if( pTab->iPKey>=0 ){
92700    assert( pTab->iPKey<pTab->nCol );
92701    zCol = pTab->aCol[pTab->iPKey].zName;
92702  }else{
92703    zCol = "ROWID";
92704  }
92705  assert( iDb>=0 && iDb<db->nDb );
92706  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
92707    pExpr->op = TK_NULL;
92708  }
92709}
92710
92711/*
92712** Do an authorization check using the code and arguments given.  Return
92713** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
92714** is returned, then the error count and error message in pParse are
92715** modified appropriately.
92716*/
92717SQLITE_PRIVATE int sqlite3AuthCheck(
92718  Parse *pParse,
92719  int code,
92720  const char *zArg1,
92721  const char *zArg2,
92722  const char *zArg3
92723){
92724  sqlite3 *db = pParse->db;
92725  int rc;
92726
92727  /* Don't do any authorization checks if the database is initialising
92728  ** or if the parser is being invoked from within sqlite3_declare_vtab.
92729  */
92730  if( db->init.busy || IN_DECLARE_VTAB ){
92731    return SQLITE_OK;
92732  }
92733
92734  if( db->xAuth==0 ){
92735    return SQLITE_OK;
92736  }
92737  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
92738#ifdef SQLITE_USER_AUTHENTICATION
92739                 ,db->auth.zAuthUser
92740#endif
92741                );
92742  if( rc==SQLITE_DENY ){
92743    sqlite3ErrorMsg(pParse, "not authorized");
92744    pParse->rc = SQLITE_AUTH;
92745  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
92746    rc = SQLITE_DENY;
92747    sqliteAuthBadReturnCode(pParse);
92748  }
92749  return rc;
92750}
92751
92752/*
92753** Push an authorization context.  After this routine is called, the
92754** zArg3 argument to authorization callbacks will be zContext until
92755** popped.  Or if pParse==0, this routine is a no-op.
92756*/
92757SQLITE_PRIVATE void sqlite3AuthContextPush(
92758  Parse *pParse,
92759  AuthContext *pContext,
92760  const char *zContext
92761){
92762  assert( pParse );
92763  pContext->pParse = pParse;
92764  pContext->zAuthContext = pParse->zAuthContext;
92765  pParse->zAuthContext = zContext;
92766}
92767
92768/*
92769** Pop an authorization context that was previously pushed
92770** by sqlite3AuthContextPush
92771*/
92772SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
92773  if( pContext->pParse ){
92774    pContext->pParse->zAuthContext = pContext->zAuthContext;
92775    pContext->pParse = 0;
92776  }
92777}
92778
92779#endif /* SQLITE_OMIT_AUTHORIZATION */
92780
92781/************** End of auth.c ************************************************/
92782/************** Begin file build.c *******************************************/
92783/*
92784** 2001 September 15
92785**
92786** The author disclaims copyright to this source code.  In place of
92787** a legal notice, here is a blessing:
92788**
92789**    May you do good and not evil.
92790**    May you find forgiveness for yourself and forgive others.
92791**    May you share freely, never taking more than you give.
92792**
92793*************************************************************************
92794** This file contains C code routines that are called by the SQLite parser
92795** when syntax rules are reduced.  The routines in this file handle the
92796** following kinds of SQL syntax:
92797**
92798**     CREATE TABLE
92799**     DROP TABLE
92800**     CREATE INDEX
92801**     DROP INDEX
92802**     creating ID lists
92803**     BEGIN TRANSACTION
92804**     COMMIT
92805**     ROLLBACK
92806*/
92807/* #include "sqliteInt.h" */
92808
92809/*
92810** This routine is called when a new SQL statement is beginning to
92811** be parsed.  Initialize the pParse structure as needed.
92812*/
92813SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
92814  pParse->explain = (u8)explainFlag;
92815  pParse->nVar = 0;
92816}
92817
92818#ifndef SQLITE_OMIT_SHARED_CACHE
92819/*
92820** The TableLock structure is only used by the sqlite3TableLock() and
92821** codeTableLocks() functions.
92822*/
92823struct TableLock {
92824  int iDb;             /* The database containing the table to be locked */
92825  int iTab;            /* The root page of the table to be locked */
92826  u8 isWriteLock;      /* True for write lock.  False for a read lock */
92827  const char *zName;   /* Name of the table */
92828};
92829
92830/*
92831** Record the fact that we want to lock a table at run-time.
92832**
92833** The table to be locked has root page iTab and is found in database iDb.
92834** A read or a write lock can be taken depending on isWritelock.
92835**
92836** This routine just records the fact that the lock is desired.  The
92837** code to make the lock occur is generated by a later call to
92838** codeTableLocks() which occurs during sqlite3FinishCoding().
92839*/
92840SQLITE_PRIVATE void sqlite3TableLock(
92841  Parse *pParse,     /* Parsing context */
92842  int iDb,           /* Index of the database containing the table to lock */
92843  int iTab,          /* Root page number of the table to be locked */
92844  u8 isWriteLock,    /* True for a write lock */
92845  const char *zName  /* Name of the table to be locked */
92846){
92847  Parse *pToplevel = sqlite3ParseToplevel(pParse);
92848  int i;
92849  int nBytes;
92850  TableLock *p;
92851  assert( iDb>=0 );
92852
92853  for(i=0; i<pToplevel->nTableLock; i++){
92854    p = &pToplevel->aTableLock[i];
92855    if( p->iDb==iDb && p->iTab==iTab ){
92856      p->isWriteLock = (p->isWriteLock || isWriteLock);
92857      return;
92858    }
92859  }
92860
92861  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
92862  pToplevel->aTableLock =
92863      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
92864  if( pToplevel->aTableLock ){
92865    p = &pToplevel->aTableLock[pToplevel->nTableLock++];
92866    p->iDb = iDb;
92867    p->iTab = iTab;
92868    p->isWriteLock = isWriteLock;
92869    p->zName = zName;
92870  }else{
92871    pToplevel->nTableLock = 0;
92872    pToplevel->db->mallocFailed = 1;
92873  }
92874}
92875
92876/*
92877** Code an OP_TableLock instruction for each table locked by the
92878** statement (configured by calls to sqlite3TableLock()).
92879*/
92880static void codeTableLocks(Parse *pParse){
92881  int i;
92882  Vdbe *pVdbe;
92883
92884  pVdbe = sqlite3GetVdbe(pParse);
92885  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
92886
92887  for(i=0; i<pParse->nTableLock; i++){
92888    TableLock *p = &pParse->aTableLock[i];
92889    int p1 = p->iDb;
92890    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
92891                      p->zName, P4_STATIC);
92892  }
92893}
92894#else
92895  #define codeTableLocks(x)
92896#endif
92897
92898/*
92899** Return TRUE if the given yDbMask object is empty - if it contains no
92900** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
92901** macros when SQLITE_MAX_ATTACHED is greater than 30.
92902*/
92903#if SQLITE_MAX_ATTACHED>30
92904SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
92905  int i;
92906  for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
92907  return 1;
92908}
92909#endif
92910
92911/*
92912** This routine is called after a single SQL statement has been
92913** parsed and a VDBE program to execute that statement has been
92914** prepared.  This routine puts the finishing touches on the
92915** VDBE program and resets the pParse structure for the next
92916** parse.
92917**
92918** Note that if an error occurred, it might be the case that
92919** no VDBE code was generated.
92920*/
92921SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
92922  sqlite3 *db;
92923  Vdbe *v;
92924
92925  assert( pParse->pToplevel==0 );
92926  db = pParse->db;
92927  if( pParse->nested ) return;
92928  if( db->mallocFailed || pParse->nErr ){
92929    if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
92930    return;
92931  }
92932
92933  /* Begin by generating some termination code at the end of the
92934  ** vdbe program
92935  */
92936  v = sqlite3GetVdbe(pParse);
92937  assert( !pParse->isMultiWrite
92938       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
92939  if( v ){
92940    while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
92941    sqlite3VdbeAddOp0(v, OP_Halt);
92942
92943#if SQLITE_USER_AUTHENTICATION
92944    if( pParse->nTableLock>0 && db->init.busy==0 ){
92945      sqlite3UserAuthInit(db);
92946      if( db->auth.authLevel<UAUTH_User ){
92947        pParse->rc = SQLITE_AUTH_USER;
92948        sqlite3ErrorMsg(pParse, "user not authenticated");
92949        return;
92950      }
92951    }
92952#endif
92953
92954    /* The cookie mask contains one bit for each database file open.
92955    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
92956    ** set for each database that is used.  Generate code to start a
92957    ** transaction on each used database and to verify the schema cookie
92958    ** on each used database.
92959    */
92960    if( db->mallocFailed==0
92961     && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
92962    ){
92963      int iDb, i;
92964      assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
92965      sqlite3VdbeJumpHere(v, 0);
92966      for(iDb=0; iDb<db->nDb; iDb++){
92967        if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
92968        sqlite3VdbeUsesBtree(v, iDb);
92969        sqlite3VdbeAddOp4Int(v,
92970          OP_Transaction,                    /* Opcode */
92971          iDb,                               /* P1 */
92972          DbMaskTest(pParse->writeMask,iDb), /* P2 */
92973          pParse->cookieValue[iDb],          /* P3 */
92974          db->aDb[iDb].pSchema->iGeneration  /* P4 */
92975        );
92976        if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
92977        VdbeComment((v,
92978              "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
92979      }
92980#ifndef SQLITE_OMIT_VIRTUALTABLE
92981      for(i=0; i<pParse->nVtabLock; i++){
92982        char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
92983        sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
92984      }
92985      pParse->nVtabLock = 0;
92986#endif
92987
92988      /* Once all the cookies have been verified and transactions opened,
92989      ** obtain the required table-locks. This is a no-op unless the
92990      ** shared-cache feature is enabled.
92991      */
92992      codeTableLocks(pParse);
92993
92994      /* Initialize any AUTOINCREMENT data structures required.
92995      */
92996      sqlite3AutoincrementBegin(pParse);
92997
92998      /* Code constant expressions that where factored out of inner loops */
92999      if( pParse->pConstExpr ){
93000        ExprList *pEL = pParse->pConstExpr;
93001        pParse->okConstFactor = 0;
93002        for(i=0; i<pEL->nExpr; i++){
93003          sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
93004        }
93005      }
93006
93007      /* Finally, jump back to the beginning of the executable code. */
93008      sqlite3VdbeGoto(v, 1);
93009    }
93010  }
93011
93012
93013  /* Get the VDBE program ready for execution
93014  */
93015  if( v && pParse->nErr==0 && !db->mallocFailed ){
93016    assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
93017    /* A minimum of one cursor is required if autoincrement is used
93018    *  See ticket [a696379c1f08866] */
93019    if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
93020    sqlite3VdbeMakeReady(v, pParse);
93021    pParse->rc = SQLITE_DONE;
93022    pParse->colNamesSet = 0;
93023  }else{
93024    pParse->rc = SQLITE_ERROR;
93025  }
93026  pParse->nTab = 0;
93027  pParse->nMem = 0;
93028  pParse->nSet = 0;
93029  pParse->nVar = 0;
93030  DbMaskZero(pParse->cookieMask);
93031}
93032
93033/*
93034** Run the parser and code generator recursively in order to generate
93035** code for the SQL statement given onto the end of the pParse context
93036** currently under construction.  When the parser is run recursively
93037** this way, the final OP_Halt is not appended and other initialization
93038** and finalization steps are omitted because those are handling by the
93039** outermost parser.
93040**
93041** Not everything is nestable.  This facility is designed to permit
93042** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
93043** care if you decide to try to use this routine for some other purposes.
93044*/
93045SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
93046  va_list ap;
93047  char *zSql;
93048  char *zErrMsg = 0;
93049  sqlite3 *db = pParse->db;
93050# define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
93051  char saveBuf[SAVE_SZ];
93052
93053  if( pParse->nErr ) return;
93054  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
93055  va_start(ap, zFormat);
93056  zSql = sqlite3VMPrintf(db, zFormat, ap);
93057  va_end(ap);
93058  if( zSql==0 ){
93059    return;   /* A malloc must have failed */
93060  }
93061  pParse->nested++;
93062  memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
93063  memset(&pParse->nVar, 0, SAVE_SZ);
93064  sqlite3RunParser(pParse, zSql, &zErrMsg);
93065  sqlite3DbFree(db, zErrMsg);
93066  sqlite3DbFree(db, zSql);
93067  memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
93068  pParse->nested--;
93069}
93070
93071#if SQLITE_USER_AUTHENTICATION
93072/*
93073** Return TRUE if zTable is the name of the system table that stores the
93074** list of users and their access credentials.
93075*/
93076SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
93077  return sqlite3_stricmp(zTable, "sqlite_user")==0;
93078}
93079#endif
93080
93081/*
93082** Locate the in-memory structure that describes a particular database
93083** table given the name of that table and (optionally) the name of the
93084** database containing the table.  Return NULL if not found.
93085**
93086** If zDatabase is 0, all databases are searched for the table and the
93087** first matching table is returned.  (No checking for duplicate table
93088** names is done.)  The search order is TEMP first, then MAIN, then any
93089** auxiliary databases added using the ATTACH command.
93090**
93091** See also sqlite3LocateTable().
93092*/
93093SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
93094  Table *p = 0;
93095  int i;
93096
93097  /* All mutexes are required for schema access.  Make sure we hold them. */
93098  assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
93099#if SQLITE_USER_AUTHENTICATION
93100  /* Only the admin user is allowed to know that the sqlite_user table
93101  ** exists */
93102  if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
93103    return 0;
93104  }
93105#endif
93106  for(i=OMIT_TEMPDB; i<db->nDb; i++){
93107    int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
93108    if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
93109    assert( sqlite3SchemaMutexHeld(db, j, 0) );
93110    p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
93111    if( p ) break;
93112  }
93113  return p;
93114}
93115
93116/*
93117** Locate the in-memory structure that describes a particular database
93118** table given the name of that table and (optionally) the name of the
93119** database containing the table.  Return NULL if not found.  Also leave an
93120** error message in pParse->zErrMsg.
93121**
93122** The difference between this routine and sqlite3FindTable() is that this
93123** routine leaves an error message in pParse->zErrMsg where
93124** sqlite3FindTable() does not.
93125*/
93126SQLITE_PRIVATE Table *sqlite3LocateTable(
93127  Parse *pParse,         /* context in which to report errors */
93128  int isView,            /* True if looking for a VIEW rather than a TABLE */
93129  const char *zName,     /* Name of the table we are looking for */
93130  const char *zDbase     /* Name of the database.  Might be NULL */
93131){
93132  Table *p;
93133
93134  /* Read the database schema. If an error occurs, leave an error message
93135  ** and code in pParse and return NULL. */
93136  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
93137    return 0;
93138  }
93139
93140  p = sqlite3FindTable(pParse->db, zName, zDbase);
93141  if( p==0 ){
93142    const char *zMsg = isView ? "no such view" : "no such table";
93143#ifndef SQLITE_OMIT_VIRTUALTABLE
93144    if( sqlite3FindDbName(pParse->db, zDbase)<1 ){
93145      /* If zName is the not the name of a table in the schema created using
93146      ** CREATE, then check to see if it is the name of an virtual table that
93147      ** can be an eponymous virtual table. */
93148      Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
93149      if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
93150        return pMod->pEpoTab;
93151      }
93152    }
93153#endif
93154    if( zDbase ){
93155      sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
93156    }else{
93157      sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
93158    }
93159    pParse->checkSchema = 1;
93160  }
93161#if SQLITE_USER_AUTHENTICATION
93162  else if( pParse->db->auth.authLevel<UAUTH_User ){
93163    sqlite3ErrorMsg(pParse, "user not authenticated");
93164    p = 0;
93165  }
93166#endif
93167  return p;
93168}
93169
93170/*
93171** Locate the table identified by *p.
93172**
93173** This is a wrapper around sqlite3LocateTable(). The difference between
93174** sqlite3LocateTable() and this function is that this function restricts
93175** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
93176** non-NULL if it is part of a view or trigger program definition. See
93177** sqlite3FixSrcList() for details.
93178*/
93179SQLITE_PRIVATE Table *sqlite3LocateTableItem(
93180  Parse *pParse,
93181  int isView,
93182  struct SrcList_item *p
93183){
93184  const char *zDb;
93185  assert( p->pSchema==0 || p->zDatabase==0 );
93186  if( p->pSchema ){
93187    int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
93188    zDb = pParse->db->aDb[iDb].zName;
93189  }else{
93190    zDb = p->zDatabase;
93191  }
93192  return sqlite3LocateTable(pParse, isView, p->zName, zDb);
93193}
93194
93195/*
93196** Locate the in-memory structure that describes
93197** a particular index given the name of that index
93198** and the name of the database that contains the index.
93199** Return NULL if not found.
93200**
93201** If zDatabase is 0, all databases are searched for the
93202** table and the first matching index is returned.  (No checking
93203** for duplicate index names is done.)  The search order is
93204** TEMP first, then MAIN, then any auxiliary databases added
93205** using the ATTACH command.
93206*/
93207SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
93208  Index *p = 0;
93209  int i;
93210  /* All mutexes are required for schema access.  Make sure we hold them. */
93211  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
93212  for(i=OMIT_TEMPDB; i<db->nDb; i++){
93213    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
93214    Schema *pSchema = db->aDb[j].pSchema;
93215    assert( pSchema );
93216    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
93217    assert( sqlite3SchemaMutexHeld(db, j, 0) );
93218    p = sqlite3HashFind(&pSchema->idxHash, zName);
93219    if( p ) break;
93220  }
93221  return p;
93222}
93223
93224/*
93225** Reclaim the memory used by an index
93226*/
93227static void freeIndex(sqlite3 *db, Index *p){
93228#ifndef SQLITE_OMIT_ANALYZE
93229  sqlite3DeleteIndexSamples(db, p);
93230#endif
93231  sqlite3ExprDelete(db, p->pPartIdxWhere);
93232  sqlite3ExprListDelete(db, p->aColExpr);
93233  sqlite3DbFree(db, p->zColAff);
93234  if( p->isResized ) sqlite3DbFree(db, p->azColl);
93235#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
93236  sqlite3_free(p->aiRowEst);
93237#endif
93238  sqlite3DbFree(db, p);
93239}
93240
93241/*
93242** For the index called zIdxName which is found in the database iDb,
93243** unlike that index from its Table then remove the index from
93244** the index hash table and free all memory structures associated
93245** with the index.
93246*/
93247SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
93248  Index *pIndex;
93249  Hash *pHash;
93250
93251  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
93252  pHash = &db->aDb[iDb].pSchema->idxHash;
93253  pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
93254  if( ALWAYS(pIndex) ){
93255    if( pIndex->pTable->pIndex==pIndex ){
93256      pIndex->pTable->pIndex = pIndex->pNext;
93257    }else{
93258      Index *p;
93259      /* Justification of ALWAYS();  The index must be on the list of
93260      ** indices. */
93261      p = pIndex->pTable->pIndex;
93262      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
93263      if( ALWAYS(p && p->pNext==pIndex) ){
93264        p->pNext = pIndex->pNext;
93265      }
93266    }
93267    freeIndex(db, pIndex);
93268  }
93269  db->flags |= SQLITE_InternChanges;
93270}
93271
93272/*
93273** Look through the list of open database files in db->aDb[] and if
93274** any have been closed, remove them from the list.  Reallocate the
93275** db->aDb[] structure to a smaller size, if possible.
93276**
93277** Entry 0 (the "main" database) and entry 1 (the "temp" database)
93278** are never candidates for being collapsed.
93279*/
93280SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
93281  int i, j;
93282  for(i=j=2; i<db->nDb; i++){
93283    struct Db *pDb = &db->aDb[i];
93284    if( pDb->pBt==0 ){
93285      sqlite3DbFree(db, pDb->zName);
93286      pDb->zName = 0;
93287      continue;
93288    }
93289    if( j<i ){
93290      db->aDb[j] = db->aDb[i];
93291    }
93292    j++;
93293  }
93294  memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
93295  db->nDb = j;
93296  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
93297    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
93298    sqlite3DbFree(db, db->aDb);
93299    db->aDb = db->aDbStatic;
93300  }
93301}
93302
93303/*
93304** Reset the schema for the database at index iDb.  Also reset the
93305** TEMP schema.
93306*/
93307SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
93308  Db *pDb;
93309  assert( iDb<db->nDb );
93310
93311  /* Case 1:  Reset the single schema identified by iDb */
93312  pDb = &db->aDb[iDb];
93313  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
93314  assert( pDb->pSchema!=0 );
93315  sqlite3SchemaClear(pDb->pSchema);
93316
93317  /* If any database other than TEMP is reset, then also reset TEMP
93318  ** since TEMP might be holding triggers that reference tables in the
93319  ** other database.
93320  */
93321  if( iDb!=1 ){
93322    pDb = &db->aDb[1];
93323    assert( pDb->pSchema!=0 );
93324    sqlite3SchemaClear(pDb->pSchema);
93325  }
93326  return;
93327}
93328
93329/*
93330** Erase all schema information from all attached databases (including
93331** "main" and "temp") for a single database connection.
93332*/
93333SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
93334  int i;
93335  sqlite3BtreeEnterAll(db);
93336  for(i=0; i<db->nDb; i++){
93337    Db *pDb = &db->aDb[i];
93338    if( pDb->pSchema ){
93339      sqlite3SchemaClear(pDb->pSchema);
93340    }
93341  }
93342  db->flags &= ~SQLITE_InternChanges;
93343  sqlite3VtabUnlockList(db);
93344  sqlite3BtreeLeaveAll(db);
93345  sqlite3CollapseDatabaseArray(db);
93346}
93347
93348/*
93349** This routine is called when a commit occurs.
93350*/
93351SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
93352  db->flags &= ~SQLITE_InternChanges;
93353}
93354
93355/*
93356** Delete memory allocated for the column names of a table or view (the
93357** Table.aCol[] array).
93358*/
93359SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
93360  int i;
93361  Column *pCol;
93362  assert( pTable!=0 );
93363  if( (pCol = pTable->aCol)!=0 ){
93364    for(i=0; i<pTable->nCol; i++, pCol++){
93365      sqlite3DbFree(db, pCol->zName);
93366      sqlite3ExprDelete(db, pCol->pDflt);
93367      sqlite3DbFree(db, pCol->zDflt);
93368      sqlite3DbFree(db, pCol->zType);
93369      sqlite3DbFree(db, pCol->zColl);
93370    }
93371    sqlite3DbFree(db, pTable->aCol);
93372  }
93373}
93374
93375/*
93376** Remove the memory data structures associated with the given
93377** Table.  No changes are made to disk by this routine.
93378**
93379** This routine just deletes the data structure.  It does not unlink
93380** the table data structure from the hash table.  But it does destroy
93381** memory structures of the indices and foreign keys associated with
93382** the table.
93383**
93384** The db parameter is optional.  It is needed if the Table object
93385** contains lookaside memory.  (Table objects in the schema do not use
93386** lookaside memory, but some ephemeral Table objects do.)  Or the
93387** db parameter can be used with db->pnBytesFreed to measure the memory
93388** used by the Table object.
93389*/
93390SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
93391  Index *pIndex, *pNext;
93392  TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
93393
93394  assert( !pTable || pTable->nRef>0 );
93395
93396  /* Do not delete the table until the reference count reaches zero. */
93397  if( !pTable ) return;
93398  if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
93399
93400  /* Record the number of outstanding lookaside allocations in schema Tables
93401  ** prior to doing any free() operations.  Since schema Tables do not use
93402  ** lookaside, this number should not change. */
93403  TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
93404                         db->lookaside.nOut : 0 );
93405
93406  /* Delete all indices associated with this table. */
93407  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
93408    pNext = pIndex->pNext;
93409    assert( pIndex->pSchema==pTable->pSchema );
93410    if( !db || db->pnBytesFreed==0 ){
93411      char *zName = pIndex->zName;
93412      TESTONLY ( Index *pOld = ) sqlite3HashInsert(
93413         &pIndex->pSchema->idxHash, zName, 0
93414      );
93415      assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
93416      assert( pOld==pIndex || pOld==0 );
93417    }
93418    freeIndex(db, pIndex);
93419  }
93420
93421  /* Delete any foreign keys attached to this table. */
93422  sqlite3FkDelete(db, pTable);
93423
93424  /* Delete the Table structure itself.
93425  */
93426  sqlite3DeleteColumnNames(db, pTable);
93427  sqlite3DbFree(db, pTable->zName);
93428  sqlite3DbFree(db, pTable->zColAff);
93429  sqlite3SelectDelete(db, pTable->pSelect);
93430  sqlite3ExprListDelete(db, pTable->pCheck);
93431#ifndef SQLITE_OMIT_VIRTUALTABLE
93432  sqlite3VtabClear(db, pTable);
93433#endif
93434  sqlite3DbFree(db, pTable);
93435
93436  /* Verify that no lookaside memory was used by schema tables */
93437  assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
93438}
93439
93440/*
93441** Unlink the given table from the hash tables and the delete the
93442** table structure with all its indices and foreign keys.
93443*/
93444SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
93445  Table *p;
93446  Db *pDb;
93447
93448  assert( db!=0 );
93449  assert( iDb>=0 && iDb<db->nDb );
93450  assert( zTabName );
93451  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
93452  testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
93453  pDb = &db->aDb[iDb];
93454  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
93455  sqlite3DeleteTable(db, p);
93456  db->flags |= SQLITE_InternChanges;
93457}
93458
93459/*
93460** Given a token, return a string that consists of the text of that
93461** token.  Space to hold the returned string
93462** is obtained from sqliteMalloc() and must be freed by the calling
93463** function.
93464**
93465** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
93466** surround the body of the token are removed.
93467**
93468** Tokens are often just pointers into the original SQL text and so
93469** are not \000 terminated and are not persistent.  The returned string
93470** is \000 terminated and is persistent.
93471*/
93472SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
93473  char *zName;
93474  if( pName ){
93475    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
93476    sqlite3Dequote(zName);
93477  }else{
93478    zName = 0;
93479  }
93480  return zName;
93481}
93482
93483/*
93484** Open the sqlite_master table stored in database number iDb for
93485** writing. The table is opened using cursor 0.
93486*/
93487SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
93488  Vdbe *v = sqlite3GetVdbe(p);
93489  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
93490  sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
93491  if( p->nTab==0 ){
93492    p->nTab = 1;
93493  }
93494}
93495
93496/*
93497** Parameter zName points to a nul-terminated buffer containing the name
93498** of a database ("main", "temp" or the name of an attached db). This
93499** function returns the index of the named database in db->aDb[], or
93500** -1 if the named db cannot be found.
93501*/
93502SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
93503  int i = -1;         /* Database number */
93504  if( zName ){
93505    Db *pDb;
93506    int n = sqlite3Strlen30(zName);
93507    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
93508      if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
93509          0==sqlite3StrICmp(pDb->zName, zName) ){
93510        break;
93511      }
93512    }
93513  }
93514  return i;
93515}
93516
93517/*
93518** The token *pName contains the name of a database (either "main" or
93519** "temp" or the name of an attached db). This routine returns the
93520** index of the named database in db->aDb[], or -1 if the named db
93521** does not exist.
93522*/
93523SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
93524  int i;                               /* Database number */
93525  char *zName;                         /* Name we are searching for */
93526  zName = sqlite3NameFromToken(db, pName);
93527  i = sqlite3FindDbName(db, zName);
93528  sqlite3DbFree(db, zName);
93529  return i;
93530}
93531
93532/* The table or view or trigger name is passed to this routine via tokens
93533** pName1 and pName2. If the table name was fully qualified, for example:
93534**
93535** CREATE TABLE xxx.yyy (...);
93536**
93537** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
93538** the table name is not fully qualified, i.e.:
93539**
93540** CREATE TABLE yyy(...);
93541**
93542** Then pName1 is set to "yyy" and pName2 is "".
93543**
93544** This routine sets the *ppUnqual pointer to point at the token (pName1 or
93545** pName2) that stores the unqualified table name.  The index of the
93546** database "xxx" is returned.
93547*/
93548SQLITE_PRIVATE int sqlite3TwoPartName(
93549  Parse *pParse,      /* Parsing and code generating context */
93550  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
93551  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
93552  Token **pUnqual     /* Write the unqualified object name here */
93553){
93554  int iDb;                    /* Database holding the object */
93555  sqlite3 *db = pParse->db;
93556
93557  if( ALWAYS(pName2!=0) && pName2->n>0 ){
93558    if( db->init.busy ) {
93559      sqlite3ErrorMsg(pParse, "corrupt database");
93560      return -1;
93561    }
93562    *pUnqual = pName2;
93563    iDb = sqlite3FindDb(db, pName1);
93564    if( iDb<0 ){
93565      sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
93566      return -1;
93567    }
93568  }else{
93569    assert( db->init.iDb==0 || db->init.busy );
93570    iDb = db->init.iDb;
93571    *pUnqual = pName1;
93572  }
93573  return iDb;
93574}
93575
93576/*
93577** This routine is used to check if the UTF-8 string zName is a legal
93578** unqualified name for a new schema object (table, index, view or
93579** trigger). All names are legal except those that begin with the string
93580** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
93581** is reserved for internal use.
93582*/
93583SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
93584  if( !pParse->db->init.busy && pParse->nested==0
93585          && (pParse->db->flags & SQLITE_WriteSchema)==0
93586          && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
93587    sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
93588    return SQLITE_ERROR;
93589  }
93590  return SQLITE_OK;
93591}
93592
93593/*
93594** Return the PRIMARY KEY index of a table
93595*/
93596SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
93597  Index *p;
93598  for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
93599  return p;
93600}
93601
93602/*
93603** Return the column of index pIdx that corresponds to table
93604** column iCol.  Return -1 if not found.
93605*/
93606SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
93607  int i;
93608  for(i=0; i<pIdx->nColumn; i++){
93609    if( iCol==pIdx->aiColumn[i] ) return i;
93610  }
93611  return -1;
93612}
93613
93614/*
93615** Begin constructing a new table representation in memory.  This is
93616** the first of several action routines that get called in response
93617** to a CREATE TABLE statement.  In particular, this routine is called
93618** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
93619** flag is true if the table should be stored in the auxiliary database
93620** file instead of in the main database file.  This is normally the case
93621** when the "TEMP" or "TEMPORARY" keyword occurs in between
93622** CREATE and TABLE.
93623**
93624** The new table record is initialized and put in pParse->pNewTable.
93625** As more of the CREATE TABLE statement is parsed, additional action
93626** routines will be called to add more information to this record.
93627** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
93628** is called to complete the construction of the new table record.
93629*/
93630SQLITE_PRIVATE void sqlite3StartTable(
93631  Parse *pParse,   /* Parser context */
93632  Token *pName1,   /* First part of the name of the table or view */
93633  Token *pName2,   /* Second part of the name of the table or view */
93634  int isTemp,      /* True if this is a TEMP table */
93635  int isView,      /* True if this is a VIEW */
93636  int isVirtual,   /* True if this is a VIRTUAL table */
93637  int noErr        /* Do nothing if table already exists */
93638){
93639  Table *pTable;
93640  char *zName = 0; /* The name of the new table */
93641  sqlite3 *db = pParse->db;
93642  Vdbe *v;
93643  int iDb;         /* Database number to create the table in */
93644  Token *pName;    /* Unqualified name of the table to create */
93645
93646  /* The table or view name to create is passed to this routine via tokens
93647  ** pName1 and pName2. If the table name was fully qualified, for example:
93648  **
93649  ** CREATE TABLE xxx.yyy (...);
93650  **
93651  ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
93652  ** the table name is not fully qualified, i.e.:
93653  **
93654  ** CREATE TABLE yyy(...);
93655  **
93656  ** Then pName1 is set to "yyy" and pName2 is "".
93657  **
93658  ** The call below sets the pName pointer to point at the token (pName1 or
93659  ** pName2) that stores the unqualified table name. The variable iDb is
93660  ** set to the index of the database that the table or view is to be
93661  ** created in.
93662  */
93663  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
93664  if( iDb<0 ) return;
93665  if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
93666    /* If creating a temp table, the name may not be qualified. Unless
93667    ** the database name is "temp" anyway.  */
93668    sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
93669    return;
93670  }
93671  if( !OMIT_TEMPDB && isTemp ) iDb = 1;
93672
93673  pParse->sNameToken = *pName;
93674  zName = sqlite3NameFromToken(db, pName);
93675  if( zName==0 ) return;
93676  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
93677    goto begin_table_error;
93678  }
93679  if( db->init.iDb==1 ) isTemp = 1;
93680#ifndef SQLITE_OMIT_AUTHORIZATION
93681  assert( (isTemp & 1)==isTemp );
93682  {
93683    int code;
93684    char *zDb = db->aDb[iDb].zName;
93685    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
93686      goto begin_table_error;
93687    }
93688    if( isView ){
93689      if( !OMIT_TEMPDB && isTemp ){
93690        code = SQLITE_CREATE_TEMP_VIEW;
93691      }else{
93692        code = SQLITE_CREATE_VIEW;
93693      }
93694    }else{
93695      if( !OMIT_TEMPDB && isTemp ){
93696        code = SQLITE_CREATE_TEMP_TABLE;
93697      }else{
93698        code = SQLITE_CREATE_TABLE;
93699      }
93700    }
93701    if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
93702      goto begin_table_error;
93703    }
93704  }
93705#endif
93706
93707  /* Make sure the new table name does not collide with an existing
93708  ** index or table name in the same database.  Issue an error message if
93709  ** it does. The exception is if the statement being parsed was passed
93710  ** to an sqlite3_declare_vtab() call. In that case only the column names
93711  ** and types will be used, so there is no need to test for namespace
93712  ** collisions.
93713  */
93714  if( !IN_DECLARE_VTAB ){
93715    char *zDb = db->aDb[iDb].zName;
93716    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
93717      goto begin_table_error;
93718    }
93719    pTable = sqlite3FindTable(db, zName, zDb);
93720    if( pTable ){
93721      if( !noErr ){
93722        sqlite3ErrorMsg(pParse, "table %T already exists", pName);
93723      }else{
93724        assert( !db->init.busy || CORRUPT_DB );
93725        sqlite3CodeVerifySchema(pParse, iDb);
93726      }
93727      goto begin_table_error;
93728    }
93729    if( sqlite3FindIndex(db, zName, zDb)!=0 ){
93730      sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
93731      goto begin_table_error;
93732    }
93733  }
93734
93735  pTable = sqlite3DbMallocZero(db, sizeof(Table));
93736  if( pTable==0 ){
93737    db->mallocFailed = 1;
93738    pParse->rc = SQLITE_NOMEM;
93739    pParse->nErr++;
93740    goto begin_table_error;
93741  }
93742  pTable->zName = zName;
93743  pTable->iPKey = -1;
93744  pTable->pSchema = db->aDb[iDb].pSchema;
93745  pTable->nRef = 1;
93746  pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
93747  assert( pParse->pNewTable==0 );
93748  pParse->pNewTable = pTable;
93749
93750  /* If this is the magic sqlite_sequence table used by autoincrement,
93751  ** then record a pointer to this table in the main database structure
93752  ** so that INSERT can find the table easily.
93753  */
93754#ifndef SQLITE_OMIT_AUTOINCREMENT
93755  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
93756    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
93757    pTable->pSchema->pSeqTab = pTable;
93758  }
93759#endif
93760
93761  /* Begin generating the code that will insert the table record into
93762  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
93763  ** and allocate the record number for the table entry now.  Before any
93764  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
93765  ** indices to be created and the table record must come before the
93766  ** indices.  Hence, the record number for the table must be allocated
93767  ** now.
93768  */
93769  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
93770    int addr1;
93771    int fileFormat;
93772    int reg1, reg2, reg3;
93773    /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
93774    static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
93775    sqlite3BeginWriteOperation(pParse, 1, iDb);
93776
93777#ifndef SQLITE_OMIT_VIRTUALTABLE
93778    if( isVirtual ){
93779      sqlite3VdbeAddOp0(v, OP_VBegin);
93780    }
93781#endif
93782
93783    /* If the file format and encoding in the database have not been set,
93784    ** set them now.
93785    */
93786    reg1 = pParse->regRowid = ++pParse->nMem;
93787    reg2 = pParse->regRoot = ++pParse->nMem;
93788    reg3 = ++pParse->nMem;
93789    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
93790    sqlite3VdbeUsesBtree(v, iDb);
93791    addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
93792    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
93793                  1 : SQLITE_MAX_FILE_FORMAT;
93794    sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
93795    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
93796    sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
93797    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
93798    sqlite3VdbeJumpHere(v, addr1);
93799
93800    /* This just creates a place-holder record in the sqlite_master table.
93801    ** The record created does not contain anything yet.  It will be replaced
93802    ** by the real entry in code generated at sqlite3EndTable().
93803    **
93804    ** The rowid for the new entry is left in register pParse->regRowid.
93805    ** The root page number of the new table is left in reg pParse->regRoot.
93806    ** The rowid and root page number values are needed by the code that
93807    ** sqlite3EndTable will generate.
93808    */
93809#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
93810    if( isView || isVirtual ){
93811      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
93812    }else
93813#endif
93814    {
93815      pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
93816    }
93817    sqlite3OpenMasterTable(pParse, iDb);
93818    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
93819    sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
93820    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
93821    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
93822    sqlite3VdbeAddOp0(v, OP_Close);
93823  }
93824
93825  /* Normal (non-error) return. */
93826  return;
93827
93828  /* If an error occurs, we jump here */
93829begin_table_error:
93830  sqlite3DbFree(db, zName);
93831  return;
93832}
93833
93834/*
93835** This macro is used to compare two strings in a case-insensitive manner.
93836** It is slightly faster than calling sqlite3StrICmp() directly, but
93837** produces larger code.
93838**
93839** WARNING: This macro is not compatible with the strcmp() family. It
93840** returns true if the two strings are equal, otherwise false.
93841*/
93842#define STRICMP(x, y) (\
93843sqlite3UpperToLower[*(unsigned char *)(x)]==   \
93844sqlite3UpperToLower[*(unsigned char *)(y)]     \
93845&& sqlite3StrICmp((x)+1,(y)+1)==0 )
93846
93847/*
93848** Add a new column to the table currently being constructed.
93849**
93850** The parser calls this routine once for each column declaration
93851** in a CREATE TABLE statement.  sqlite3StartTable() gets called
93852** first to get things going.  Then this routine is called for each
93853** column.
93854*/
93855SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
93856  Table *p;
93857  int i;
93858  char *z;
93859  Column *pCol;
93860  sqlite3 *db = pParse->db;
93861  if( (p = pParse->pNewTable)==0 ) return;
93862#if SQLITE_MAX_COLUMN
93863  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
93864    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
93865    return;
93866  }
93867#endif
93868  z = sqlite3NameFromToken(db, pName);
93869  if( z==0 ) return;
93870  for(i=0; i<p->nCol; i++){
93871    if( STRICMP(z, p->aCol[i].zName) ){
93872      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
93873      sqlite3DbFree(db, z);
93874      return;
93875    }
93876  }
93877  if( (p->nCol & 0x7)==0 ){
93878    Column *aNew;
93879    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
93880    if( aNew==0 ){
93881      sqlite3DbFree(db, z);
93882      return;
93883    }
93884    p->aCol = aNew;
93885  }
93886  pCol = &p->aCol[p->nCol];
93887  memset(pCol, 0, sizeof(p->aCol[0]));
93888  pCol->zName = z;
93889
93890  /* If there is no type specified, columns have the default affinity
93891  ** 'BLOB'. If there is a type specified, then sqlite3AddColumnType() will
93892  ** be called next to set pCol->affinity correctly.
93893  */
93894  pCol->affinity = SQLITE_AFF_BLOB;
93895  pCol->szEst = 1;
93896  p->nCol++;
93897}
93898
93899/*
93900** This routine is called by the parser while in the middle of
93901** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
93902** been seen on a column.  This routine sets the notNull flag on
93903** the column currently under construction.
93904*/
93905SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
93906  Table *p;
93907  p = pParse->pNewTable;
93908  if( p==0 || NEVER(p->nCol<1) ) return;
93909  p->aCol[p->nCol-1].notNull = (u8)onError;
93910}
93911
93912/*
93913** Scan the column type name zType (length nType) and return the
93914** associated affinity type.
93915**
93916** This routine does a case-independent search of zType for the
93917** substrings in the following table. If one of the substrings is
93918** found, the corresponding affinity is returned. If zType contains
93919** more than one of the substrings, entries toward the top of
93920** the table take priority. For example, if zType is 'BLOBINT',
93921** SQLITE_AFF_INTEGER is returned.
93922**
93923** Substring     | Affinity
93924** --------------------------------
93925** 'INT'         | SQLITE_AFF_INTEGER
93926** 'CHAR'        | SQLITE_AFF_TEXT
93927** 'CLOB'        | SQLITE_AFF_TEXT
93928** 'TEXT'        | SQLITE_AFF_TEXT
93929** 'BLOB'        | SQLITE_AFF_BLOB
93930** 'REAL'        | SQLITE_AFF_REAL
93931** 'FLOA'        | SQLITE_AFF_REAL
93932** 'DOUB'        | SQLITE_AFF_REAL
93933**
93934** If none of the substrings in the above table are found,
93935** SQLITE_AFF_NUMERIC is returned.
93936*/
93937SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
93938  u32 h = 0;
93939  char aff = SQLITE_AFF_NUMERIC;
93940  const char *zChar = 0;
93941
93942  if( zIn==0 ) return aff;
93943  while( zIn[0] ){
93944    h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
93945    zIn++;
93946    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
93947      aff = SQLITE_AFF_TEXT;
93948      zChar = zIn;
93949    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
93950      aff = SQLITE_AFF_TEXT;
93951    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
93952      aff = SQLITE_AFF_TEXT;
93953    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
93954        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
93955      aff = SQLITE_AFF_BLOB;
93956      if( zIn[0]=='(' ) zChar = zIn;
93957#ifndef SQLITE_OMIT_FLOATING_POINT
93958    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
93959        && aff==SQLITE_AFF_NUMERIC ){
93960      aff = SQLITE_AFF_REAL;
93961    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
93962        && aff==SQLITE_AFF_NUMERIC ){
93963      aff = SQLITE_AFF_REAL;
93964    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
93965        && aff==SQLITE_AFF_NUMERIC ){
93966      aff = SQLITE_AFF_REAL;
93967#endif
93968    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
93969      aff = SQLITE_AFF_INTEGER;
93970      break;
93971    }
93972  }
93973
93974  /* If pszEst is not NULL, store an estimate of the field size.  The
93975  ** estimate is scaled so that the size of an integer is 1.  */
93976  if( pszEst ){
93977    *pszEst = 1;   /* default size is approx 4 bytes */
93978    if( aff<SQLITE_AFF_NUMERIC ){
93979      if( zChar ){
93980        while( zChar[0] ){
93981          if( sqlite3Isdigit(zChar[0]) ){
93982            int v = 0;
93983            sqlite3GetInt32(zChar, &v);
93984            v = v/4 + 1;
93985            if( v>255 ) v = 255;
93986            *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
93987            break;
93988          }
93989          zChar++;
93990        }
93991      }else{
93992        *pszEst = 5;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
93993      }
93994    }
93995  }
93996  return aff;
93997}
93998
93999/*
94000** This routine is called by the parser while in the middle of
94001** parsing a CREATE TABLE statement.  The pFirst token is the first
94002** token in the sequence of tokens that describe the type of the
94003** column currently under construction.   pLast is the last token
94004** in the sequence.  Use this information to construct a string
94005** that contains the typename of the column and store that string
94006** in zType.
94007*/
94008SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
94009  Table *p;
94010  Column *pCol;
94011
94012  p = pParse->pNewTable;
94013  if( p==0 || NEVER(p->nCol<1) ) return;
94014  pCol = &p->aCol[p->nCol-1];
94015  assert( pCol->zType==0 || CORRUPT_DB );
94016  sqlite3DbFree(pParse->db, pCol->zType);
94017  pCol->zType = sqlite3NameFromToken(pParse->db, pType);
94018  pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
94019}
94020
94021/*
94022** The expression is the default value for the most recently added column
94023** of the table currently under construction.
94024**
94025** Default value expressions must be constant.  Raise an exception if this
94026** is not the case.
94027**
94028** This routine is called by the parser while in the middle of
94029** parsing a CREATE TABLE statement.
94030*/
94031SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
94032  Table *p;
94033  Column *pCol;
94034  sqlite3 *db = pParse->db;
94035  p = pParse->pNewTable;
94036  if( p!=0 ){
94037    pCol = &(p->aCol[p->nCol-1]);
94038    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
94039      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
94040          pCol->zName);
94041    }else{
94042      /* A copy of pExpr is used instead of the original, as pExpr contains
94043      ** tokens that point to volatile memory. The 'span' of the expression
94044      ** is required by pragma table_info.
94045      */
94046      sqlite3ExprDelete(db, pCol->pDflt);
94047      pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
94048      sqlite3DbFree(db, pCol->zDflt);
94049      pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
94050                                     (int)(pSpan->zEnd - pSpan->zStart));
94051    }
94052  }
94053  sqlite3ExprDelete(db, pSpan->pExpr);
94054}
94055
94056/*
94057** Backwards Compatibility Hack:
94058**
94059** Historical versions of SQLite accepted strings as column names in
94060** indexes and PRIMARY KEY constraints and in UNIQUE constraints.  Example:
94061**
94062**     CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
94063**     CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
94064**
94065** This is goofy.  But to preserve backwards compatibility we continue to
94066** accept it.  This routine does the necessary conversion.  It converts
94067** the expression given in its argument from a TK_STRING into a TK_ID
94068** if the expression is just a TK_STRING with an optional COLLATE clause.
94069** If the epxression is anything other than TK_STRING, the expression is
94070** unchanged.
94071*/
94072static void sqlite3StringToId(Expr *p){
94073  if( p->op==TK_STRING ){
94074    p->op = TK_ID;
94075  }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
94076    p->pLeft->op = TK_ID;
94077  }
94078}
94079
94080/*
94081** Designate the PRIMARY KEY for the table.  pList is a list of names
94082** of columns that form the primary key.  If pList is NULL, then the
94083** most recently added column of the table is the primary key.
94084**
94085** A table can have at most one primary key.  If the table already has
94086** a primary key (and this is the second primary key) then create an
94087** error.
94088**
94089** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
94090** then we will try to use that column as the rowid.  Set the Table.iPKey
94091** field of the table under construction to be the index of the
94092** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
94093** no INTEGER PRIMARY KEY.
94094**
94095** If the key is not an INTEGER PRIMARY KEY, then create a unique
94096** index for the key.  No index is created for INTEGER PRIMARY KEYs.
94097*/
94098SQLITE_PRIVATE void sqlite3AddPrimaryKey(
94099  Parse *pParse,    /* Parsing context */
94100  ExprList *pList,  /* List of field names to be indexed */
94101  int onError,      /* What to do with a uniqueness conflict */
94102  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
94103  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
94104){
94105  Table *pTab = pParse->pNewTable;
94106  char *zType = 0;
94107  int iCol = -1, i;
94108  int nTerm;
94109  if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
94110  if( pTab->tabFlags & TF_HasPrimaryKey ){
94111    sqlite3ErrorMsg(pParse,
94112      "table \"%s\" has more than one primary key", pTab->zName);
94113    goto primary_key_exit;
94114  }
94115  pTab->tabFlags |= TF_HasPrimaryKey;
94116  if( pList==0 ){
94117    iCol = pTab->nCol - 1;
94118    pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
94119    zType = pTab->aCol[iCol].zType;
94120    nTerm = 1;
94121  }else{
94122    nTerm = pList->nExpr;
94123    for(i=0; i<nTerm; i++){
94124      Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
94125      assert( pCExpr!=0 );
94126      sqlite3StringToId(pCExpr);
94127      if( pCExpr->op==TK_ID ){
94128        const char *zCName = pCExpr->u.zToken;
94129        for(iCol=0; iCol<pTab->nCol; iCol++){
94130          if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
94131            pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
94132            zType = pTab->aCol[iCol].zType;
94133            break;
94134          }
94135        }
94136      }
94137    }
94138  }
94139  if( nTerm==1
94140   && zType && sqlite3StrICmp(zType, "INTEGER")==0
94141   && sortOrder!=SQLITE_SO_DESC
94142  ){
94143    pTab->iPKey = iCol;
94144    pTab->keyConf = (u8)onError;
94145    assert( autoInc==0 || autoInc==1 );
94146    pTab->tabFlags |= autoInc*TF_Autoincrement;
94147    if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
94148  }else if( autoInc ){
94149#ifndef SQLITE_OMIT_AUTOINCREMENT
94150    sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
94151       "INTEGER PRIMARY KEY");
94152#endif
94153  }else{
94154    Index *p;
94155    p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
94156                           0, sortOrder, 0);
94157    if( p ){
94158      p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
94159    }
94160    pList = 0;
94161  }
94162
94163primary_key_exit:
94164  sqlite3ExprListDelete(pParse->db, pList);
94165  return;
94166}
94167
94168/*
94169** Add a new CHECK constraint to the table currently under construction.
94170*/
94171SQLITE_PRIVATE void sqlite3AddCheckConstraint(
94172  Parse *pParse,    /* Parsing context */
94173  Expr *pCheckExpr  /* The check expression */
94174){
94175#ifndef SQLITE_OMIT_CHECK
94176  Table *pTab = pParse->pNewTable;
94177  sqlite3 *db = pParse->db;
94178  if( pTab && !IN_DECLARE_VTAB
94179   && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
94180  ){
94181    pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
94182    if( pParse->constraintName.n ){
94183      sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
94184    }
94185  }else
94186#endif
94187  {
94188    sqlite3ExprDelete(pParse->db, pCheckExpr);
94189  }
94190}
94191
94192/*
94193** Set the collation function of the most recently parsed table column
94194** to the CollSeq given.
94195*/
94196SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
94197  Table *p;
94198  int i;
94199  char *zColl;              /* Dequoted name of collation sequence */
94200  sqlite3 *db;
94201
94202  if( (p = pParse->pNewTable)==0 ) return;
94203  i = p->nCol-1;
94204  db = pParse->db;
94205  zColl = sqlite3NameFromToken(db, pToken);
94206  if( !zColl ) return;
94207
94208  if( sqlite3LocateCollSeq(pParse, zColl) ){
94209    Index *pIdx;
94210    sqlite3DbFree(db, p->aCol[i].zColl);
94211    p->aCol[i].zColl = zColl;
94212
94213    /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
94214    ** then an index may have been created on this column before the
94215    ** collation type was added. Correct this if it is the case.
94216    */
94217    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
94218      assert( pIdx->nKeyCol==1 );
94219      if( pIdx->aiColumn[0]==i ){
94220        pIdx->azColl[0] = p->aCol[i].zColl;
94221      }
94222    }
94223  }else{
94224    sqlite3DbFree(db, zColl);
94225  }
94226}
94227
94228/*
94229** This function returns the collation sequence for database native text
94230** encoding identified by the string zName, length nName.
94231**
94232** If the requested collation sequence is not available, or not available
94233** in the database native encoding, the collation factory is invoked to
94234** request it. If the collation factory does not supply such a sequence,
94235** and the sequence is available in another text encoding, then that is
94236** returned instead.
94237**
94238** If no versions of the requested collations sequence are available, or
94239** another error occurs, NULL is returned and an error message written into
94240** pParse.
94241**
94242** This routine is a wrapper around sqlite3FindCollSeq().  This routine
94243** invokes the collation factory if the named collation cannot be found
94244** and generates an error message.
94245**
94246** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
94247*/
94248SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
94249  sqlite3 *db = pParse->db;
94250  u8 enc = ENC(db);
94251  u8 initbusy = db->init.busy;
94252  CollSeq *pColl;
94253
94254  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
94255  if( !initbusy && (!pColl || !pColl->xCmp) ){
94256    pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
94257  }
94258
94259  return pColl;
94260}
94261
94262
94263/*
94264** Generate code that will increment the schema cookie.
94265**
94266** The schema cookie is used to determine when the schema for the
94267** database changes.  After each schema change, the cookie value
94268** changes.  When a process first reads the schema it records the
94269** cookie.  Thereafter, whenever it goes to access the database,
94270** it checks the cookie to make sure the schema has not changed
94271** since it was last read.
94272**
94273** This plan is not completely bullet-proof.  It is possible for
94274** the schema to change multiple times and for the cookie to be
94275** set back to prior value.  But schema changes are infrequent
94276** and the probability of hitting the same cookie value is only
94277** 1 chance in 2^32.  So we're safe enough.
94278*/
94279SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
94280  int r1 = sqlite3GetTempReg(pParse);
94281  sqlite3 *db = pParse->db;
94282  Vdbe *v = pParse->pVdbe;
94283  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94284  sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
94285  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
94286  sqlite3ReleaseTempReg(pParse, r1);
94287}
94288
94289/*
94290** Measure the number of characters needed to output the given
94291** identifier.  The number returned includes any quotes used
94292** but does not include the null terminator.
94293**
94294** The estimate is conservative.  It might be larger that what is
94295** really needed.
94296*/
94297static int identLength(const char *z){
94298  int n;
94299  for(n=0; *z; n++, z++){
94300    if( *z=='"' ){ n++; }
94301  }
94302  return n + 2;
94303}
94304
94305/*
94306** The first parameter is a pointer to an output buffer. The second
94307** parameter is a pointer to an integer that contains the offset at
94308** which to write into the output buffer. This function copies the
94309** nul-terminated string pointed to by the third parameter, zSignedIdent,
94310** to the specified offset in the buffer and updates *pIdx to refer
94311** to the first byte after the last byte written before returning.
94312**
94313** If the string zSignedIdent consists entirely of alpha-numeric
94314** characters, does not begin with a digit and is not an SQL keyword,
94315** then it is copied to the output buffer exactly as it is. Otherwise,
94316** it is quoted using double-quotes.
94317*/
94318static void identPut(char *z, int *pIdx, char *zSignedIdent){
94319  unsigned char *zIdent = (unsigned char*)zSignedIdent;
94320  int i, j, needQuote;
94321  i = *pIdx;
94322
94323  for(j=0; zIdent[j]; j++){
94324    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
94325  }
94326  needQuote = sqlite3Isdigit(zIdent[0])
94327            || sqlite3KeywordCode(zIdent, j)!=TK_ID
94328            || zIdent[j]!=0
94329            || j==0;
94330
94331  if( needQuote ) z[i++] = '"';
94332  for(j=0; zIdent[j]; j++){
94333    z[i++] = zIdent[j];
94334    if( zIdent[j]=='"' ) z[i++] = '"';
94335  }
94336  if( needQuote ) z[i++] = '"';
94337  z[i] = 0;
94338  *pIdx = i;
94339}
94340
94341/*
94342** Generate a CREATE TABLE statement appropriate for the given
94343** table.  Memory to hold the text of the statement is obtained
94344** from sqliteMalloc() and must be freed by the calling function.
94345*/
94346static char *createTableStmt(sqlite3 *db, Table *p){
94347  int i, k, n;
94348  char *zStmt;
94349  char *zSep, *zSep2, *zEnd;
94350  Column *pCol;
94351  n = 0;
94352  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
94353    n += identLength(pCol->zName) + 5;
94354  }
94355  n += identLength(p->zName);
94356  if( n<50 ){
94357    zSep = "";
94358    zSep2 = ",";
94359    zEnd = ")";
94360  }else{
94361    zSep = "\n  ";
94362    zSep2 = ",\n  ";
94363    zEnd = "\n)";
94364  }
94365  n += 35 + 6*p->nCol;
94366  zStmt = sqlite3DbMallocRaw(0, n);
94367  if( zStmt==0 ){
94368    db->mallocFailed = 1;
94369    return 0;
94370  }
94371  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
94372  k = sqlite3Strlen30(zStmt);
94373  identPut(zStmt, &k, p->zName);
94374  zStmt[k++] = '(';
94375  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
94376    static const char * const azType[] = {
94377        /* SQLITE_AFF_BLOB    */ "",
94378        /* SQLITE_AFF_TEXT    */ " TEXT",
94379        /* SQLITE_AFF_NUMERIC */ " NUM",
94380        /* SQLITE_AFF_INTEGER */ " INT",
94381        /* SQLITE_AFF_REAL    */ " REAL"
94382    };
94383    int len;
94384    const char *zType;
94385
94386    sqlite3_snprintf(n-k, &zStmt[k], zSep);
94387    k += sqlite3Strlen30(&zStmt[k]);
94388    zSep = zSep2;
94389    identPut(zStmt, &k, pCol->zName);
94390    assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
94391    assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
94392    testcase( pCol->affinity==SQLITE_AFF_BLOB );
94393    testcase( pCol->affinity==SQLITE_AFF_TEXT );
94394    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
94395    testcase( pCol->affinity==SQLITE_AFF_INTEGER );
94396    testcase( pCol->affinity==SQLITE_AFF_REAL );
94397
94398    zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
94399    len = sqlite3Strlen30(zType);
94400    assert( pCol->affinity==SQLITE_AFF_BLOB
94401            || pCol->affinity==sqlite3AffinityType(zType, 0) );
94402    memcpy(&zStmt[k], zType, len);
94403    k += len;
94404    assert( k<=n );
94405  }
94406  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
94407  return zStmt;
94408}
94409
94410/*
94411** Resize an Index object to hold N columns total.  Return SQLITE_OK
94412** on success and SQLITE_NOMEM on an OOM error.
94413*/
94414static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
94415  char *zExtra;
94416  int nByte;
94417  if( pIdx->nColumn>=N ) return SQLITE_OK;
94418  assert( pIdx->isResized==0 );
94419  nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
94420  zExtra = sqlite3DbMallocZero(db, nByte);
94421  if( zExtra==0 ) return SQLITE_NOMEM;
94422  memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
94423  pIdx->azColl = (char**)zExtra;
94424  zExtra += sizeof(char*)*N;
94425  memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
94426  pIdx->aiColumn = (i16*)zExtra;
94427  zExtra += sizeof(i16)*N;
94428  memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
94429  pIdx->aSortOrder = (u8*)zExtra;
94430  pIdx->nColumn = N;
94431  pIdx->isResized = 1;
94432  return SQLITE_OK;
94433}
94434
94435/*
94436** Estimate the total row width for a table.
94437*/
94438static void estimateTableWidth(Table *pTab){
94439  unsigned wTable = 0;
94440  const Column *pTabCol;
94441  int i;
94442  for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
94443    wTable += pTabCol->szEst;
94444  }
94445  if( pTab->iPKey<0 ) wTable++;
94446  pTab->szTabRow = sqlite3LogEst(wTable*4);
94447}
94448
94449/*
94450** Estimate the average size of a row for an index.
94451*/
94452static void estimateIndexWidth(Index *pIdx){
94453  unsigned wIndex = 0;
94454  int i;
94455  const Column *aCol = pIdx->pTable->aCol;
94456  for(i=0; i<pIdx->nColumn; i++){
94457    i16 x = pIdx->aiColumn[i];
94458    assert( x<pIdx->pTable->nCol );
94459    wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
94460  }
94461  pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
94462}
94463
94464/* Return true if value x is found any of the first nCol entries of aiCol[]
94465*/
94466static int hasColumn(const i16 *aiCol, int nCol, int x){
94467  while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
94468  return 0;
94469}
94470
94471/*
94472** This routine runs at the end of parsing a CREATE TABLE statement that
94473** has a WITHOUT ROWID clause.  The job of this routine is to convert both
94474** internal schema data structures and the generated VDBE code so that they
94475** are appropriate for a WITHOUT ROWID table instead of a rowid table.
94476** Changes include:
94477**
94478**     (1)  Convert the OP_CreateTable into an OP_CreateIndex.  There is
94479**          no rowid btree for a WITHOUT ROWID.  Instead, the canonical
94480**          data storage is a covering index btree.
94481**     (2)  Bypass the creation of the sqlite_master table entry
94482**          for the PRIMARY KEY as the primary key index is now
94483**          identified by the sqlite_master table entry of the table itself.
94484**     (3)  Set the Index.tnum of the PRIMARY KEY Index object in the
94485**          schema to the rootpage from the main table.
94486**     (4)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
94487**     (5)  Add all table columns to the PRIMARY KEY Index object
94488**          so that the PRIMARY KEY is a covering index.  The surplus
94489**          columns are part of KeyInfo.nXField and are not used for
94490**          sorting or lookup or uniqueness checks.
94491**     (6)  Replace the rowid tail on all automatically generated UNIQUE
94492**          indices with the PRIMARY KEY columns.
94493*/
94494static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
94495  Index *pIdx;
94496  Index *pPk;
94497  int nPk;
94498  int i, j;
94499  sqlite3 *db = pParse->db;
94500  Vdbe *v = pParse->pVdbe;
94501
94502  /* Convert the OP_CreateTable opcode that would normally create the
94503  ** root-page for the table into an OP_CreateIndex opcode.  The index
94504  ** created will become the PRIMARY KEY index.
94505  */
94506  if( pParse->addrCrTab ){
94507    assert( v );
94508    sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex);
94509  }
94510
94511  /* Locate the PRIMARY KEY index.  Or, if this table was originally
94512  ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
94513  */
94514  if( pTab->iPKey>=0 ){
94515    ExprList *pList;
94516    Token ipkToken;
94517    ipkToken.z = pTab->aCol[pTab->iPKey].zName;
94518    ipkToken.n = sqlite3Strlen30(ipkToken.z);
94519    pList = sqlite3ExprListAppend(pParse, 0,
94520                  sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
94521    if( pList==0 ) return;
94522    pList->a[0].sortOrder = pParse->iPkSortOrder;
94523    assert( pParse->pNewTable==pTab );
94524    pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
94525    if( pPk==0 ) return;
94526    pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
94527    pTab->iPKey = -1;
94528  }else{
94529    pPk = sqlite3PrimaryKeyIndex(pTab);
94530
94531    /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
94532    ** table entry. This is only required if currently generating VDBE
94533    ** code for a CREATE TABLE (not when parsing one as part of reading
94534    ** a database schema).  */
94535    if( v ){
94536      assert( db->init.busy==0 );
94537      sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
94538    }
94539
94540    /*
94541    ** Remove all redundant columns from the PRIMARY KEY.  For example, change
94542    ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)".  Later
94543    ** code assumes the PRIMARY KEY contains no repeated columns.
94544    */
94545    for(i=j=1; i<pPk->nKeyCol; i++){
94546      if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
94547        pPk->nColumn--;
94548      }else{
94549        pPk->aiColumn[j++] = pPk->aiColumn[i];
94550      }
94551    }
94552    pPk->nKeyCol = j;
94553  }
94554  pPk->isCovering = 1;
94555  assert( pPk!=0 );
94556  nPk = pPk->nKeyCol;
94557
94558  /* Make sure every column of the PRIMARY KEY is NOT NULL.  (Except,
94559  ** do not enforce this for imposter tables.) */
94560  if( !db->init.imposterTable ){
94561    for(i=0; i<nPk; i++){
94562      pTab->aCol[pPk->aiColumn[i]].notNull = 1;
94563    }
94564    pPk->uniqNotNull = 1;
94565  }
94566
94567  /* The root page of the PRIMARY KEY is the table root page */
94568  pPk->tnum = pTab->tnum;
94569
94570  /* Update the in-memory representation of all UNIQUE indices by converting
94571  ** the final rowid column into one or more columns of the PRIMARY KEY.
94572  */
94573  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
94574    int n;
94575    if( IsPrimaryKeyIndex(pIdx) ) continue;
94576    for(i=n=0; i<nPk; i++){
94577      if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
94578    }
94579    if( n==0 ){
94580      /* This index is a superset of the primary key */
94581      pIdx->nColumn = pIdx->nKeyCol;
94582      continue;
94583    }
94584    if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
94585    for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
94586      if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
94587        pIdx->aiColumn[j] = pPk->aiColumn[i];
94588        pIdx->azColl[j] = pPk->azColl[i];
94589        j++;
94590      }
94591    }
94592    assert( pIdx->nColumn>=pIdx->nKeyCol+n );
94593    assert( pIdx->nColumn>=j );
94594  }
94595
94596  /* Add all table columns to the PRIMARY KEY index
94597  */
94598  if( nPk<pTab->nCol ){
94599    if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
94600    for(i=0, j=nPk; i<pTab->nCol; i++){
94601      if( !hasColumn(pPk->aiColumn, j, i) ){
94602        assert( j<pPk->nColumn );
94603        pPk->aiColumn[j] = i;
94604        pPk->azColl[j] = "BINARY";
94605        j++;
94606      }
94607    }
94608    assert( pPk->nColumn==j );
94609    assert( pTab->nCol==j );
94610  }else{
94611    pPk->nColumn = pTab->nCol;
94612  }
94613}
94614
94615/*
94616** This routine is called to report the final ")" that terminates
94617** a CREATE TABLE statement.
94618**
94619** The table structure that other action routines have been building
94620** is added to the internal hash tables, assuming no errors have
94621** occurred.
94622**
94623** An entry for the table is made in the master table on disk, unless
94624** this is a temporary table or db->init.busy==1.  When db->init.busy==1
94625** it means we are reading the sqlite_master table because we just
94626** connected to the database or because the sqlite_master table has
94627** recently changed, so the entry for this table already exists in
94628** the sqlite_master table.  We do not want to create it again.
94629**
94630** If the pSelect argument is not NULL, it means that this routine
94631** was called to create a table generated from a
94632** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
94633** the new table will match the result set of the SELECT.
94634*/
94635SQLITE_PRIVATE void sqlite3EndTable(
94636  Parse *pParse,          /* Parse context */
94637  Token *pCons,           /* The ',' token after the last column defn. */
94638  Token *pEnd,            /* The ')' before options in the CREATE TABLE */
94639  u8 tabOpts,             /* Extra table options. Usually 0. */
94640  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
94641){
94642  Table *p;                 /* The new table */
94643  sqlite3 *db = pParse->db; /* The database connection */
94644  int iDb;                  /* Database in which the table lives */
94645  Index *pIdx;              /* An implied index of the table */
94646
94647  if( pEnd==0 && pSelect==0 ){
94648    return;
94649  }
94650  assert( !db->mallocFailed );
94651  p = pParse->pNewTable;
94652  if( p==0 ) return;
94653
94654  assert( !db->init.busy || !pSelect );
94655
94656  /* If the db->init.busy is 1 it means we are reading the SQL off the
94657  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
94658  ** So do not write to the disk again.  Extract the root page number
94659  ** for the table from the db->init.newTnum field.  (The page number
94660  ** should have been put there by the sqliteOpenCb routine.)
94661  */
94662  if( db->init.busy ){
94663    p->tnum = db->init.newTnum;
94664  }
94665
94666  /* Special processing for WITHOUT ROWID Tables */
94667  if( tabOpts & TF_WithoutRowid ){
94668    if( (p->tabFlags & TF_Autoincrement) ){
94669      sqlite3ErrorMsg(pParse,
94670          "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
94671      return;
94672    }
94673    if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
94674      sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
94675    }else{
94676      p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
94677      convertToWithoutRowidTable(pParse, p);
94678    }
94679  }
94680
94681  iDb = sqlite3SchemaToIndex(db, p->pSchema);
94682
94683#ifndef SQLITE_OMIT_CHECK
94684  /* Resolve names in all CHECK constraint expressions.
94685  */
94686  if( p->pCheck ){
94687    sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
94688  }
94689#endif /* !defined(SQLITE_OMIT_CHECK) */
94690
94691  /* Estimate the average row size for the table and for all implied indices */
94692  estimateTableWidth(p);
94693  for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
94694    estimateIndexWidth(pIdx);
94695  }
94696
94697  /* If not initializing, then create a record for the new table
94698  ** in the SQLITE_MASTER table of the database.
94699  **
94700  ** If this is a TEMPORARY table, write the entry into the auxiliary
94701  ** file instead of into the main database file.
94702  */
94703  if( !db->init.busy ){
94704    int n;
94705    Vdbe *v;
94706    char *zType;    /* "view" or "table" */
94707    char *zType2;   /* "VIEW" or "TABLE" */
94708    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
94709
94710    v = sqlite3GetVdbe(pParse);
94711    if( NEVER(v==0) ) return;
94712
94713    sqlite3VdbeAddOp1(v, OP_Close, 0);
94714
94715    /*
94716    ** Initialize zType for the new view or table.
94717    */
94718    if( p->pSelect==0 ){
94719      /* A regular table */
94720      zType = "table";
94721      zType2 = "TABLE";
94722#ifndef SQLITE_OMIT_VIEW
94723    }else{
94724      /* A view */
94725      zType = "view";
94726      zType2 = "VIEW";
94727#endif
94728    }
94729
94730    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
94731    ** statement to populate the new table. The root-page number for the
94732    ** new table is in register pParse->regRoot.
94733    **
94734    ** Once the SELECT has been coded by sqlite3Select(), it is in a
94735    ** suitable state to query for the column names and types to be used
94736    ** by the new table.
94737    **
94738    ** A shared-cache write-lock is not required to write to the new table,
94739    ** as a schema-lock must have already been obtained to create it. Since
94740    ** a schema-lock excludes all other database users, the write-lock would
94741    ** be redundant.
94742    */
94743    if( pSelect ){
94744      SelectDest dest;    /* Where the SELECT should store results */
94745      int regYield;       /* Register holding co-routine entry-point */
94746      int addrTop;        /* Top of the co-routine */
94747      int regRec;         /* A record to be insert into the new table */
94748      int regRowid;       /* Rowid of the next row to insert */
94749      int addrInsLoop;    /* Top of the loop for inserting rows */
94750      Table *pSelTab;     /* A table that describes the SELECT results */
94751
94752      regYield = ++pParse->nMem;
94753      regRec = ++pParse->nMem;
94754      regRowid = ++pParse->nMem;
94755      assert(pParse->nTab==1);
94756      sqlite3MayAbort(pParse);
94757      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
94758      sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
94759      pParse->nTab = 2;
94760      addrTop = sqlite3VdbeCurrentAddr(v) + 1;
94761      sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
94762      sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
94763      sqlite3Select(pParse, pSelect, &dest);
94764      sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
94765      sqlite3VdbeJumpHere(v, addrTop - 1);
94766      if( pParse->nErr ) return;
94767      pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
94768      if( pSelTab==0 ) return;
94769      assert( p->aCol==0 );
94770      p->nCol = pSelTab->nCol;
94771      p->aCol = pSelTab->aCol;
94772      pSelTab->nCol = 0;
94773      pSelTab->aCol = 0;
94774      sqlite3DeleteTable(db, pSelTab);
94775      addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
94776      VdbeCoverage(v);
94777      sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
94778      sqlite3TableAffinity(v, p, 0);
94779      sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
94780      sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
94781      sqlite3VdbeGoto(v, addrInsLoop);
94782      sqlite3VdbeJumpHere(v, addrInsLoop);
94783      sqlite3VdbeAddOp1(v, OP_Close, 1);
94784    }
94785
94786    /* Compute the complete text of the CREATE statement */
94787    if( pSelect ){
94788      zStmt = createTableStmt(db, p);
94789    }else{
94790      Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
94791      n = (int)(pEnd2->z - pParse->sNameToken.z);
94792      if( pEnd2->z[0]!=';' ) n += pEnd2->n;
94793      zStmt = sqlite3MPrintf(db,
94794          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
94795      );
94796    }
94797
94798    /* A slot for the record has already been allocated in the
94799    ** SQLITE_MASTER table.  We just need to update that slot with all
94800    ** the information we've collected.
94801    */
94802    sqlite3NestedParse(pParse,
94803      "UPDATE %Q.%s "
94804         "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
94805       "WHERE rowid=#%d",
94806      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
94807      zType,
94808      p->zName,
94809      p->zName,
94810      pParse->regRoot,
94811      zStmt,
94812      pParse->regRowid
94813    );
94814    sqlite3DbFree(db, zStmt);
94815    sqlite3ChangeCookie(pParse, iDb);
94816
94817#ifndef SQLITE_OMIT_AUTOINCREMENT
94818    /* Check to see if we need to create an sqlite_sequence table for
94819    ** keeping track of autoincrement keys.
94820    */
94821    if( p->tabFlags & TF_Autoincrement ){
94822      Db *pDb = &db->aDb[iDb];
94823      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94824      if( pDb->pSchema->pSeqTab==0 ){
94825        sqlite3NestedParse(pParse,
94826          "CREATE TABLE %Q.sqlite_sequence(name,seq)",
94827          pDb->zName
94828        );
94829      }
94830    }
94831#endif
94832
94833    /* Reparse everything to update our internal data structures */
94834    sqlite3VdbeAddParseSchemaOp(v, iDb,
94835           sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
94836  }
94837
94838
94839  /* Add the table to the in-memory representation of the database.
94840  */
94841  if( db->init.busy ){
94842    Table *pOld;
94843    Schema *pSchema = p->pSchema;
94844    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94845    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
94846    if( pOld ){
94847      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
94848      db->mallocFailed = 1;
94849      return;
94850    }
94851    pParse->pNewTable = 0;
94852    db->flags |= SQLITE_InternChanges;
94853
94854#ifndef SQLITE_OMIT_ALTERTABLE
94855    if( !p->pSelect ){
94856      const char *zName = (const char *)pParse->sNameToken.z;
94857      int nName;
94858      assert( !pSelect && pCons && pEnd );
94859      if( pCons->z==0 ){
94860        pCons = pEnd;
94861      }
94862      nName = (int)((const char *)pCons->z - zName);
94863      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
94864    }
94865#endif
94866  }
94867}
94868
94869#ifndef SQLITE_OMIT_VIEW
94870/*
94871** The parser calls this routine in order to create a new VIEW
94872*/
94873SQLITE_PRIVATE void sqlite3CreateView(
94874  Parse *pParse,     /* The parsing context */
94875  Token *pBegin,     /* The CREATE token that begins the statement */
94876  Token *pName1,     /* The token that holds the name of the view */
94877  Token *pName2,     /* The token that holds the name of the view */
94878  ExprList *pCNames, /* Optional list of view column names */
94879  Select *pSelect,   /* A SELECT statement that will become the new view */
94880  int isTemp,        /* TRUE for a TEMPORARY view */
94881  int noErr          /* Suppress error messages if VIEW already exists */
94882){
94883  Table *p;
94884  int n;
94885  const char *z;
94886  Token sEnd;
94887  DbFixer sFix;
94888  Token *pName = 0;
94889  int iDb;
94890  sqlite3 *db = pParse->db;
94891
94892  if( pParse->nVar>0 ){
94893    sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
94894    goto create_view_fail;
94895  }
94896  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
94897  p = pParse->pNewTable;
94898  if( p==0 || pParse->nErr ) goto create_view_fail;
94899  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
94900  iDb = sqlite3SchemaToIndex(db, p->pSchema);
94901  sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
94902  if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
94903
94904  /* Make a copy of the entire SELECT statement that defines the view.
94905  ** This will force all the Expr.token.z values to be dynamically
94906  ** allocated rather than point to the input string - which means that
94907  ** they will persist after the current sqlite3_exec() call returns.
94908  */
94909  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
94910  p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
94911  if( db->mallocFailed ) goto create_view_fail;
94912
94913  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
94914  ** the end.
94915  */
94916  sEnd = pParse->sLastToken;
94917  assert( sEnd.z[0]!=0 );
94918  if( sEnd.z[0]!=';' ){
94919    sEnd.z += sEnd.n;
94920  }
94921  sEnd.n = 0;
94922  n = (int)(sEnd.z - pBegin->z);
94923  assert( n>0 );
94924  z = pBegin->z;
94925  while( sqlite3Isspace(z[n-1]) ){ n--; }
94926  sEnd.z = &z[n-1];
94927  sEnd.n = 1;
94928
94929  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
94930  sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
94931
94932create_view_fail:
94933  sqlite3SelectDelete(db, pSelect);
94934  sqlite3ExprListDelete(db, pCNames);
94935  return;
94936}
94937#endif /* SQLITE_OMIT_VIEW */
94938
94939#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
94940/*
94941** The Table structure pTable is really a VIEW.  Fill in the names of
94942** the columns of the view in the pTable structure.  Return the number
94943** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
94944*/
94945SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
94946  Table *pSelTab;   /* A fake table from which we get the result set */
94947  Select *pSel;     /* Copy of the SELECT that implements the view */
94948  int nErr = 0;     /* Number of errors encountered */
94949  int n;            /* Temporarily holds the number of cursors assigned */
94950  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
94951  sqlite3_xauth xAuth;       /* Saved xAuth pointer */
94952  u8 bEnabledLA;             /* Saved db->lookaside.bEnabled state */
94953
94954  assert( pTable );
94955
94956#ifndef SQLITE_OMIT_VIRTUALTABLE
94957  if( sqlite3VtabCallConnect(pParse, pTable) ){
94958    return SQLITE_ERROR;
94959  }
94960  if( IsVirtual(pTable) ) return 0;
94961#endif
94962
94963#ifndef SQLITE_OMIT_VIEW
94964  /* A positive nCol means the columns names for this view are
94965  ** already known.
94966  */
94967  if( pTable->nCol>0 ) return 0;
94968
94969  /* A negative nCol is a special marker meaning that we are currently
94970  ** trying to compute the column names.  If we enter this routine with
94971  ** a negative nCol, it means two or more views form a loop, like this:
94972  **
94973  **     CREATE VIEW one AS SELECT * FROM two;
94974  **     CREATE VIEW two AS SELECT * FROM one;
94975  **
94976  ** Actually, the error above is now caught prior to reaching this point.
94977  ** But the following test is still important as it does come up
94978  ** in the following:
94979  **
94980  **     CREATE TABLE main.ex1(a);
94981  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
94982  **     SELECT * FROM temp.ex1;
94983  */
94984  if( pTable->nCol<0 ){
94985    sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
94986    return 1;
94987  }
94988  assert( pTable->nCol>=0 );
94989
94990  /* If we get this far, it means we need to compute the table names.
94991  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
94992  ** "*" elements in the results set of the view and will assign cursors
94993  ** to the elements of the FROM clause.  But we do not want these changes
94994  ** to be permanent.  So the computation is done on a copy of the SELECT
94995  ** statement that defines the view.
94996  */
94997  assert( pTable->pSelect );
94998  bEnabledLA = db->lookaside.bEnabled;
94999  if( pTable->pCheck ){
95000    db->lookaside.bEnabled = 0;
95001    sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
95002                               &pTable->nCol, &pTable->aCol);
95003  }else{
95004    pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
95005    if( pSel ){
95006      n = pParse->nTab;
95007      sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
95008      pTable->nCol = -1;
95009      db->lookaside.bEnabled = 0;
95010#ifndef SQLITE_OMIT_AUTHORIZATION
95011      xAuth = db->xAuth;
95012      db->xAuth = 0;
95013      pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
95014      db->xAuth = xAuth;
95015#else
95016      pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
95017#endif
95018      pParse->nTab = n;
95019      if( pSelTab ){
95020        assert( pTable->aCol==0 );
95021        pTable->nCol = pSelTab->nCol;
95022        pTable->aCol = pSelTab->aCol;
95023        pSelTab->nCol = 0;
95024        pSelTab->aCol = 0;
95025        sqlite3DeleteTable(db, pSelTab);
95026        assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
95027      }else{
95028        pTable->nCol = 0;
95029        nErr++;
95030      }
95031      sqlite3SelectDelete(db, pSel);
95032    } else {
95033      nErr++;
95034    }
95035  }
95036  db->lookaside.bEnabled = bEnabledLA;
95037  pTable->pSchema->schemaFlags |= DB_UnresetViews;
95038#endif /* SQLITE_OMIT_VIEW */
95039  return nErr;
95040}
95041#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
95042
95043#ifndef SQLITE_OMIT_VIEW
95044/*
95045** Clear the column names from every VIEW in database idx.
95046*/
95047static void sqliteViewResetAll(sqlite3 *db, int idx){
95048  HashElem *i;
95049  assert( sqlite3SchemaMutexHeld(db, idx, 0) );
95050  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
95051  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
95052    Table *pTab = sqliteHashData(i);
95053    if( pTab->pSelect ){
95054      sqlite3DeleteColumnNames(db, pTab);
95055      pTab->aCol = 0;
95056      pTab->nCol = 0;
95057    }
95058  }
95059  DbClearProperty(db, idx, DB_UnresetViews);
95060}
95061#else
95062# define sqliteViewResetAll(A,B)
95063#endif /* SQLITE_OMIT_VIEW */
95064
95065/*
95066** This function is called by the VDBE to adjust the internal schema
95067** used by SQLite when the btree layer moves a table root page. The
95068** root-page of a table or index in database iDb has changed from iFrom
95069** to iTo.
95070**
95071** Ticket #1728:  The symbol table might still contain information
95072** on tables and/or indices that are the process of being deleted.
95073** If you are unlucky, one of those deleted indices or tables might
95074** have the same rootpage number as the real table or index that is
95075** being moved.  So we cannot stop searching after the first match
95076** because the first match might be for one of the deleted indices
95077** or tables and not the table/index that is actually being moved.
95078** We must continue looping until all tables and indices with
95079** rootpage==iFrom have been converted to have a rootpage of iTo
95080** in order to be certain that we got the right one.
95081*/
95082#ifndef SQLITE_OMIT_AUTOVACUUM
95083SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
95084  HashElem *pElem;
95085  Hash *pHash;
95086  Db *pDb;
95087
95088  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95089  pDb = &db->aDb[iDb];
95090  pHash = &pDb->pSchema->tblHash;
95091  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
95092    Table *pTab = sqliteHashData(pElem);
95093    if( pTab->tnum==iFrom ){
95094      pTab->tnum = iTo;
95095    }
95096  }
95097  pHash = &pDb->pSchema->idxHash;
95098  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
95099    Index *pIdx = sqliteHashData(pElem);
95100    if( pIdx->tnum==iFrom ){
95101      pIdx->tnum = iTo;
95102    }
95103  }
95104}
95105#endif
95106
95107/*
95108** Write code to erase the table with root-page iTable from database iDb.
95109** Also write code to modify the sqlite_master table and internal schema
95110** if a root-page of another table is moved by the btree-layer whilst
95111** erasing iTable (this can happen with an auto-vacuum database).
95112*/
95113static void destroyRootPage(Parse *pParse, int iTable, int iDb){
95114  Vdbe *v = sqlite3GetVdbe(pParse);
95115  int r1 = sqlite3GetTempReg(pParse);
95116  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
95117  sqlite3MayAbort(pParse);
95118#ifndef SQLITE_OMIT_AUTOVACUUM
95119  /* OP_Destroy stores an in integer r1. If this integer
95120  ** is non-zero, then it is the root page number of a table moved to
95121  ** location iTable. The following code modifies the sqlite_master table to
95122  ** reflect this.
95123  **
95124  ** The "#NNN" in the SQL is a special constant that means whatever value
95125  ** is in register NNN.  See grammar rules associated with the TK_REGISTER
95126  ** token for additional information.
95127  */
95128  sqlite3NestedParse(pParse,
95129     "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
95130     pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
95131#endif
95132  sqlite3ReleaseTempReg(pParse, r1);
95133}
95134
95135/*
95136** Write VDBE code to erase table pTab and all associated indices on disk.
95137** Code to update the sqlite_master tables and internal schema definitions
95138** in case a root-page belonging to another table is moved by the btree layer
95139** is also added (this can happen with an auto-vacuum database).
95140*/
95141static void destroyTable(Parse *pParse, Table *pTab){
95142#ifdef SQLITE_OMIT_AUTOVACUUM
95143  Index *pIdx;
95144  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
95145  destroyRootPage(pParse, pTab->tnum, iDb);
95146  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
95147    destroyRootPage(pParse, pIdx->tnum, iDb);
95148  }
95149#else
95150  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
95151  ** is not defined), then it is important to call OP_Destroy on the
95152  ** table and index root-pages in order, starting with the numerically
95153  ** largest root-page number. This guarantees that none of the root-pages
95154  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
95155  ** following were coded:
95156  **
95157  ** OP_Destroy 4 0
95158  ** ...
95159  ** OP_Destroy 5 0
95160  **
95161  ** and root page 5 happened to be the largest root-page number in the
95162  ** database, then root page 5 would be moved to page 4 by the
95163  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
95164  ** a free-list page.
95165  */
95166  int iTab = pTab->tnum;
95167  int iDestroyed = 0;
95168
95169  while( 1 ){
95170    Index *pIdx;
95171    int iLargest = 0;
95172
95173    if( iDestroyed==0 || iTab<iDestroyed ){
95174      iLargest = iTab;
95175    }
95176    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
95177      int iIdx = pIdx->tnum;
95178      assert( pIdx->pSchema==pTab->pSchema );
95179      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
95180        iLargest = iIdx;
95181      }
95182    }
95183    if( iLargest==0 ){
95184      return;
95185    }else{
95186      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
95187      assert( iDb>=0 && iDb<pParse->db->nDb );
95188      destroyRootPage(pParse, iLargest, iDb);
95189      iDestroyed = iLargest;
95190    }
95191  }
95192#endif
95193}
95194
95195/*
95196** Remove entries from the sqlite_statN tables (for N in (1,2,3))
95197** after a DROP INDEX or DROP TABLE command.
95198*/
95199static void sqlite3ClearStatTables(
95200  Parse *pParse,         /* The parsing context */
95201  int iDb,               /* The database number */
95202  const char *zType,     /* "idx" or "tbl" */
95203  const char *zName      /* Name of index or table */
95204){
95205  int i;
95206  const char *zDbName = pParse->db->aDb[iDb].zName;
95207  for(i=1; i<=4; i++){
95208    char zTab[24];
95209    sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
95210    if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
95211      sqlite3NestedParse(pParse,
95212        "DELETE FROM %Q.%s WHERE %s=%Q",
95213        zDbName, zTab, zType, zName
95214      );
95215    }
95216  }
95217}
95218
95219/*
95220** Generate code to drop a table.
95221*/
95222SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
95223  Vdbe *v;
95224  sqlite3 *db = pParse->db;
95225  Trigger *pTrigger;
95226  Db *pDb = &db->aDb[iDb];
95227
95228  v = sqlite3GetVdbe(pParse);
95229  assert( v!=0 );
95230  sqlite3BeginWriteOperation(pParse, 1, iDb);
95231
95232#ifndef SQLITE_OMIT_VIRTUALTABLE
95233  if( IsVirtual(pTab) ){
95234    sqlite3VdbeAddOp0(v, OP_VBegin);
95235  }
95236#endif
95237
95238  /* Drop all triggers associated with the table being dropped. Code
95239  ** is generated to remove entries from sqlite_master and/or
95240  ** sqlite_temp_master if required.
95241  */
95242  pTrigger = sqlite3TriggerList(pParse, pTab);
95243  while( pTrigger ){
95244    assert( pTrigger->pSchema==pTab->pSchema ||
95245        pTrigger->pSchema==db->aDb[1].pSchema );
95246    sqlite3DropTriggerPtr(pParse, pTrigger);
95247    pTrigger = pTrigger->pNext;
95248  }
95249
95250#ifndef SQLITE_OMIT_AUTOINCREMENT
95251  /* Remove any entries of the sqlite_sequence table associated with
95252  ** the table being dropped. This is done before the table is dropped
95253  ** at the btree level, in case the sqlite_sequence table needs to
95254  ** move as a result of the drop (can happen in auto-vacuum mode).
95255  */
95256  if( pTab->tabFlags & TF_Autoincrement ){
95257    sqlite3NestedParse(pParse,
95258      "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
95259      pDb->zName, pTab->zName
95260    );
95261  }
95262#endif
95263
95264  /* Drop all SQLITE_MASTER table and index entries that refer to the
95265  ** table. The program name loops through the master table and deletes
95266  ** every row that refers to a table of the same name as the one being
95267  ** dropped. Triggers are handled separately because a trigger can be
95268  ** created in the temp database that refers to a table in another
95269  ** database.
95270  */
95271  sqlite3NestedParse(pParse,
95272      "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
95273      pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
95274  if( !isView && !IsVirtual(pTab) ){
95275    destroyTable(pParse, pTab);
95276  }
95277
95278  /* Remove the table entry from SQLite's internal schema and modify
95279  ** the schema cookie.
95280  */
95281  if( IsVirtual(pTab) ){
95282    sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
95283  }
95284  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
95285  sqlite3ChangeCookie(pParse, iDb);
95286  sqliteViewResetAll(db, iDb);
95287}
95288
95289/*
95290** This routine is called to do the work of a DROP TABLE statement.
95291** pName is the name of the table to be dropped.
95292*/
95293SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
95294  Table *pTab;
95295  Vdbe *v;
95296  sqlite3 *db = pParse->db;
95297  int iDb;
95298
95299  if( db->mallocFailed ){
95300    goto exit_drop_table;
95301  }
95302  assert( pParse->nErr==0 );
95303  assert( pName->nSrc==1 );
95304  if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
95305  if( noErr ) db->suppressErr++;
95306  pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
95307  if( noErr ) db->suppressErr--;
95308
95309  if( pTab==0 ){
95310    if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
95311    goto exit_drop_table;
95312  }
95313  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
95314  assert( iDb>=0 && iDb<db->nDb );
95315
95316  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
95317  ** it is initialized.
95318  */
95319  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
95320    goto exit_drop_table;
95321  }
95322#ifndef SQLITE_OMIT_AUTHORIZATION
95323  {
95324    int code;
95325    const char *zTab = SCHEMA_TABLE(iDb);
95326    const char *zDb = db->aDb[iDb].zName;
95327    const char *zArg2 = 0;
95328    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
95329      goto exit_drop_table;
95330    }
95331    if( isView ){
95332      if( !OMIT_TEMPDB && iDb==1 ){
95333        code = SQLITE_DROP_TEMP_VIEW;
95334      }else{
95335        code = SQLITE_DROP_VIEW;
95336      }
95337#ifndef SQLITE_OMIT_VIRTUALTABLE
95338    }else if( IsVirtual(pTab) ){
95339      code = SQLITE_DROP_VTABLE;
95340      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
95341#endif
95342    }else{
95343      if( !OMIT_TEMPDB && iDb==1 ){
95344        code = SQLITE_DROP_TEMP_TABLE;
95345      }else{
95346        code = SQLITE_DROP_TABLE;
95347      }
95348    }
95349    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
95350      goto exit_drop_table;
95351    }
95352    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
95353      goto exit_drop_table;
95354    }
95355  }
95356#endif
95357  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
95358    && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
95359    sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
95360    goto exit_drop_table;
95361  }
95362
95363#ifndef SQLITE_OMIT_VIEW
95364  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
95365  ** on a table.
95366  */
95367  if( isView && pTab->pSelect==0 ){
95368    sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
95369    goto exit_drop_table;
95370  }
95371  if( !isView && pTab->pSelect ){
95372    sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
95373    goto exit_drop_table;
95374  }
95375#endif
95376
95377  /* Generate code to remove the table from the master table
95378  ** on disk.
95379  */
95380  v = sqlite3GetVdbe(pParse);
95381  if( v ){
95382    sqlite3BeginWriteOperation(pParse, 1, iDb);
95383    sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
95384    sqlite3FkDropTable(pParse, pName, pTab);
95385    sqlite3CodeDropTable(pParse, pTab, iDb, isView);
95386  }
95387
95388exit_drop_table:
95389  sqlite3SrcListDelete(db, pName);
95390}
95391
95392/*
95393** This routine is called to create a new foreign key on the table
95394** currently under construction.  pFromCol determines which columns
95395** in the current table point to the foreign key.  If pFromCol==0 then
95396** connect the key to the last column inserted.  pTo is the name of
95397** the table referred to (a.k.a the "parent" table).  pToCol is a list
95398** of tables in the parent pTo table.  flags contains all
95399** information about the conflict resolution algorithms specified
95400** in the ON DELETE, ON UPDATE and ON INSERT clauses.
95401**
95402** An FKey structure is created and added to the table currently
95403** under construction in the pParse->pNewTable field.
95404**
95405** The foreign key is set for IMMEDIATE processing.  A subsequent call
95406** to sqlite3DeferForeignKey() might change this to DEFERRED.
95407*/
95408SQLITE_PRIVATE void sqlite3CreateForeignKey(
95409  Parse *pParse,       /* Parsing context */
95410  ExprList *pFromCol,  /* Columns in this table that point to other table */
95411  Token *pTo,          /* Name of the other table */
95412  ExprList *pToCol,    /* Columns in the other table */
95413  int flags            /* Conflict resolution algorithms. */
95414){
95415  sqlite3 *db = pParse->db;
95416#ifndef SQLITE_OMIT_FOREIGN_KEY
95417  FKey *pFKey = 0;
95418  FKey *pNextTo;
95419  Table *p = pParse->pNewTable;
95420  int nByte;
95421  int i;
95422  int nCol;
95423  char *z;
95424
95425  assert( pTo!=0 );
95426  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
95427  if( pFromCol==0 ){
95428    int iCol = p->nCol-1;
95429    if( NEVER(iCol<0) ) goto fk_end;
95430    if( pToCol && pToCol->nExpr!=1 ){
95431      sqlite3ErrorMsg(pParse, "foreign key on %s"
95432         " should reference only one column of table %T",
95433         p->aCol[iCol].zName, pTo);
95434      goto fk_end;
95435    }
95436    nCol = 1;
95437  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
95438    sqlite3ErrorMsg(pParse,
95439        "number of columns in foreign key does not match the number of "
95440        "columns in the referenced table");
95441    goto fk_end;
95442  }else{
95443    nCol = pFromCol->nExpr;
95444  }
95445  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
95446  if( pToCol ){
95447    for(i=0; i<pToCol->nExpr; i++){
95448      nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
95449    }
95450  }
95451  pFKey = sqlite3DbMallocZero(db, nByte );
95452  if( pFKey==0 ){
95453    goto fk_end;
95454  }
95455  pFKey->pFrom = p;
95456  pFKey->pNextFrom = p->pFKey;
95457  z = (char*)&pFKey->aCol[nCol];
95458  pFKey->zTo = z;
95459  memcpy(z, pTo->z, pTo->n);
95460  z[pTo->n] = 0;
95461  sqlite3Dequote(z);
95462  z += pTo->n+1;
95463  pFKey->nCol = nCol;
95464  if( pFromCol==0 ){
95465    pFKey->aCol[0].iFrom = p->nCol-1;
95466  }else{
95467    for(i=0; i<nCol; i++){
95468      int j;
95469      for(j=0; j<p->nCol; j++){
95470        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
95471          pFKey->aCol[i].iFrom = j;
95472          break;
95473        }
95474      }
95475      if( j>=p->nCol ){
95476        sqlite3ErrorMsg(pParse,
95477          "unknown column \"%s\" in foreign key definition",
95478          pFromCol->a[i].zName);
95479        goto fk_end;
95480      }
95481    }
95482  }
95483  if( pToCol ){
95484    for(i=0; i<nCol; i++){
95485      int n = sqlite3Strlen30(pToCol->a[i].zName);
95486      pFKey->aCol[i].zCol = z;
95487      memcpy(z, pToCol->a[i].zName, n);
95488      z[n] = 0;
95489      z += n+1;
95490    }
95491  }
95492  pFKey->isDeferred = 0;
95493  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
95494  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
95495
95496  assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
95497  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
95498      pFKey->zTo, (void *)pFKey
95499  );
95500  if( pNextTo==pFKey ){
95501    db->mallocFailed = 1;
95502    goto fk_end;
95503  }
95504  if( pNextTo ){
95505    assert( pNextTo->pPrevTo==0 );
95506    pFKey->pNextTo = pNextTo;
95507    pNextTo->pPrevTo = pFKey;
95508  }
95509
95510  /* Link the foreign key to the table as the last step.
95511  */
95512  p->pFKey = pFKey;
95513  pFKey = 0;
95514
95515fk_end:
95516  sqlite3DbFree(db, pFKey);
95517#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
95518  sqlite3ExprListDelete(db, pFromCol);
95519  sqlite3ExprListDelete(db, pToCol);
95520}
95521
95522/*
95523** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
95524** clause is seen as part of a foreign key definition.  The isDeferred
95525** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
95526** The behavior of the most recently created foreign key is adjusted
95527** accordingly.
95528*/
95529SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
95530#ifndef SQLITE_OMIT_FOREIGN_KEY
95531  Table *pTab;
95532  FKey *pFKey;
95533  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
95534  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
95535  pFKey->isDeferred = (u8)isDeferred;
95536#endif
95537}
95538
95539/*
95540** Generate code that will erase and refill index *pIdx.  This is
95541** used to initialize a newly created index or to recompute the
95542** content of an index in response to a REINDEX command.
95543**
95544** if memRootPage is not negative, it means that the index is newly
95545** created.  The register specified by memRootPage contains the
95546** root page number of the index.  If memRootPage is negative, then
95547** the index already exists and must be cleared before being refilled and
95548** the root page number of the index is taken from pIndex->tnum.
95549*/
95550static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
95551  Table *pTab = pIndex->pTable;  /* The table that is indexed */
95552  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
95553  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
95554  int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
95555  int addr1;                     /* Address of top of loop */
95556  int addr2;                     /* Address to jump to for next iteration */
95557  int tnum;                      /* Root page of index */
95558  int iPartIdxLabel;             /* Jump to this label to skip a row */
95559  Vdbe *v;                       /* Generate code into this virtual machine */
95560  KeyInfo *pKey;                 /* KeyInfo for index */
95561  int regRecord;                 /* Register holding assembled index record */
95562  sqlite3 *db = pParse->db;      /* The database connection */
95563  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
95564
95565#ifndef SQLITE_OMIT_AUTHORIZATION
95566  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
95567      db->aDb[iDb].zName ) ){
95568    return;
95569  }
95570#endif
95571
95572  /* Require a write-lock on the table to perform this operation */
95573  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
95574
95575  v = sqlite3GetVdbe(pParse);
95576  if( v==0 ) return;
95577  if( memRootPage>=0 ){
95578    tnum = memRootPage;
95579  }else{
95580    tnum = pIndex->tnum;
95581  }
95582  pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
95583
95584  /* Open the sorter cursor if we are to use one. */
95585  iSorter = pParse->nTab++;
95586  sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
95587                    sqlite3KeyInfoRef(pKey), P4_KEYINFO);
95588
95589  /* Open the table. Loop through all rows of the table, inserting index
95590  ** records into the sorter. */
95591  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
95592  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
95593  regRecord = sqlite3GetTempReg(pParse);
95594
95595  sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
95596  sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
95597  sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
95598  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
95599  sqlite3VdbeJumpHere(v, addr1);
95600  if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
95601  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
95602                    (char *)pKey, P4_KEYINFO);
95603  sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
95604
95605  addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
95606  assert( pKey!=0 || db->mallocFailed || pParse->nErr );
95607  if( IsUniqueIndex(pIndex) && pKey!=0 ){
95608    int j2 = sqlite3VdbeCurrentAddr(v) + 3;
95609    sqlite3VdbeGoto(v, j2);
95610    addr2 = sqlite3VdbeCurrentAddr(v);
95611    sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
95612                         pIndex->nKeyCol); VdbeCoverage(v);
95613    sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
95614  }else{
95615    addr2 = sqlite3VdbeCurrentAddr(v);
95616  }
95617  sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
95618  sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
95619  sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
95620  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
95621  sqlite3ReleaseTempReg(pParse, regRecord);
95622  sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
95623  sqlite3VdbeJumpHere(v, addr1);
95624
95625  sqlite3VdbeAddOp1(v, OP_Close, iTab);
95626  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
95627  sqlite3VdbeAddOp1(v, OP_Close, iSorter);
95628}
95629
95630/*
95631** Allocate heap space to hold an Index object with nCol columns.
95632**
95633** Increase the allocation size to provide an extra nExtra bytes
95634** of 8-byte aligned space after the Index object and return a
95635** pointer to this extra space in *ppExtra.
95636*/
95637SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
95638  sqlite3 *db,         /* Database connection */
95639  i16 nCol,            /* Total number of columns in the index */
95640  int nExtra,          /* Number of bytes of extra space to alloc */
95641  char **ppExtra       /* Pointer to the "extra" space */
95642){
95643  Index *p;            /* Allocated index object */
95644  int nByte;           /* Bytes of space for Index object + arrays */
95645
95646  nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
95647          ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
95648          ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
95649                 sizeof(i16)*nCol +            /* Index.aiColumn   */
95650                 sizeof(u8)*nCol);             /* Index.aSortOrder */
95651  p = sqlite3DbMallocZero(db, nByte + nExtra);
95652  if( p ){
95653    char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
95654    p->azColl = (char**)pExtra;       pExtra += ROUND8(sizeof(char*)*nCol);
95655    p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
95656    p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
95657    p->aSortOrder = (u8*)pExtra;
95658    p->nColumn = nCol;
95659    p->nKeyCol = nCol - 1;
95660    *ppExtra = ((char*)p) + nByte;
95661  }
95662  return p;
95663}
95664
95665/*
95666** Create a new index for an SQL table.  pName1.pName2 is the name of the index
95667** and pTblList is the name of the table that is to be indexed.  Both will
95668** be NULL for a primary key or an index that is created to satisfy a
95669** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
95670** as the table to be indexed.  pParse->pNewTable is a table that is
95671** currently being constructed by a CREATE TABLE statement.
95672**
95673** pList is a list of columns to be indexed.  pList will be NULL if this
95674** is a primary key or unique-constraint on the most recent column added
95675** to the table currently under construction.
95676**
95677** If the index is created successfully, return a pointer to the new Index
95678** structure. This is used by sqlite3AddPrimaryKey() to mark the index
95679** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
95680*/
95681SQLITE_PRIVATE Index *sqlite3CreateIndex(
95682  Parse *pParse,     /* All information about this parse */
95683  Token *pName1,     /* First part of index name. May be NULL */
95684  Token *pName2,     /* Second part of index name. May be NULL */
95685  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
95686  ExprList *pList,   /* A list of columns to be indexed */
95687  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
95688  Token *pStart,     /* The CREATE token that begins this statement */
95689  Expr *pPIWhere,    /* WHERE clause for partial indices */
95690  int sortOrder,     /* Sort order of primary key when pList==NULL */
95691  int ifNotExist     /* Omit error if index already exists */
95692){
95693  Index *pRet = 0;     /* Pointer to return */
95694  Table *pTab = 0;     /* Table to be indexed */
95695  Index *pIndex = 0;   /* The index to be created */
95696  char *zName = 0;     /* Name of the index */
95697  int nName;           /* Number of characters in zName */
95698  int i, j;
95699  DbFixer sFix;        /* For assigning database names to pTable */
95700  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
95701  sqlite3 *db = pParse->db;
95702  Db *pDb;             /* The specific table containing the indexed database */
95703  int iDb;             /* Index of the database that is being written */
95704  Token *pName = 0;    /* Unqualified name of the index to create */
95705  struct ExprList_item *pListItem; /* For looping over pList */
95706  int nExtra = 0;                  /* Space allocated for zExtra[] */
95707  int nExtraCol;                   /* Number of extra columns needed */
95708  char *zExtra = 0;                /* Extra space after the Index object */
95709  Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
95710
95711  if( db->mallocFailed || IN_DECLARE_VTAB || pParse->nErr>0 ){
95712    goto exit_create_index;
95713  }
95714  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
95715    goto exit_create_index;
95716  }
95717
95718  /*
95719  ** Find the table that is to be indexed.  Return early if not found.
95720  */
95721  if( pTblName!=0 ){
95722
95723    /* Use the two-part index name to determine the database
95724    ** to search for the table. 'Fix' the table name to this db
95725    ** before looking up the table.
95726    */
95727    assert( pName1 && pName2 );
95728    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
95729    if( iDb<0 ) goto exit_create_index;
95730    assert( pName && pName->z );
95731
95732#ifndef SQLITE_OMIT_TEMPDB
95733    /* If the index name was unqualified, check if the table
95734    ** is a temp table. If so, set the database to 1. Do not do this
95735    ** if initialising a database schema.
95736    */
95737    if( !db->init.busy ){
95738      pTab = sqlite3SrcListLookup(pParse, pTblName);
95739      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
95740        iDb = 1;
95741      }
95742    }
95743#endif
95744
95745    sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
95746    if( sqlite3FixSrcList(&sFix, pTblName) ){
95747      /* Because the parser constructs pTblName from a single identifier,
95748      ** sqlite3FixSrcList can never fail. */
95749      assert(0);
95750    }
95751    pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
95752    assert( db->mallocFailed==0 || pTab==0 );
95753    if( pTab==0 ) goto exit_create_index;
95754    if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
95755      sqlite3ErrorMsg(pParse,
95756           "cannot create a TEMP index on non-TEMP table \"%s\"",
95757           pTab->zName);
95758      goto exit_create_index;
95759    }
95760    if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
95761  }else{
95762    assert( pName==0 );
95763    assert( pStart==0 );
95764    pTab = pParse->pNewTable;
95765    if( !pTab ) goto exit_create_index;
95766    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
95767  }
95768  pDb = &db->aDb[iDb];
95769
95770  assert( pTab!=0 );
95771  assert( pParse->nErr==0 );
95772  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
95773       && db->init.busy==0
95774#if SQLITE_USER_AUTHENTICATION
95775       && sqlite3UserAuthTable(pTab->zName)==0
95776#endif
95777       && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
95778    sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
95779    goto exit_create_index;
95780  }
95781#ifndef SQLITE_OMIT_VIEW
95782  if( pTab->pSelect ){
95783    sqlite3ErrorMsg(pParse, "views may not be indexed");
95784    goto exit_create_index;
95785  }
95786#endif
95787#ifndef SQLITE_OMIT_VIRTUALTABLE
95788  if( IsVirtual(pTab) ){
95789    sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
95790    goto exit_create_index;
95791  }
95792#endif
95793
95794  /*
95795  ** Find the name of the index.  Make sure there is not already another
95796  ** index or table with the same name.
95797  **
95798  ** Exception:  If we are reading the names of permanent indices from the
95799  ** sqlite_master table (because some other process changed the schema) and
95800  ** one of the index names collides with the name of a temporary table or
95801  ** index, then we will continue to process this index.
95802  **
95803  ** If pName==0 it means that we are
95804  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
95805  ** own name.
95806  */
95807  if( pName ){
95808    zName = sqlite3NameFromToken(db, pName);
95809    if( zName==0 ) goto exit_create_index;
95810    assert( pName->z!=0 );
95811    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
95812      goto exit_create_index;
95813    }
95814    if( !db->init.busy ){
95815      if( sqlite3FindTable(db, zName, 0)!=0 ){
95816        sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
95817        goto exit_create_index;
95818      }
95819    }
95820    if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
95821      if( !ifNotExist ){
95822        sqlite3ErrorMsg(pParse, "index %s already exists", zName);
95823      }else{
95824        assert( !db->init.busy );
95825        sqlite3CodeVerifySchema(pParse, iDb);
95826      }
95827      goto exit_create_index;
95828    }
95829  }else{
95830    int n;
95831    Index *pLoop;
95832    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
95833    zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
95834    if( zName==0 ){
95835      goto exit_create_index;
95836    }
95837  }
95838
95839  /* Check for authorization to create an index.
95840  */
95841#ifndef SQLITE_OMIT_AUTHORIZATION
95842  {
95843    const char *zDb = pDb->zName;
95844    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
95845      goto exit_create_index;
95846    }
95847    i = SQLITE_CREATE_INDEX;
95848    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
95849    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
95850      goto exit_create_index;
95851    }
95852  }
95853#endif
95854
95855  /* If pList==0, it means this routine was called to make a primary
95856  ** key out of the last column added to the table under construction.
95857  ** So create a fake list to simulate this.
95858  */
95859  if( pList==0 ){
95860    Token prevCol;
95861    prevCol.z = pTab->aCol[pTab->nCol-1].zName;
95862    prevCol.n = sqlite3Strlen30(prevCol.z);
95863    pList = sqlite3ExprListAppend(pParse, 0,
95864              sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
95865    if( pList==0 ) goto exit_create_index;
95866    assert( pList->nExpr==1 );
95867    sqlite3ExprListSetSortOrder(pList, sortOrder);
95868  }else{
95869    sqlite3ExprListCheckLength(pParse, pList, "index");
95870  }
95871
95872  /* Figure out how many bytes of space are required to store explicitly
95873  ** specified collation sequence names.
95874  */
95875  for(i=0; i<pList->nExpr; i++){
95876    Expr *pExpr = pList->a[i].pExpr;
95877    assert( pExpr!=0 );
95878    if( pExpr->op==TK_COLLATE ){
95879      nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
95880    }
95881  }
95882
95883  /*
95884  ** Allocate the index structure.
95885  */
95886  nName = sqlite3Strlen30(zName);
95887  nExtraCol = pPk ? pPk->nKeyCol : 1;
95888  pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
95889                                      nName + nExtra + 1, &zExtra);
95890  if( db->mallocFailed ){
95891    goto exit_create_index;
95892  }
95893  assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
95894  assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
95895  pIndex->zName = zExtra;
95896  zExtra += nName + 1;
95897  memcpy(pIndex->zName, zName, nName+1);
95898  pIndex->pTable = pTab;
95899  pIndex->onError = (u8)onError;
95900  pIndex->uniqNotNull = onError!=OE_None;
95901  pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
95902  pIndex->pSchema = db->aDb[iDb].pSchema;
95903  pIndex->nKeyCol = pList->nExpr;
95904  if( pPIWhere ){
95905    sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
95906    pIndex->pPartIdxWhere = pPIWhere;
95907    pPIWhere = 0;
95908  }
95909  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95910
95911  /* Check to see if we should honor DESC requests on index columns
95912  */
95913  if( pDb->pSchema->file_format>=4 ){
95914    sortOrderMask = -1;   /* Honor DESC */
95915  }else{
95916    sortOrderMask = 0;    /* Ignore DESC */
95917  }
95918
95919  /* Analyze the list of expressions that form the terms of the index and
95920  ** report any errors.  In the common case where the expression is exactly
95921  ** a table column, store that column in aiColumn[].  For general expressions,
95922  ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
95923  **
95924  ** TODO: Issue a warning if two or more columns of the index are identical.
95925  ** TODO: Issue a warning if the table primary key is used as part of the
95926  ** index key.
95927  */
95928  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
95929    Expr *pCExpr;                  /* The i-th index expression */
95930    int requestedSortOrder;        /* ASC or DESC on the i-th expression */
95931    char *zColl;                   /* Collation sequence name */
95932
95933    sqlite3StringToId(pListItem->pExpr);
95934    sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
95935    if( pParse->nErr ) goto exit_create_index;
95936    pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
95937    if( pCExpr->op!=TK_COLUMN ){
95938      if( pTab==pParse->pNewTable ){
95939        sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
95940                                "UNIQUE constraints");
95941        goto exit_create_index;
95942      }
95943      if( pIndex->aColExpr==0 ){
95944        ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
95945        pIndex->aColExpr = pCopy;
95946        if( !db->mallocFailed ){
95947          assert( pCopy!=0 );
95948          pListItem = &pCopy->a[i];
95949        }
95950      }
95951      j = XN_EXPR;
95952      pIndex->aiColumn[i] = XN_EXPR;
95953      pIndex->uniqNotNull = 0;
95954    }else{
95955      j = pCExpr->iColumn;
95956      assert( j<=0x7fff );
95957      if( j<0 ){
95958        j = pTab->iPKey;
95959      }else if( pTab->aCol[j].notNull==0 ){
95960        pIndex->uniqNotNull = 0;
95961      }
95962      pIndex->aiColumn[i] = (i16)j;
95963    }
95964    zColl = 0;
95965    if( pListItem->pExpr->op==TK_COLLATE ){
95966      int nColl;
95967      zColl = pListItem->pExpr->u.zToken;
95968      nColl = sqlite3Strlen30(zColl) + 1;
95969      assert( nExtra>=nColl );
95970      memcpy(zExtra, zColl, nColl);
95971      zColl = zExtra;
95972      zExtra += nColl;
95973      nExtra -= nColl;
95974    }else if( j>=0 ){
95975      zColl = pTab->aCol[j].zColl;
95976    }
95977    if( !zColl ) zColl = "BINARY";
95978    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
95979      goto exit_create_index;
95980    }
95981    pIndex->azColl[i] = zColl;
95982    requestedSortOrder = pListItem->sortOrder & sortOrderMask;
95983    pIndex->aSortOrder[i] = (u8)requestedSortOrder;
95984  }
95985
95986  /* Append the table key to the end of the index.  For WITHOUT ROWID
95987  ** tables (when pPk!=0) this will be the declared PRIMARY KEY.  For
95988  ** normal tables (when pPk==0) this will be the rowid.
95989  */
95990  if( pPk ){
95991    for(j=0; j<pPk->nKeyCol; j++){
95992      int x = pPk->aiColumn[j];
95993      assert( x>=0 );
95994      if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
95995        pIndex->nColumn--;
95996      }else{
95997        pIndex->aiColumn[i] = x;
95998        pIndex->azColl[i] = pPk->azColl[j];
95999        pIndex->aSortOrder[i] = pPk->aSortOrder[j];
96000        i++;
96001      }
96002    }
96003    assert( i==pIndex->nColumn );
96004  }else{
96005    pIndex->aiColumn[i] = XN_ROWID;
96006    pIndex->azColl[i] = "BINARY";
96007  }
96008  sqlite3DefaultRowEst(pIndex);
96009  if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
96010
96011  if( pTab==pParse->pNewTable ){
96012    /* This routine has been called to create an automatic index as a
96013    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
96014    ** a PRIMARY KEY or UNIQUE clause following the column definitions.
96015    ** i.e. one of:
96016    **
96017    ** CREATE TABLE t(x PRIMARY KEY, y);
96018    ** CREATE TABLE t(x, y, UNIQUE(x, y));
96019    **
96020    ** Either way, check to see if the table already has such an index. If
96021    ** so, don't bother creating this one. This only applies to
96022    ** automatically created indices. Users can do as they wish with
96023    ** explicit indices.
96024    **
96025    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
96026    ** (and thus suppressing the second one) even if they have different
96027    ** sort orders.
96028    **
96029    ** If there are different collating sequences or if the columns of
96030    ** the constraint occur in different orders, then the constraints are
96031    ** considered distinct and both result in separate indices.
96032    */
96033    Index *pIdx;
96034    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
96035      int k;
96036      assert( IsUniqueIndex(pIdx) );
96037      assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
96038      assert( IsUniqueIndex(pIndex) );
96039
96040      if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
96041      for(k=0; k<pIdx->nKeyCol; k++){
96042        const char *z1;
96043        const char *z2;
96044        assert( pIdx->aiColumn[k]>=0 );
96045        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
96046        z1 = pIdx->azColl[k];
96047        z2 = pIndex->azColl[k];
96048        if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
96049      }
96050      if( k==pIdx->nKeyCol ){
96051        if( pIdx->onError!=pIndex->onError ){
96052          /* This constraint creates the same index as a previous
96053          ** constraint specified somewhere in the CREATE TABLE statement.
96054          ** However the ON CONFLICT clauses are different. If both this
96055          ** constraint and the previous equivalent constraint have explicit
96056          ** ON CONFLICT clauses this is an error. Otherwise, use the
96057          ** explicitly specified behavior for the index.
96058          */
96059          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
96060            sqlite3ErrorMsg(pParse,
96061                "conflicting ON CONFLICT clauses specified", 0);
96062          }
96063          if( pIdx->onError==OE_Default ){
96064            pIdx->onError = pIndex->onError;
96065          }
96066        }
96067        pRet = pIdx;
96068        goto exit_create_index;
96069      }
96070    }
96071  }
96072
96073  /* Link the new Index structure to its table and to the other
96074  ** in-memory database structures.
96075  */
96076  assert( pParse->nErr==0 );
96077  if( db->init.busy ){
96078    Index *p;
96079    assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
96080    p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
96081                          pIndex->zName, pIndex);
96082    if( p ){
96083      assert( p==pIndex );  /* Malloc must have failed */
96084      db->mallocFailed = 1;
96085      goto exit_create_index;
96086    }
96087    db->flags |= SQLITE_InternChanges;
96088    if( pTblName!=0 ){
96089      pIndex->tnum = db->init.newTnum;
96090    }
96091  }
96092
96093  /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
96094  ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
96095  ** emit code to allocate the index rootpage on disk and make an entry for
96096  ** the index in the sqlite_master table and populate the index with
96097  ** content.  But, do not do this if we are simply reading the sqlite_master
96098  ** table to parse the schema, or if this index is the PRIMARY KEY index
96099  ** of a WITHOUT ROWID table.
96100  **
96101  ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
96102  ** or UNIQUE index in a CREATE TABLE statement.  Since the table
96103  ** has just been created, it contains no data and the index initialization
96104  ** step can be skipped.
96105  */
96106  else if( HasRowid(pTab) || pTblName!=0 ){
96107    Vdbe *v;
96108    char *zStmt;
96109    int iMem = ++pParse->nMem;
96110
96111    v = sqlite3GetVdbe(pParse);
96112    if( v==0 ) goto exit_create_index;
96113
96114    sqlite3BeginWriteOperation(pParse, 1, iDb);
96115
96116    /* Create the rootpage for the index using CreateIndex. But before
96117    ** doing so, code a Noop instruction and store its address in
96118    ** Index.tnum. This is required in case this index is actually a
96119    ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
96120    ** that case the convertToWithoutRowidTable() routine will replace
96121    ** the Noop with a Goto to jump over the VDBE code generated below. */
96122    pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
96123    sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
96124
96125    /* Gather the complete text of the CREATE INDEX statement into
96126    ** the zStmt variable
96127    */
96128    if( pStart ){
96129      int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
96130      if( pName->z[n-1]==';' ) n--;
96131      /* A named index with an explicit CREATE INDEX statement */
96132      zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
96133        onError==OE_None ? "" : " UNIQUE", n, pName->z);
96134    }else{
96135      /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
96136      /* zStmt = sqlite3MPrintf(""); */
96137      zStmt = 0;
96138    }
96139
96140    /* Add an entry in sqlite_master for this index
96141    */
96142    sqlite3NestedParse(pParse,
96143        "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
96144        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
96145        pIndex->zName,
96146        pTab->zName,
96147        iMem,
96148        zStmt
96149    );
96150    sqlite3DbFree(db, zStmt);
96151
96152    /* Fill the index with data and reparse the schema. Code an OP_Expire
96153    ** to invalidate all pre-compiled statements.
96154    */
96155    if( pTblName ){
96156      sqlite3RefillIndex(pParse, pIndex, iMem);
96157      sqlite3ChangeCookie(pParse, iDb);
96158      sqlite3VdbeAddParseSchemaOp(v, iDb,
96159         sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
96160      sqlite3VdbeAddOp1(v, OP_Expire, 0);
96161    }
96162
96163    sqlite3VdbeJumpHere(v, pIndex->tnum);
96164  }
96165
96166  /* When adding an index to the list of indices for a table, make
96167  ** sure all indices labeled OE_Replace come after all those labeled
96168  ** OE_Ignore.  This is necessary for the correct constraint check
96169  ** processing (in sqlite3GenerateConstraintChecks()) as part of
96170  ** UPDATE and INSERT statements.
96171  */
96172  if( db->init.busy || pTblName==0 ){
96173    if( onError!=OE_Replace || pTab->pIndex==0
96174         || pTab->pIndex->onError==OE_Replace){
96175      pIndex->pNext = pTab->pIndex;
96176      pTab->pIndex = pIndex;
96177    }else{
96178      Index *pOther = pTab->pIndex;
96179      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
96180        pOther = pOther->pNext;
96181      }
96182      pIndex->pNext = pOther->pNext;
96183      pOther->pNext = pIndex;
96184    }
96185    pRet = pIndex;
96186    pIndex = 0;
96187  }
96188
96189  /* Clean up before exiting */
96190exit_create_index:
96191  if( pIndex ) freeIndex(db, pIndex);
96192  sqlite3ExprDelete(db, pPIWhere);
96193  sqlite3ExprListDelete(db, pList);
96194  sqlite3SrcListDelete(db, pTblName);
96195  sqlite3DbFree(db, zName);
96196  return pRet;
96197}
96198
96199/*
96200** Fill the Index.aiRowEst[] array with default information - information
96201** to be used when we have not run the ANALYZE command.
96202**
96203** aiRowEst[0] is supposed to contain the number of elements in the index.
96204** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
96205** number of rows in the table that match any particular value of the
96206** first column of the index.  aiRowEst[2] is an estimate of the number
96207** of rows that match any particular combination of the first 2 columns
96208** of the index.  And so forth.  It must always be the case that
96209*
96210**           aiRowEst[N]<=aiRowEst[N-1]
96211**           aiRowEst[N]>=1
96212**
96213** Apart from that, we have little to go on besides intuition as to
96214** how aiRowEst[] should be initialized.  The numbers generated here
96215** are based on typical values found in actual indices.
96216*/
96217SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
96218  /*                10,  9,  8,  7,  6 */
96219  LogEst aVal[] = { 33, 32, 30, 28, 26 };
96220  LogEst *a = pIdx->aiRowLogEst;
96221  int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
96222  int i;
96223
96224  /* Set the first entry (number of rows in the index) to the estimated
96225  ** number of rows in the table. Or 10, if the estimated number of rows
96226  ** in the table is less than that.  */
96227  a[0] = pIdx->pTable->nRowLogEst;
96228  if( a[0]<33 ) a[0] = 33;        assert( 33==sqlite3LogEst(10) );
96229
96230  /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
96231  ** 6 and each subsequent value (if any) is 5.  */
96232  memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
96233  for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
96234    a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
96235  }
96236
96237  assert( 0==sqlite3LogEst(1) );
96238  if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
96239}
96240
96241/*
96242** This routine will drop an existing named index.  This routine
96243** implements the DROP INDEX statement.
96244*/
96245SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
96246  Index *pIndex;
96247  Vdbe *v;
96248  sqlite3 *db = pParse->db;
96249  int iDb;
96250
96251  assert( pParse->nErr==0 );   /* Never called with prior errors */
96252  if( db->mallocFailed ){
96253    goto exit_drop_index;
96254  }
96255  assert( pName->nSrc==1 );
96256  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
96257    goto exit_drop_index;
96258  }
96259  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
96260  if( pIndex==0 ){
96261    if( !ifExists ){
96262      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
96263    }else{
96264      sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
96265    }
96266    pParse->checkSchema = 1;
96267    goto exit_drop_index;
96268  }
96269  if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
96270    sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
96271      "or PRIMARY KEY constraint cannot be dropped", 0);
96272    goto exit_drop_index;
96273  }
96274  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
96275#ifndef SQLITE_OMIT_AUTHORIZATION
96276  {
96277    int code = SQLITE_DROP_INDEX;
96278    Table *pTab = pIndex->pTable;
96279    const char *zDb = db->aDb[iDb].zName;
96280    const char *zTab = SCHEMA_TABLE(iDb);
96281    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
96282      goto exit_drop_index;
96283    }
96284    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
96285    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
96286      goto exit_drop_index;
96287    }
96288  }
96289#endif
96290
96291  /* Generate code to remove the index and from the master table */
96292  v = sqlite3GetVdbe(pParse);
96293  if( v ){
96294    sqlite3BeginWriteOperation(pParse, 1, iDb);
96295    sqlite3NestedParse(pParse,
96296       "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
96297       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
96298    );
96299    sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
96300    sqlite3ChangeCookie(pParse, iDb);
96301    destroyRootPage(pParse, pIndex->tnum, iDb);
96302    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
96303  }
96304
96305exit_drop_index:
96306  sqlite3SrcListDelete(db, pName);
96307}
96308
96309/*
96310** pArray is a pointer to an array of objects. Each object in the
96311** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
96312** to extend the array so that there is space for a new object at the end.
96313**
96314** When this function is called, *pnEntry contains the current size of
96315** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
96316** in total).
96317**
96318** If the realloc() is successful (i.e. if no OOM condition occurs), the
96319** space allocated for the new object is zeroed, *pnEntry updated to
96320** reflect the new size of the array and a pointer to the new allocation
96321** returned. *pIdx is set to the index of the new array entry in this case.
96322**
96323** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
96324** unchanged and a copy of pArray returned.
96325*/
96326SQLITE_PRIVATE void *sqlite3ArrayAllocate(
96327  sqlite3 *db,      /* Connection to notify of malloc failures */
96328  void *pArray,     /* Array of objects.  Might be reallocated */
96329  int szEntry,      /* Size of each object in the array */
96330  int *pnEntry,     /* Number of objects currently in use */
96331  int *pIdx         /* Write the index of a new slot here */
96332){
96333  char *z;
96334  int n = *pnEntry;
96335  if( (n & (n-1))==0 ){
96336    int sz = (n==0) ? 1 : 2*n;
96337    void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
96338    if( pNew==0 ){
96339      *pIdx = -1;
96340      return pArray;
96341    }
96342    pArray = pNew;
96343  }
96344  z = (char*)pArray;
96345  memset(&z[n * szEntry], 0, szEntry);
96346  *pIdx = n;
96347  ++*pnEntry;
96348  return pArray;
96349}
96350
96351/*
96352** Append a new element to the given IdList.  Create a new IdList if
96353** need be.
96354**
96355** A new IdList is returned, or NULL if malloc() fails.
96356*/
96357SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
96358  int i;
96359  if( pList==0 ){
96360    pList = sqlite3DbMallocZero(db, sizeof(IdList) );
96361    if( pList==0 ) return 0;
96362  }
96363  pList->a = sqlite3ArrayAllocate(
96364      db,
96365      pList->a,
96366      sizeof(pList->a[0]),
96367      &pList->nId,
96368      &i
96369  );
96370  if( i<0 ){
96371    sqlite3IdListDelete(db, pList);
96372    return 0;
96373  }
96374  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
96375  return pList;
96376}
96377
96378/*
96379** Delete an IdList.
96380*/
96381SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
96382  int i;
96383  if( pList==0 ) return;
96384  for(i=0; i<pList->nId; i++){
96385    sqlite3DbFree(db, pList->a[i].zName);
96386  }
96387  sqlite3DbFree(db, pList->a);
96388  sqlite3DbFree(db, pList);
96389}
96390
96391/*
96392** Return the index in pList of the identifier named zId.  Return -1
96393** if not found.
96394*/
96395SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
96396  int i;
96397  if( pList==0 ) return -1;
96398  for(i=0; i<pList->nId; i++){
96399    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
96400  }
96401  return -1;
96402}
96403
96404/*
96405** Expand the space allocated for the given SrcList object by
96406** creating nExtra new slots beginning at iStart.  iStart is zero based.
96407** New slots are zeroed.
96408**
96409** For example, suppose a SrcList initially contains two entries: A,B.
96410** To append 3 new entries onto the end, do this:
96411**
96412**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
96413**
96414** After the call above it would contain:  A, B, nil, nil, nil.
96415** If the iStart argument had been 1 instead of 2, then the result
96416** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
96417** the iStart value would be 0.  The result then would
96418** be: nil, nil, nil, A, B.
96419**
96420** If a memory allocation fails the SrcList is unchanged.  The
96421** db->mallocFailed flag will be set to true.
96422*/
96423SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
96424  sqlite3 *db,       /* Database connection to notify of OOM errors */
96425  SrcList *pSrc,     /* The SrcList to be enlarged */
96426  int nExtra,        /* Number of new slots to add to pSrc->a[] */
96427  int iStart         /* Index in pSrc->a[] of first new slot */
96428){
96429  int i;
96430
96431  /* Sanity checking on calling parameters */
96432  assert( iStart>=0 );
96433  assert( nExtra>=1 );
96434  assert( pSrc!=0 );
96435  assert( iStart<=pSrc->nSrc );
96436
96437  /* Allocate additional space if needed */
96438  if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
96439    SrcList *pNew;
96440    int nAlloc = pSrc->nSrc+nExtra;
96441    int nGot;
96442    pNew = sqlite3DbRealloc(db, pSrc,
96443               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
96444    if( pNew==0 ){
96445      assert( db->mallocFailed );
96446      return pSrc;
96447    }
96448    pSrc = pNew;
96449    nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
96450    pSrc->nAlloc = nGot;
96451  }
96452
96453  /* Move existing slots that come after the newly inserted slots
96454  ** out of the way */
96455  for(i=pSrc->nSrc-1; i>=iStart; i--){
96456    pSrc->a[i+nExtra] = pSrc->a[i];
96457  }
96458  pSrc->nSrc += nExtra;
96459
96460  /* Zero the newly allocated slots */
96461  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
96462  for(i=iStart; i<iStart+nExtra; i++){
96463    pSrc->a[i].iCursor = -1;
96464  }
96465
96466  /* Return a pointer to the enlarged SrcList */
96467  return pSrc;
96468}
96469
96470
96471/*
96472** Append a new table name to the given SrcList.  Create a new SrcList if
96473** need be.  A new entry is created in the SrcList even if pTable is NULL.
96474**
96475** A SrcList is returned, or NULL if there is an OOM error.  The returned
96476** SrcList might be the same as the SrcList that was input or it might be
96477** a new one.  If an OOM error does occurs, then the prior value of pList
96478** that is input to this routine is automatically freed.
96479**
96480** If pDatabase is not null, it means that the table has an optional
96481** database name prefix.  Like this:  "database.table".  The pDatabase
96482** points to the table name and the pTable points to the database name.
96483** The SrcList.a[].zName field is filled with the table name which might
96484** come from pTable (if pDatabase is NULL) or from pDatabase.
96485** SrcList.a[].zDatabase is filled with the database name from pTable,
96486** or with NULL if no database is specified.
96487**
96488** In other words, if call like this:
96489**
96490**         sqlite3SrcListAppend(D,A,B,0);
96491**
96492** Then B is a table name and the database name is unspecified.  If called
96493** like this:
96494**
96495**         sqlite3SrcListAppend(D,A,B,C);
96496**
96497** Then C is the table name and B is the database name.  If C is defined
96498** then so is B.  In other words, we never have a case where:
96499**
96500**         sqlite3SrcListAppend(D,A,0,C);
96501**
96502** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
96503** before being added to the SrcList.
96504*/
96505SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
96506  sqlite3 *db,        /* Connection to notify of malloc failures */
96507  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
96508  Token *pTable,      /* Table to append */
96509  Token *pDatabase    /* Database of the table */
96510){
96511  struct SrcList_item *pItem;
96512  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
96513  if( pList==0 ){
96514    pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
96515    if( pList==0 ) return 0;
96516    pList->nAlloc = 1;
96517  }
96518  pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
96519  if( db->mallocFailed ){
96520    sqlite3SrcListDelete(db, pList);
96521    return 0;
96522  }
96523  pItem = &pList->a[pList->nSrc-1];
96524  if( pDatabase && pDatabase->z==0 ){
96525    pDatabase = 0;
96526  }
96527  if( pDatabase ){
96528    Token *pTemp = pDatabase;
96529    pDatabase = pTable;
96530    pTable = pTemp;
96531  }
96532  pItem->zName = sqlite3NameFromToken(db, pTable);
96533  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
96534  return pList;
96535}
96536
96537/*
96538** Assign VdbeCursor index numbers to all tables in a SrcList
96539*/
96540SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
96541  int i;
96542  struct SrcList_item *pItem;
96543  assert(pList || pParse->db->mallocFailed );
96544  if( pList ){
96545    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
96546      if( pItem->iCursor>=0 ) break;
96547      pItem->iCursor = pParse->nTab++;
96548      if( pItem->pSelect ){
96549        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
96550      }
96551    }
96552  }
96553}
96554
96555/*
96556** Delete an entire SrcList including all its substructure.
96557*/
96558SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
96559  int i;
96560  struct SrcList_item *pItem;
96561  if( pList==0 ) return;
96562  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
96563    sqlite3DbFree(db, pItem->zDatabase);
96564    sqlite3DbFree(db, pItem->zName);
96565    sqlite3DbFree(db, pItem->zAlias);
96566    if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
96567    if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
96568    sqlite3DeleteTable(db, pItem->pTab);
96569    sqlite3SelectDelete(db, pItem->pSelect);
96570    sqlite3ExprDelete(db, pItem->pOn);
96571    sqlite3IdListDelete(db, pItem->pUsing);
96572  }
96573  sqlite3DbFree(db, pList);
96574}
96575
96576/*
96577** This routine is called by the parser to add a new term to the
96578** end of a growing FROM clause.  The "p" parameter is the part of
96579** the FROM clause that has already been constructed.  "p" is NULL
96580** if this is the first term of the FROM clause.  pTable and pDatabase
96581** are the name of the table and database named in the FROM clause term.
96582** pDatabase is NULL if the database name qualifier is missing - the
96583** usual case.  If the term has an alias, then pAlias points to the
96584** alias token.  If the term is a subquery, then pSubquery is the
96585** SELECT statement that the subquery encodes.  The pTable and
96586** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
96587** parameters are the content of the ON and USING clauses.
96588**
96589** Return a new SrcList which encodes is the FROM with the new
96590** term added.
96591*/
96592SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
96593  Parse *pParse,          /* Parsing context */
96594  SrcList *p,             /* The left part of the FROM clause already seen */
96595  Token *pTable,          /* Name of the table to add to the FROM clause */
96596  Token *pDatabase,       /* Name of the database containing pTable */
96597  Token *pAlias,          /* The right-hand side of the AS subexpression */
96598  Select *pSubquery,      /* A subquery used in place of a table name */
96599  Expr *pOn,              /* The ON clause of a join */
96600  IdList *pUsing          /* The USING clause of a join */
96601){
96602  struct SrcList_item *pItem;
96603  sqlite3 *db = pParse->db;
96604  if( !p && (pOn || pUsing) ){
96605    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
96606      (pOn ? "ON" : "USING")
96607    );
96608    goto append_from_error;
96609  }
96610  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
96611  if( p==0 || NEVER(p->nSrc==0) ){
96612    goto append_from_error;
96613  }
96614  pItem = &p->a[p->nSrc-1];
96615  assert( pAlias!=0 );
96616  if( pAlias->n ){
96617    pItem->zAlias = sqlite3NameFromToken(db, pAlias);
96618  }
96619  pItem->pSelect = pSubquery;
96620  pItem->pOn = pOn;
96621  pItem->pUsing = pUsing;
96622  return p;
96623
96624 append_from_error:
96625  assert( p==0 );
96626  sqlite3ExprDelete(db, pOn);
96627  sqlite3IdListDelete(db, pUsing);
96628  sqlite3SelectDelete(db, pSubquery);
96629  return 0;
96630}
96631
96632/*
96633** Add an INDEXED BY or NOT INDEXED clause to the most recently added
96634** element of the source-list passed as the second argument.
96635*/
96636SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
96637  assert( pIndexedBy!=0 );
96638  if( p && ALWAYS(p->nSrc>0) ){
96639    struct SrcList_item *pItem = &p->a[p->nSrc-1];
96640    assert( pItem->fg.notIndexed==0 );
96641    assert( pItem->fg.isIndexedBy==0 );
96642    assert( pItem->fg.isTabFunc==0 );
96643    if( pIndexedBy->n==1 && !pIndexedBy->z ){
96644      /* A "NOT INDEXED" clause was supplied. See parse.y
96645      ** construct "indexed_opt" for details. */
96646      pItem->fg.notIndexed = 1;
96647    }else{
96648      pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
96649      pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0);
96650    }
96651  }
96652}
96653
96654/*
96655** Add the list of function arguments to the SrcList entry for a
96656** table-valued-function.
96657*/
96658SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
96659  if( p && pList ){
96660    struct SrcList_item *pItem = &p->a[p->nSrc-1];
96661    assert( pItem->fg.notIndexed==0 );
96662    assert( pItem->fg.isIndexedBy==0 );
96663    assert( pItem->fg.isTabFunc==0 );
96664    pItem->u1.pFuncArg = pList;
96665    pItem->fg.isTabFunc = 1;
96666  }else{
96667    sqlite3ExprListDelete(pParse->db, pList);
96668  }
96669}
96670
96671/*
96672** When building up a FROM clause in the parser, the join operator
96673** is initially attached to the left operand.  But the code generator
96674** expects the join operator to be on the right operand.  This routine
96675** Shifts all join operators from left to right for an entire FROM
96676** clause.
96677**
96678** Example: Suppose the join is like this:
96679**
96680**           A natural cross join B
96681**
96682** The operator is "natural cross join".  The A and B operands are stored
96683** in p->a[0] and p->a[1], respectively.  The parser initially stores the
96684** operator with A.  This routine shifts that operator over to B.
96685*/
96686SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
96687  if( p ){
96688    int i;
96689    for(i=p->nSrc-1; i>0; i--){
96690      p->a[i].fg.jointype = p->a[i-1].fg.jointype;
96691    }
96692    p->a[0].fg.jointype = 0;
96693  }
96694}
96695
96696/*
96697** Begin a transaction
96698*/
96699SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
96700  sqlite3 *db;
96701  Vdbe *v;
96702  int i;
96703
96704  assert( pParse!=0 );
96705  db = pParse->db;
96706  assert( db!=0 );
96707/*  if( db->aDb[0].pBt==0 ) return; */
96708  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
96709    return;
96710  }
96711  v = sqlite3GetVdbe(pParse);
96712  if( !v ) return;
96713  if( type!=TK_DEFERRED ){
96714    for(i=0; i<db->nDb; i++){
96715      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
96716      sqlite3VdbeUsesBtree(v, i);
96717    }
96718  }
96719  sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
96720}
96721
96722/*
96723** Commit a transaction
96724*/
96725SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
96726  Vdbe *v;
96727
96728  assert( pParse!=0 );
96729  assert( pParse->db!=0 );
96730  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
96731    return;
96732  }
96733  v = sqlite3GetVdbe(pParse);
96734  if( v ){
96735    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
96736  }
96737}
96738
96739/*
96740** Rollback a transaction
96741*/
96742SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
96743  Vdbe *v;
96744
96745  assert( pParse!=0 );
96746  assert( pParse->db!=0 );
96747  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
96748    return;
96749  }
96750  v = sqlite3GetVdbe(pParse);
96751  if( v ){
96752    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
96753  }
96754}
96755
96756/*
96757** This function is called by the parser when it parses a command to create,
96758** release or rollback an SQL savepoint.
96759*/
96760SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
96761  char *zName = sqlite3NameFromToken(pParse->db, pName);
96762  if( zName ){
96763    Vdbe *v = sqlite3GetVdbe(pParse);
96764#ifndef SQLITE_OMIT_AUTHORIZATION
96765    static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
96766    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
96767#endif
96768    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
96769      sqlite3DbFree(pParse->db, zName);
96770      return;
96771    }
96772    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
96773  }
96774}
96775
96776/*
96777** Make sure the TEMP database is open and available for use.  Return
96778** the number of errors.  Leave any error messages in the pParse structure.
96779*/
96780SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
96781  sqlite3 *db = pParse->db;
96782  if( db->aDb[1].pBt==0 && !pParse->explain ){
96783    int rc;
96784    Btree *pBt;
96785    static const int flags =
96786          SQLITE_OPEN_READWRITE |
96787          SQLITE_OPEN_CREATE |
96788          SQLITE_OPEN_EXCLUSIVE |
96789          SQLITE_OPEN_DELETEONCLOSE |
96790          SQLITE_OPEN_TEMP_DB;
96791
96792    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
96793    if( rc!=SQLITE_OK ){
96794      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
96795        "file for storing temporary tables");
96796      pParse->rc = rc;
96797      return 1;
96798    }
96799    db->aDb[1].pBt = pBt;
96800    assert( db->aDb[1].pSchema );
96801    if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
96802      db->mallocFailed = 1;
96803      return 1;
96804    }
96805  }
96806  return 0;
96807}
96808
96809/*
96810** Record the fact that the schema cookie will need to be verified
96811** for database iDb.  The code to actually verify the schema cookie
96812** will occur at the end of the top-level VDBE and will be generated
96813** later, by sqlite3FinishCoding().
96814*/
96815SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
96816  Parse *pToplevel = sqlite3ParseToplevel(pParse);
96817  sqlite3 *db = pToplevel->db;
96818
96819  assert( iDb>=0 && iDb<db->nDb );
96820  assert( db->aDb[iDb].pBt!=0 || iDb==1 );
96821  assert( iDb<SQLITE_MAX_ATTACHED+2 );
96822  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
96823  if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
96824    DbMaskSet(pToplevel->cookieMask, iDb);
96825    pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
96826    if( !OMIT_TEMPDB && iDb==1 ){
96827      sqlite3OpenTempDatabase(pToplevel);
96828    }
96829  }
96830}
96831
96832/*
96833** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
96834** attached database. Otherwise, invoke it for the database named zDb only.
96835*/
96836SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
96837  sqlite3 *db = pParse->db;
96838  int i;
96839  for(i=0; i<db->nDb; i++){
96840    Db *pDb = &db->aDb[i];
96841    if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
96842      sqlite3CodeVerifySchema(pParse, i);
96843    }
96844  }
96845}
96846
96847/*
96848** Generate VDBE code that prepares for doing an operation that
96849** might change the database.
96850**
96851** This routine starts a new transaction if we are not already within
96852** a transaction.  If we are already within a transaction, then a checkpoint
96853** is set if the setStatement parameter is true.  A checkpoint should
96854** be set for operations that might fail (due to a constraint) part of
96855** the way through and which will need to undo some writes without having to
96856** rollback the whole transaction.  For operations where all constraints
96857** can be checked before any changes are made to the database, it is never
96858** necessary to undo a write and the checkpoint should not be set.
96859*/
96860SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
96861  Parse *pToplevel = sqlite3ParseToplevel(pParse);
96862  sqlite3CodeVerifySchema(pParse, iDb);
96863  DbMaskSet(pToplevel->writeMask, iDb);
96864  pToplevel->isMultiWrite |= setStatement;
96865}
96866
96867/*
96868** Indicate that the statement currently under construction might write
96869** more than one entry (example: deleting one row then inserting another,
96870** inserting multiple rows in a table, or inserting a row and index entries.)
96871** If an abort occurs after some of these writes have completed, then it will
96872** be necessary to undo the completed writes.
96873*/
96874SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
96875  Parse *pToplevel = sqlite3ParseToplevel(pParse);
96876  pToplevel->isMultiWrite = 1;
96877}
96878
96879/*
96880** The code generator calls this routine if is discovers that it is
96881** possible to abort a statement prior to completion.  In order to
96882** perform this abort without corrupting the database, we need to make
96883** sure that the statement is protected by a statement transaction.
96884**
96885** Technically, we only need to set the mayAbort flag if the
96886** isMultiWrite flag was previously set.  There is a time dependency
96887** such that the abort must occur after the multiwrite.  This makes
96888** some statements involving the REPLACE conflict resolution algorithm
96889** go a little faster.  But taking advantage of this time dependency
96890** makes it more difficult to prove that the code is correct (in
96891** particular, it prevents us from writing an effective
96892** implementation of sqlite3AssertMayAbort()) and so we have chosen
96893** to take the safe route and skip the optimization.
96894*/
96895SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
96896  Parse *pToplevel = sqlite3ParseToplevel(pParse);
96897  pToplevel->mayAbort = 1;
96898}
96899
96900/*
96901** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
96902** error. The onError parameter determines which (if any) of the statement
96903** and/or current transaction is rolled back.
96904*/
96905SQLITE_PRIVATE void sqlite3HaltConstraint(
96906  Parse *pParse,    /* Parsing context */
96907  int errCode,      /* extended error code */
96908  int onError,      /* Constraint type */
96909  char *p4,         /* Error message */
96910  i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
96911  u8 p5Errmsg       /* P5_ErrMsg type */
96912){
96913  Vdbe *v = sqlite3GetVdbe(pParse);
96914  assert( (errCode&0xff)==SQLITE_CONSTRAINT );
96915  if( onError==OE_Abort ){
96916    sqlite3MayAbort(pParse);
96917  }
96918  sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
96919  if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
96920}
96921
96922/*
96923** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
96924*/
96925SQLITE_PRIVATE void sqlite3UniqueConstraint(
96926  Parse *pParse,    /* Parsing context */
96927  int onError,      /* Constraint type */
96928  Index *pIdx       /* The index that triggers the constraint */
96929){
96930  char *zErr;
96931  int j;
96932  StrAccum errMsg;
96933  Table *pTab = pIdx->pTable;
96934
96935  sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
96936  if( pIdx->aColExpr ){
96937    sqlite3XPrintf(&errMsg, 0, "index '%q'", pIdx->zName);
96938  }else{
96939    for(j=0; j<pIdx->nKeyCol; j++){
96940      char *zCol;
96941      assert( pIdx->aiColumn[j]>=0 );
96942      zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
96943      if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
96944      sqlite3XPrintf(&errMsg, 0, "%s.%s", pTab->zName, zCol);
96945    }
96946  }
96947  zErr = sqlite3StrAccumFinish(&errMsg);
96948  sqlite3HaltConstraint(pParse,
96949    IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
96950                            : SQLITE_CONSTRAINT_UNIQUE,
96951    onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
96952}
96953
96954
96955/*
96956** Code an OP_Halt due to non-unique rowid.
96957*/
96958SQLITE_PRIVATE void sqlite3RowidConstraint(
96959  Parse *pParse,    /* Parsing context */
96960  int onError,      /* Conflict resolution algorithm */
96961  Table *pTab       /* The table with the non-unique rowid */
96962){
96963  char *zMsg;
96964  int rc;
96965  if( pTab->iPKey>=0 ){
96966    zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
96967                          pTab->aCol[pTab->iPKey].zName);
96968    rc = SQLITE_CONSTRAINT_PRIMARYKEY;
96969  }else{
96970    zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
96971    rc = SQLITE_CONSTRAINT_ROWID;
96972  }
96973  sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
96974                        P5_ConstraintUnique);
96975}
96976
96977/*
96978** Check to see if pIndex uses the collating sequence pColl.  Return
96979** true if it does and false if it does not.
96980*/
96981#ifndef SQLITE_OMIT_REINDEX
96982static int collationMatch(const char *zColl, Index *pIndex){
96983  int i;
96984  assert( zColl!=0 );
96985  for(i=0; i<pIndex->nColumn; i++){
96986    const char *z = pIndex->azColl[i];
96987    assert( z!=0 || pIndex->aiColumn[i]<0 );
96988    if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
96989      return 1;
96990    }
96991  }
96992  return 0;
96993}
96994#endif
96995
96996/*
96997** Recompute all indices of pTab that use the collating sequence pColl.
96998** If pColl==0 then recompute all indices of pTab.
96999*/
97000#ifndef SQLITE_OMIT_REINDEX
97001static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
97002  Index *pIndex;              /* An index associated with pTab */
97003
97004  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
97005    if( zColl==0 || collationMatch(zColl, pIndex) ){
97006      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
97007      sqlite3BeginWriteOperation(pParse, 0, iDb);
97008      sqlite3RefillIndex(pParse, pIndex, -1);
97009    }
97010  }
97011}
97012#endif
97013
97014/*
97015** Recompute all indices of all tables in all databases where the
97016** indices use the collating sequence pColl.  If pColl==0 then recompute
97017** all indices everywhere.
97018*/
97019#ifndef SQLITE_OMIT_REINDEX
97020static void reindexDatabases(Parse *pParse, char const *zColl){
97021  Db *pDb;                    /* A single database */
97022  int iDb;                    /* The database index number */
97023  sqlite3 *db = pParse->db;   /* The database connection */
97024  HashElem *k;                /* For looping over tables in pDb */
97025  Table *pTab;                /* A table in the database */
97026
97027  assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
97028  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
97029    assert( pDb!=0 );
97030    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
97031      pTab = (Table*)sqliteHashData(k);
97032      reindexTable(pParse, pTab, zColl);
97033    }
97034  }
97035}
97036#endif
97037
97038/*
97039** Generate code for the REINDEX command.
97040**
97041**        REINDEX                            -- 1
97042**        REINDEX  <collation>               -- 2
97043**        REINDEX  ?<database>.?<tablename>  -- 3
97044**        REINDEX  ?<database>.?<indexname>  -- 4
97045**
97046** Form 1 causes all indices in all attached databases to be rebuilt.
97047** Form 2 rebuilds all indices in all databases that use the named
97048** collating function.  Forms 3 and 4 rebuild the named index or all
97049** indices associated with the named table.
97050*/
97051#ifndef SQLITE_OMIT_REINDEX
97052SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
97053  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
97054  char *z;                    /* Name of a table or index */
97055  const char *zDb;            /* Name of the database */
97056  Table *pTab;                /* A table in the database */
97057  Index *pIndex;              /* An index associated with pTab */
97058  int iDb;                    /* The database index number */
97059  sqlite3 *db = pParse->db;   /* The database connection */
97060  Token *pObjName;            /* Name of the table or index to be reindexed */
97061
97062  /* Read the database schema. If an error occurs, leave an error message
97063  ** and code in pParse and return NULL. */
97064  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
97065    return;
97066  }
97067
97068  if( pName1==0 ){
97069    reindexDatabases(pParse, 0);
97070    return;
97071  }else if( NEVER(pName2==0) || pName2->z==0 ){
97072    char *zColl;
97073    assert( pName1->z );
97074    zColl = sqlite3NameFromToken(pParse->db, pName1);
97075    if( !zColl ) return;
97076    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
97077    if( pColl ){
97078      reindexDatabases(pParse, zColl);
97079      sqlite3DbFree(db, zColl);
97080      return;
97081    }
97082    sqlite3DbFree(db, zColl);
97083  }
97084  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
97085  if( iDb<0 ) return;
97086  z = sqlite3NameFromToken(db, pObjName);
97087  if( z==0 ) return;
97088  zDb = db->aDb[iDb].zName;
97089  pTab = sqlite3FindTable(db, z, zDb);
97090  if( pTab ){
97091    reindexTable(pParse, pTab, 0);
97092    sqlite3DbFree(db, z);
97093    return;
97094  }
97095  pIndex = sqlite3FindIndex(db, z, zDb);
97096  sqlite3DbFree(db, z);
97097  if( pIndex ){
97098    sqlite3BeginWriteOperation(pParse, 0, iDb);
97099    sqlite3RefillIndex(pParse, pIndex, -1);
97100    return;
97101  }
97102  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
97103}
97104#endif
97105
97106/*
97107** Return a KeyInfo structure that is appropriate for the given Index.
97108**
97109** The KeyInfo structure for an index is cached in the Index object.
97110** So there might be multiple references to the returned pointer.  The
97111** caller should not try to modify the KeyInfo object.
97112**
97113** The caller should invoke sqlite3KeyInfoUnref() on the returned object
97114** when it has finished using it.
97115*/
97116SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
97117  int i;
97118  int nCol = pIdx->nColumn;
97119  int nKey = pIdx->nKeyCol;
97120  KeyInfo *pKey;
97121  if( pParse->nErr ) return 0;
97122  if( pIdx->uniqNotNull ){
97123    pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
97124  }else{
97125    pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
97126  }
97127  if( pKey ){
97128    assert( sqlite3KeyInfoIsWriteable(pKey) );
97129    for(i=0; i<nCol; i++){
97130      char *zColl = pIdx->azColl[i];
97131      assert( zColl!=0 );
97132      pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
97133                        sqlite3LocateCollSeq(pParse, zColl);
97134      pKey->aSortOrder[i] = pIdx->aSortOrder[i];
97135    }
97136    if( pParse->nErr ){
97137      sqlite3KeyInfoUnref(pKey);
97138      pKey = 0;
97139    }
97140  }
97141  return pKey;
97142}
97143
97144#ifndef SQLITE_OMIT_CTE
97145/*
97146** This routine is invoked once per CTE by the parser while parsing a
97147** WITH clause.
97148*/
97149SQLITE_PRIVATE With *sqlite3WithAdd(
97150  Parse *pParse,          /* Parsing context */
97151  With *pWith,            /* Existing WITH clause, or NULL */
97152  Token *pName,           /* Name of the common-table */
97153  ExprList *pArglist,     /* Optional column name list for the table */
97154  Select *pQuery          /* Query used to initialize the table */
97155){
97156  sqlite3 *db = pParse->db;
97157  With *pNew;
97158  char *zName;
97159
97160  /* Check that the CTE name is unique within this WITH clause. If
97161  ** not, store an error in the Parse structure. */
97162  zName = sqlite3NameFromToken(pParse->db, pName);
97163  if( zName && pWith ){
97164    int i;
97165    for(i=0; i<pWith->nCte; i++){
97166      if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
97167        sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
97168      }
97169    }
97170  }
97171
97172  if( pWith ){
97173    int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
97174    pNew = sqlite3DbRealloc(db, pWith, nByte);
97175  }else{
97176    pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
97177  }
97178  assert( zName!=0 || pNew==0 );
97179  assert( db->mallocFailed==0 || pNew==0 );
97180
97181  if( pNew==0 ){
97182    sqlite3ExprListDelete(db, pArglist);
97183    sqlite3SelectDelete(db, pQuery);
97184    sqlite3DbFree(db, zName);
97185    pNew = pWith;
97186  }else{
97187    pNew->a[pNew->nCte].pSelect = pQuery;
97188    pNew->a[pNew->nCte].pCols = pArglist;
97189    pNew->a[pNew->nCte].zName = zName;
97190    pNew->a[pNew->nCte].zCteErr = 0;
97191    pNew->nCte++;
97192  }
97193
97194  return pNew;
97195}
97196
97197/*
97198** Free the contents of the With object passed as the second argument.
97199*/
97200SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
97201  if( pWith ){
97202    int i;
97203    for(i=0; i<pWith->nCte; i++){
97204      struct Cte *pCte = &pWith->a[i];
97205      sqlite3ExprListDelete(db, pCte->pCols);
97206      sqlite3SelectDelete(db, pCte->pSelect);
97207      sqlite3DbFree(db, pCte->zName);
97208    }
97209    sqlite3DbFree(db, pWith);
97210  }
97211}
97212#endif /* !defined(SQLITE_OMIT_CTE) */
97213
97214/************** End of build.c ***********************************************/
97215/************** Begin file callback.c ****************************************/
97216/*
97217** 2005 May 23
97218**
97219** The author disclaims copyright to this source code.  In place of
97220** a legal notice, here is a blessing:
97221**
97222**    May you do good and not evil.
97223**    May you find forgiveness for yourself and forgive others.
97224**    May you share freely, never taking more than you give.
97225**
97226*************************************************************************
97227**
97228** This file contains functions used to access the internal hash tables
97229** of user defined functions and collation sequences.
97230*/
97231
97232/* #include "sqliteInt.h" */
97233
97234/*
97235** Invoke the 'collation needed' callback to request a collation sequence
97236** in the encoding enc of name zName, length nName.
97237*/
97238static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
97239  assert( !db->xCollNeeded || !db->xCollNeeded16 );
97240  if( db->xCollNeeded ){
97241    char *zExternal = sqlite3DbStrDup(db, zName);
97242    if( !zExternal ) return;
97243    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
97244    sqlite3DbFree(db, zExternal);
97245  }
97246#ifndef SQLITE_OMIT_UTF16
97247  if( db->xCollNeeded16 ){
97248    char const *zExternal;
97249    sqlite3_value *pTmp = sqlite3ValueNew(db);
97250    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
97251    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
97252    if( zExternal ){
97253      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
97254    }
97255    sqlite3ValueFree(pTmp);
97256  }
97257#endif
97258}
97259
97260/*
97261** This routine is called if the collation factory fails to deliver a
97262** collation function in the best encoding but there may be other versions
97263** of this collation function (for other text encodings) available. Use one
97264** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
97265** possible.
97266*/
97267static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
97268  CollSeq *pColl2;
97269  char *z = pColl->zName;
97270  int i;
97271  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
97272  for(i=0; i<3; i++){
97273    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
97274    if( pColl2->xCmp!=0 ){
97275      memcpy(pColl, pColl2, sizeof(CollSeq));
97276      pColl->xDel = 0;         /* Do not copy the destructor */
97277      return SQLITE_OK;
97278    }
97279  }
97280  return SQLITE_ERROR;
97281}
97282
97283/*
97284** This function is responsible for invoking the collation factory callback
97285** or substituting a collation sequence of a different encoding when the
97286** requested collation sequence is not available in the desired encoding.
97287**
97288** If it is not NULL, then pColl must point to the database native encoding
97289** collation sequence with name zName, length nName.
97290**
97291** The return value is either the collation sequence to be used in database
97292** db for collation type name zName, length nName, or NULL, if no collation
97293** sequence can be found.  If no collation is found, leave an error message.
97294**
97295** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
97296*/
97297SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
97298  Parse *pParse,        /* Parsing context */
97299  u8 enc,               /* The desired encoding for the collating sequence */
97300  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
97301  const char *zName     /* Collating sequence name */
97302){
97303  CollSeq *p;
97304  sqlite3 *db = pParse->db;
97305
97306  p = pColl;
97307  if( !p ){
97308    p = sqlite3FindCollSeq(db, enc, zName, 0);
97309  }
97310  if( !p || !p->xCmp ){
97311    /* No collation sequence of this type for this encoding is registered.
97312    ** Call the collation factory to see if it can supply us with one.
97313    */
97314    callCollNeeded(db, enc, zName);
97315    p = sqlite3FindCollSeq(db, enc, zName, 0);
97316  }
97317  if( p && !p->xCmp && synthCollSeq(db, p) ){
97318    p = 0;
97319  }
97320  assert( !p || p->xCmp );
97321  if( p==0 ){
97322    sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
97323  }
97324  return p;
97325}
97326
97327/*
97328** This routine is called on a collation sequence before it is used to
97329** check that it is defined. An undefined collation sequence exists when
97330** a database is loaded that contains references to collation sequences
97331** that have not been defined by sqlite3_create_collation() etc.
97332**
97333** If required, this routine calls the 'collation needed' callback to
97334** request a definition of the collating sequence. If this doesn't work,
97335** an equivalent collating sequence that uses a text encoding different
97336** from the main database is substituted, if one is available.
97337*/
97338SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
97339  if( pColl ){
97340    const char *zName = pColl->zName;
97341    sqlite3 *db = pParse->db;
97342    CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
97343    if( !p ){
97344      return SQLITE_ERROR;
97345    }
97346    assert( p==pColl );
97347  }
97348  return SQLITE_OK;
97349}
97350
97351
97352
97353/*
97354** Locate and return an entry from the db.aCollSeq hash table. If the entry
97355** specified by zName and nName is not found and parameter 'create' is
97356** true, then create a new entry. Otherwise return NULL.
97357**
97358** Each pointer stored in the sqlite3.aCollSeq hash table contains an
97359** array of three CollSeq structures. The first is the collation sequence
97360** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
97361**
97362** Stored immediately after the three collation sequences is a copy of
97363** the collation sequence name. A pointer to this string is stored in
97364** each collation sequence structure.
97365*/
97366static CollSeq *findCollSeqEntry(
97367  sqlite3 *db,          /* Database connection */
97368  const char *zName,    /* Name of the collating sequence */
97369  int create            /* Create a new entry if true */
97370){
97371  CollSeq *pColl;
97372  pColl = sqlite3HashFind(&db->aCollSeq, zName);
97373
97374  if( 0==pColl && create ){
97375    int nName = sqlite3Strlen30(zName);
97376    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
97377    if( pColl ){
97378      CollSeq *pDel = 0;
97379      pColl[0].zName = (char*)&pColl[3];
97380      pColl[0].enc = SQLITE_UTF8;
97381      pColl[1].zName = (char*)&pColl[3];
97382      pColl[1].enc = SQLITE_UTF16LE;
97383      pColl[2].zName = (char*)&pColl[3];
97384      pColl[2].enc = SQLITE_UTF16BE;
97385      memcpy(pColl[0].zName, zName, nName);
97386      pColl[0].zName[nName] = 0;
97387      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
97388
97389      /* If a malloc() failure occurred in sqlite3HashInsert(), it will
97390      ** return the pColl pointer to be deleted (because it wasn't added
97391      ** to the hash table).
97392      */
97393      assert( pDel==0 || pDel==pColl );
97394      if( pDel!=0 ){
97395        db->mallocFailed = 1;
97396        sqlite3DbFree(db, pDel);
97397        pColl = 0;
97398      }
97399    }
97400  }
97401  return pColl;
97402}
97403
97404/*
97405** Parameter zName points to a UTF-8 encoded string nName bytes long.
97406** Return the CollSeq* pointer for the collation sequence named zName
97407** for the encoding 'enc' from the database 'db'.
97408**
97409** If the entry specified is not found and 'create' is true, then create a
97410** new entry.  Otherwise return NULL.
97411**
97412** A separate function sqlite3LocateCollSeq() is a wrapper around
97413** this routine.  sqlite3LocateCollSeq() invokes the collation factory
97414** if necessary and generates an error message if the collating sequence
97415** cannot be found.
97416**
97417** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
97418*/
97419SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
97420  sqlite3 *db,
97421  u8 enc,
97422  const char *zName,
97423  int create
97424){
97425  CollSeq *pColl;
97426  if( zName ){
97427    pColl = findCollSeqEntry(db, zName, create);
97428  }else{
97429    pColl = db->pDfltColl;
97430  }
97431  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
97432  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
97433  if( pColl ) pColl += enc-1;
97434  return pColl;
97435}
97436
97437/* During the search for the best function definition, this procedure
97438** is called to test how well the function passed as the first argument
97439** matches the request for a function with nArg arguments in a system
97440** that uses encoding enc. The value returned indicates how well the
97441** request is matched. A higher value indicates a better match.
97442**
97443** If nArg is -1 that means to only return a match (non-zero) if p->nArg
97444** is also -1.  In other words, we are searching for a function that
97445** takes a variable number of arguments.
97446**
97447** If nArg is -2 that means that we are searching for any function
97448** regardless of the number of arguments it uses, so return a positive
97449** match score for any
97450**
97451** The returned value is always between 0 and 6, as follows:
97452**
97453** 0: Not a match.
97454** 1: UTF8/16 conversion required and function takes any number of arguments.
97455** 2: UTF16 byte order change required and function takes any number of args.
97456** 3: encoding matches and function takes any number of arguments
97457** 4: UTF8/16 conversion required - argument count matches exactly
97458** 5: UTF16 byte order conversion required - argument count matches exactly
97459** 6: Perfect match:  encoding and argument count match exactly.
97460**
97461** If nArg==(-2) then any function with a non-null xStep or xFunc is
97462** a perfect match and any function with both xStep and xFunc NULL is
97463** a non-match.
97464*/
97465#define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
97466static int matchQuality(
97467  FuncDef *p,     /* The function we are evaluating for match quality */
97468  int nArg,       /* Desired number of arguments.  (-1)==any */
97469  u8 enc          /* Desired text encoding */
97470){
97471  int match;
97472
97473  /* nArg of -2 is a special case */
97474  if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
97475
97476  /* Wrong number of arguments means "no match" */
97477  if( p->nArg!=nArg && p->nArg>=0 ) return 0;
97478
97479  /* Give a better score to a function with a specific number of arguments
97480  ** than to function that accepts any number of arguments. */
97481  if( p->nArg==nArg ){
97482    match = 4;
97483  }else{
97484    match = 1;
97485  }
97486
97487  /* Bonus points if the text encoding matches */
97488  if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
97489    match += 2;  /* Exact encoding match */
97490  }else if( (enc & p->funcFlags & 2)!=0 ){
97491    match += 1;  /* Both are UTF16, but with different byte orders */
97492  }
97493
97494  return match;
97495}
97496
97497/*
97498** Search a FuncDefHash for a function with the given name.  Return
97499** a pointer to the matching FuncDef if found, or 0 if there is no match.
97500*/
97501static FuncDef *functionSearch(
97502  FuncDefHash *pHash,  /* Hash table to search */
97503  int h,               /* Hash of the name */
97504  const char *zFunc,   /* Name of function */
97505  int nFunc            /* Number of bytes in zFunc */
97506){
97507  FuncDef *p;
97508  for(p=pHash->a[h]; p; p=p->pHash){
97509    if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
97510      return p;
97511    }
97512  }
97513  return 0;
97514}
97515
97516/*
97517** Insert a new FuncDef into a FuncDefHash hash table.
97518*/
97519SQLITE_PRIVATE void sqlite3FuncDefInsert(
97520  FuncDefHash *pHash,  /* The hash table into which to insert */
97521  FuncDef *pDef        /* The function definition to insert */
97522){
97523  FuncDef *pOther;
97524  int nName = sqlite3Strlen30(pDef->zName);
97525  u8 c1 = (u8)pDef->zName[0];
97526  int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
97527  pOther = functionSearch(pHash, h, pDef->zName, nName);
97528  if( pOther ){
97529    assert( pOther!=pDef && pOther->pNext!=pDef );
97530    pDef->pNext = pOther->pNext;
97531    pOther->pNext = pDef;
97532  }else{
97533    pDef->pNext = 0;
97534    pDef->pHash = pHash->a[h];
97535    pHash->a[h] = pDef;
97536  }
97537}
97538
97539
97540
97541/*
97542** Locate a user function given a name, a number of arguments and a flag
97543** indicating whether the function prefers UTF-16 over UTF-8.  Return a
97544** pointer to the FuncDef structure that defines that function, or return
97545** NULL if the function does not exist.
97546**
97547** If the createFlag argument is true, then a new (blank) FuncDef
97548** structure is created and liked into the "db" structure if a
97549** no matching function previously existed.
97550**
97551** If nArg is -2, then the first valid function found is returned.  A
97552** function is valid if either xFunc or xStep is non-zero.  The nArg==(-2)
97553** case is used to see if zName is a valid function name for some number
97554** of arguments.  If nArg is -2, then createFlag must be 0.
97555**
97556** If createFlag is false, then a function with the required name and
97557** number of arguments may be returned even if the eTextRep flag does not
97558** match that requested.
97559*/
97560SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
97561  sqlite3 *db,       /* An open database */
97562  const char *zName, /* Name of the function.  Not null-terminated */
97563  int nName,         /* Number of characters in the name */
97564  int nArg,          /* Number of arguments.  -1 means any number */
97565  u8 enc,            /* Preferred text encoding */
97566  u8 createFlag      /* Create new entry if true and does not otherwise exist */
97567){
97568  FuncDef *p;         /* Iterator variable */
97569  FuncDef *pBest = 0; /* Best match found so far */
97570  int bestScore = 0;  /* Score of best match */
97571  int h;              /* Hash value */
97572
97573  assert( nArg>=(-2) );
97574  assert( nArg>=(-1) || createFlag==0 );
97575  h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
97576
97577  /* First search for a match amongst the application-defined functions.
97578  */
97579  p = functionSearch(&db->aFunc, h, zName, nName);
97580  while( p ){
97581    int score = matchQuality(p, nArg, enc);
97582    if( score>bestScore ){
97583      pBest = p;
97584      bestScore = score;
97585    }
97586    p = p->pNext;
97587  }
97588
97589  /* If no match is found, search the built-in functions.
97590  **
97591  ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
97592  ** functions even if a prior app-defined function was found.  And give
97593  ** priority to built-in functions.
97594  **
97595  ** Except, if createFlag is true, that means that we are trying to
97596  ** install a new function.  Whatever FuncDef structure is returned it will
97597  ** have fields overwritten with new information appropriate for the
97598  ** new function.  But the FuncDefs for built-in functions are read-only.
97599  ** So we must not search for built-ins when creating a new function.
97600  */
97601  if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
97602    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
97603    bestScore = 0;
97604    p = functionSearch(pHash, h, zName, nName);
97605    while( p ){
97606      int score = matchQuality(p, nArg, enc);
97607      if( score>bestScore ){
97608        pBest = p;
97609        bestScore = score;
97610      }
97611      p = p->pNext;
97612    }
97613  }
97614
97615  /* If the createFlag parameter is true and the search did not reveal an
97616  ** exact match for the name, number of arguments and encoding, then add a
97617  ** new entry to the hash table and return it.
97618  */
97619  if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
97620      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
97621    pBest->zName = (char *)&pBest[1];
97622    pBest->nArg = (u16)nArg;
97623    pBest->funcFlags = enc;
97624    memcpy(pBest->zName, zName, nName);
97625    pBest->zName[nName] = 0;
97626    sqlite3FuncDefInsert(&db->aFunc, pBest);
97627  }
97628
97629  if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
97630    return pBest;
97631  }
97632  return 0;
97633}
97634
97635/*
97636** Free all resources held by the schema structure. The void* argument points
97637** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
97638** pointer itself, it just cleans up subsidiary resources (i.e. the contents
97639** of the schema hash tables).
97640**
97641** The Schema.cache_size variable is not cleared.
97642*/
97643SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
97644  Hash temp1;
97645  Hash temp2;
97646  HashElem *pElem;
97647  Schema *pSchema = (Schema *)p;
97648
97649  temp1 = pSchema->tblHash;
97650  temp2 = pSchema->trigHash;
97651  sqlite3HashInit(&pSchema->trigHash);
97652  sqlite3HashClear(&pSchema->idxHash);
97653  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
97654    sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
97655  }
97656  sqlite3HashClear(&temp2);
97657  sqlite3HashInit(&pSchema->tblHash);
97658  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
97659    Table *pTab = sqliteHashData(pElem);
97660    sqlite3DeleteTable(0, pTab);
97661  }
97662  sqlite3HashClear(&temp1);
97663  sqlite3HashClear(&pSchema->fkeyHash);
97664  pSchema->pSeqTab = 0;
97665  if( pSchema->schemaFlags & DB_SchemaLoaded ){
97666    pSchema->iGeneration++;
97667    pSchema->schemaFlags &= ~DB_SchemaLoaded;
97668  }
97669}
97670
97671/*
97672** Find and return the schema associated with a BTree.  Create
97673** a new one if necessary.
97674*/
97675SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
97676  Schema * p;
97677  if( pBt ){
97678    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
97679  }else{
97680    p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
97681  }
97682  if( !p ){
97683    db->mallocFailed = 1;
97684  }else if ( 0==p->file_format ){
97685    sqlite3HashInit(&p->tblHash);
97686    sqlite3HashInit(&p->idxHash);
97687    sqlite3HashInit(&p->trigHash);
97688    sqlite3HashInit(&p->fkeyHash);
97689    p->enc = SQLITE_UTF8;
97690  }
97691  return p;
97692}
97693
97694/************** End of callback.c ********************************************/
97695/************** Begin file delete.c ******************************************/
97696/*
97697** 2001 September 15
97698**
97699** The author disclaims copyright to this source code.  In place of
97700** a legal notice, here is a blessing:
97701**
97702**    May you do good and not evil.
97703**    May you find forgiveness for yourself and forgive others.
97704**    May you share freely, never taking more than you give.
97705**
97706*************************************************************************
97707** This file contains C code routines that are called by the parser
97708** in order to generate code for DELETE FROM statements.
97709*/
97710/* #include "sqliteInt.h" */
97711
97712/*
97713** While a SrcList can in general represent multiple tables and subqueries
97714** (as in the FROM clause of a SELECT statement) in this case it contains
97715** the name of a single table, as one might find in an INSERT, DELETE,
97716** or UPDATE statement.  Look up that table in the symbol table and
97717** return a pointer.  Set an error message and return NULL if the table
97718** name is not found or if any other error occurs.
97719**
97720** The following fields are initialized appropriate in pSrc:
97721**
97722**    pSrc->a[0].pTab       Pointer to the Table object
97723**    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
97724**
97725*/
97726SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
97727  struct SrcList_item *pItem = pSrc->a;
97728  Table *pTab;
97729  assert( pItem && pSrc->nSrc==1 );
97730  pTab = sqlite3LocateTableItem(pParse, 0, pItem);
97731  sqlite3DeleteTable(pParse->db, pItem->pTab);
97732  pItem->pTab = pTab;
97733  if( pTab ){
97734    pTab->nRef++;
97735  }
97736  if( sqlite3IndexedByLookup(pParse, pItem) ){
97737    pTab = 0;
97738  }
97739  return pTab;
97740}
97741
97742/*
97743** Check to make sure the given table is writable.  If it is not
97744** writable, generate an error message and return 1.  If it is
97745** writable return 0;
97746*/
97747SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
97748  /* A table is not writable under the following circumstances:
97749  **
97750  **   1) It is a virtual table and no implementation of the xUpdate method
97751  **      has been provided, or
97752  **   2) It is a system table (i.e. sqlite_master), this call is not
97753  **      part of a nested parse and writable_schema pragma has not
97754  **      been specified.
97755  **
97756  ** In either case leave an error message in pParse and return non-zero.
97757  */
97758  if( ( IsVirtual(pTab)
97759     && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
97760   || ( (pTab->tabFlags & TF_Readonly)!=0
97761     && (pParse->db->flags & SQLITE_WriteSchema)==0
97762     && pParse->nested==0 )
97763  ){
97764    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
97765    return 1;
97766  }
97767
97768#ifndef SQLITE_OMIT_VIEW
97769  if( !viewOk && pTab->pSelect ){
97770    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
97771    return 1;
97772  }
97773#endif
97774  return 0;
97775}
97776
97777
97778#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
97779/*
97780** Evaluate a view and store its result in an ephemeral table.  The
97781** pWhere argument is an optional WHERE clause that restricts the
97782** set of rows in the view that are to be added to the ephemeral table.
97783*/
97784SQLITE_PRIVATE void sqlite3MaterializeView(
97785  Parse *pParse,       /* Parsing context */
97786  Table *pView,        /* View definition */
97787  Expr *pWhere,        /* Optional WHERE clause to be added */
97788  int iCur             /* Cursor number for ephemeral table */
97789){
97790  SelectDest dest;
97791  Select *pSel;
97792  SrcList *pFrom;
97793  sqlite3 *db = pParse->db;
97794  int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
97795  pWhere = sqlite3ExprDup(db, pWhere, 0);
97796  pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
97797  if( pFrom ){
97798    assert( pFrom->nSrc==1 );
97799    pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
97800    pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
97801    assert( pFrom->a[0].pOn==0 );
97802    assert( pFrom->a[0].pUsing==0 );
97803  }
97804  pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
97805  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
97806  sqlite3Select(pParse, pSel, &dest);
97807  sqlite3SelectDelete(db, pSel);
97808}
97809#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
97810
97811#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
97812/*
97813** Generate an expression tree to implement the WHERE, ORDER BY,
97814** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
97815**
97816**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
97817**                            \__________________________/
97818**                               pLimitWhere (pInClause)
97819*/
97820SQLITE_PRIVATE Expr *sqlite3LimitWhere(
97821  Parse *pParse,               /* The parser context */
97822  SrcList *pSrc,               /* the FROM clause -- which tables to scan */
97823  Expr *pWhere,                /* The WHERE clause.  May be null */
97824  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
97825  Expr *pLimit,                /* The LIMIT clause.  May be null */
97826  Expr *pOffset,               /* The OFFSET clause.  May be null */
97827  char *zStmtType              /* Either DELETE or UPDATE.  For err msgs. */
97828){
97829  Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
97830  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
97831  Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
97832  ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
97833  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
97834  Select *pSelect = NULL;      /* Complete SELECT tree */
97835
97836  /* Check that there isn't an ORDER BY without a LIMIT clause.
97837  */
97838  if( pOrderBy && (pLimit == 0) ) {
97839    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
97840    goto limit_where_cleanup_2;
97841  }
97842
97843  /* We only need to generate a select expression if there
97844  ** is a limit/offset term to enforce.
97845  */
97846  if( pLimit == 0 ) {
97847    /* if pLimit is null, pOffset will always be null as well. */
97848    assert( pOffset == 0 );
97849    return pWhere;
97850  }
97851
97852  /* Generate a select expression tree to enforce the limit/offset
97853  ** term for the DELETE or UPDATE statement.  For example:
97854  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
97855  ** becomes:
97856  **   DELETE FROM table_a WHERE rowid IN (
97857  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
97858  **   );
97859  */
97860
97861  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
97862  if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
97863  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
97864  if( pEList == 0 ) goto limit_where_cleanup_2;
97865
97866  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
97867  ** and the SELECT subtree. */
97868  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
97869  if( pSelectSrc == 0 ) {
97870    sqlite3ExprListDelete(pParse->db, pEList);
97871    goto limit_where_cleanup_2;
97872  }
97873
97874  /* generate the SELECT expression tree. */
97875  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
97876                             pOrderBy,0,pLimit,pOffset);
97877  if( pSelect == 0 ) return 0;
97878
97879  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
97880  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
97881  if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
97882  pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
97883  if( pInClause == 0 ) goto limit_where_cleanup_1;
97884
97885  pInClause->x.pSelect = pSelect;
97886  pInClause->flags |= EP_xIsSelect;
97887  sqlite3ExprSetHeightAndFlags(pParse, pInClause);
97888  return pInClause;
97889
97890  /* something went wrong. clean up anything allocated. */
97891limit_where_cleanup_1:
97892  sqlite3SelectDelete(pParse->db, pSelect);
97893  return 0;
97894
97895limit_where_cleanup_2:
97896  sqlite3ExprDelete(pParse->db, pWhere);
97897  sqlite3ExprListDelete(pParse->db, pOrderBy);
97898  sqlite3ExprDelete(pParse->db, pLimit);
97899  sqlite3ExprDelete(pParse->db, pOffset);
97900  return 0;
97901}
97902#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
97903       /*      && !defined(SQLITE_OMIT_SUBQUERY) */
97904
97905/*
97906** Generate code for a DELETE FROM statement.
97907**
97908**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
97909**                 \________/       \________________/
97910**                  pTabList              pWhere
97911*/
97912SQLITE_PRIVATE void sqlite3DeleteFrom(
97913  Parse *pParse,         /* The parser context */
97914  SrcList *pTabList,     /* The table from which we should delete things */
97915  Expr *pWhere           /* The WHERE clause.  May be null */
97916){
97917  Vdbe *v;               /* The virtual database engine */
97918  Table *pTab;           /* The table from which records will be deleted */
97919  const char *zDb;       /* Name of database holding pTab */
97920  int i;                 /* Loop counter */
97921  WhereInfo *pWInfo;     /* Information about the WHERE clause */
97922  Index *pIdx;           /* For looping over indices of the table */
97923  int iTabCur;           /* Cursor number for the table */
97924  int iDataCur = 0;      /* VDBE cursor for the canonical data source */
97925  int iIdxCur = 0;       /* Cursor number of the first index */
97926  int nIdx;              /* Number of indices */
97927  sqlite3 *db;           /* Main database structure */
97928  AuthContext sContext;  /* Authorization context */
97929  NameContext sNC;       /* Name context to resolve expressions in */
97930  int iDb;               /* Database number */
97931  int memCnt = -1;       /* Memory cell used for change counting */
97932  int rcauth;            /* Value returned by authorization callback */
97933  int eOnePass;          /* ONEPASS_OFF or _SINGLE or _MULTI */
97934  int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
97935  u8 *aToOpen = 0;       /* Open cursor iTabCur+j if aToOpen[j] is true */
97936  Index *pPk;            /* The PRIMARY KEY index on the table */
97937  int iPk = 0;           /* First of nPk registers holding PRIMARY KEY value */
97938  i16 nPk = 1;           /* Number of columns in the PRIMARY KEY */
97939  int iKey;              /* Memory cell holding key of row to be deleted */
97940  i16 nKey;              /* Number of memory cells in the row key */
97941  int iEphCur = 0;       /* Ephemeral table holding all primary key values */
97942  int iRowSet = 0;       /* Register for rowset of rows to delete */
97943  int addrBypass = 0;    /* Address of jump over the delete logic */
97944  int addrLoop = 0;      /* Top of the delete loop */
97945  int addrEphOpen = 0;   /* Instruction to open the Ephemeral table */
97946
97947#ifndef SQLITE_OMIT_TRIGGER
97948  int isView;                  /* True if attempting to delete from a view */
97949  Trigger *pTrigger;           /* List of table triggers, if required */
97950  int bComplex;                /* True if there are either triggers or FKs */
97951#endif
97952
97953  memset(&sContext, 0, sizeof(sContext));
97954  db = pParse->db;
97955  if( pParse->nErr || db->mallocFailed ){
97956    goto delete_from_cleanup;
97957  }
97958  assert( pTabList->nSrc==1 );
97959
97960  /* Locate the table which we want to delete.  This table has to be
97961  ** put in an SrcList structure because some of the subroutines we
97962  ** will be calling are designed to work with multiple tables and expect
97963  ** an SrcList* parameter instead of just a Table* parameter.
97964  */
97965  pTab = sqlite3SrcListLookup(pParse, pTabList);
97966  if( pTab==0 )  goto delete_from_cleanup;
97967
97968  /* Figure out if we have any triggers and if the table being
97969  ** deleted from is a view
97970  */
97971#ifndef SQLITE_OMIT_TRIGGER
97972  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
97973  isView = pTab->pSelect!=0;
97974  bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
97975#else
97976# define pTrigger 0
97977# define isView 0
97978# define bComplex 0
97979#endif
97980#ifdef SQLITE_OMIT_VIEW
97981# undef isView
97982# define isView 0
97983#endif
97984
97985  /* If pTab is really a view, make sure it has been initialized.
97986  */
97987  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
97988    goto delete_from_cleanup;
97989  }
97990
97991  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
97992    goto delete_from_cleanup;
97993  }
97994  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
97995  assert( iDb<db->nDb );
97996  zDb = db->aDb[iDb].zName;
97997  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
97998  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
97999  if( rcauth==SQLITE_DENY ){
98000    goto delete_from_cleanup;
98001  }
98002  assert(!isView || pTrigger);
98003
98004  /* Assign cursor numbers to the table and all its indices.
98005  */
98006  assert( pTabList->nSrc==1 );
98007  iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
98008  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
98009    pParse->nTab++;
98010  }
98011
98012  /* Start the view context
98013  */
98014  if( isView ){
98015    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
98016  }
98017
98018  /* Begin generating code.
98019  */
98020  v = sqlite3GetVdbe(pParse);
98021  if( v==0 ){
98022    goto delete_from_cleanup;
98023  }
98024  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
98025  sqlite3BeginWriteOperation(pParse, 1, iDb);
98026
98027  /* If we are trying to delete from a view, realize that view into
98028  ** an ephemeral table.
98029  */
98030#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
98031  if( isView ){
98032    sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
98033    iDataCur = iIdxCur = iTabCur;
98034  }
98035#endif
98036
98037  /* Resolve the column names in the WHERE clause.
98038  */
98039  memset(&sNC, 0, sizeof(sNC));
98040  sNC.pParse = pParse;
98041  sNC.pSrcList = pTabList;
98042  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
98043    goto delete_from_cleanup;
98044  }
98045
98046  /* Initialize the counter of the number of rows deleted, if
98047  ** we are counting rows.
98048  */
98049  if( db->flags & SQLITE_CountRows ){
98050    memCnt = ++pParse->nMem;
98051    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
98052  }
98053
98054#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
98055  /* Special case: A DELETE without a WHERE clause deletes everything.
98056  ** It is easier just to erase the whole table. Prior to version 3.6.5,
98057  ** this optimization caused the row change count (the value returned by
98058  ** API function sqlite3_count_changes) to be set incorrectly.  */
98059  if( rcauth==SQLITE_OK
98060   && pWhere==0
98061   && !bComplex
98062   && !IsVirtual(pTab)
98063  ){
98064    assert( !isView );
98065    sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
98066    if( HasRowid(pTab) ){
98067      sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
98068                        pTab->zName, P4_STATIC);
98069    }
98070    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
98071      assert( pIdx->pSchema==pTab->pSchema );
98072      sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
98073    }
98074  }else
98075#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
98076  {
98077    u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK;
98078    wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
98079    if( HasRowid(pTab) ){
98080      /* For a rowid table, initialize the RowSet to an empty set */
98081      pPk = 0;
98082      nPk = 1;
98083      iRowSet = ++pParse->nMem;
98084      sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
98085    }else{
98086      /* For a WITHOUT ROWID table, create an ephemeral table used to
98087      ** hold all primary keys for rows to be deleted. */
98088      pPk = sqlite3PrimaryKeyIndex(pTab);
98089      assert( pPk!=0 );
98090      nPk = pPk->nKeyCol;
98091      iPk = pParse->nMem+1;
98092      pParse->nMem += nPk;
98093      iEphCur = pParse->nTab++;
98094      addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
98095      sqlite3VdbeSetP4KeyInfo(pParse, pPk);
98096    }
98097
98098    /* Construct a query to find the rowid or primary key for every row
98099    ** to be deleted, based on the WHERE clause. Set variable eOnePass
98100    ** to indicate the strategy used to implement this delete:
98101    **
98102    **  ONEPASS_OFF:    Two-pass approach - use a FIFO for rowids/PK values.
98103    **  ONEPASS_SINGLE: One-pass approach - at most one row deleted.
98104    **  ONEPASS_MULTI:  One-pass approach - any number of rows may be deleted.
98105    */
98106    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
98107    if( pWInfo==0 ) goto delete_from_cleanup;
98108    eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
98109    assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
98110    assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
98111
98112    /* Keep track of the number of rows to be deleted */
98113    if( db->flags & SQLITE_CountRows ){
98114      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
98115    }
98116
98117    /* Extract the rowid or primary key for the current row */
98118    if( pPk ){
98119      for(i=0; i<nPk; i++){
98120        assert( pPk->aiColumn[i]>=0 );
98121        sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
98122                                        pPk->aiColumn[i], iPk+i);
98123      }
98124      iKey = iPk;
98125    }else{
98126      iKey = pParse->nMem + 1;
98127      iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
98128      if( iKey>pParse->nMem ) pParse->nMem = iKey;
98129    }
98130
98131    if( eOnePass!=ONEPASS_OFF ){
98132      /* For ONEPASS, no need to store the rowid/primary-key. There is only
98133      ** one, so just keep it in its register(s) and fall through to the
98134      ** delete code.  */
98135      nKey = nPk; /* OP_Found will use an unpacked key */
98136      aToOpen = sqlite3DbMallocRaw(db, nIdx+2);
98137      if( aToOpen==0 ){
98138        sqlite3WhereEnd(pWInfo);
98139        goto delete_from_cleanup;
98140      }
98141      memset(aToOpen, 1, nIdx+1);
98142      aToOpen[nIdx+1] = 0;
98143      if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
98144      if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
98145      if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
98146    }else{
98147      if( pPk ){
98148        /* Add the PK key for this row to the temporary table */
98149        iKey = ++pParse->nMem;
98150        nKey = 0;   /* Zero tells OP_Found to use a composite key */
98151        sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
98152            sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
98153        sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
98154      }else{
98155        /* Add the rowid of the row to be deleted to the RowSet */
98156        nKey = 1;  /* OP_Seek always uses a single rowid */
98157        sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
98158      }
98159    }
98160
98161    /* If this DELETE cannot use the ONEPASS strategy, this is the
98162    ** end of the WHERE loop */
98163    if( eOnePass!=ONEPASS_OFF ){
98164      addrBypass = sqlite3VdbeMakeLabel(v);
98165    }else{
98166      sqlite3WhereEnd(pWInfo);
98167    }
98168
98169    /* Unless this is a view, open cursors for the table we are
98170    ** deleting from and all its indices. If this is a view, then the
98171    ** only effect this statement has is to fire the INSTEAD OF
98172    ** triggers.
98173    */
98174    if( !isView ){
98175      int iAddrOnce = 0;
98176      if( eOnePass==ONEPASS_MULTI ){
98177        iAddrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
98178      }
98179      testcase( IsVirtual(pTab) );
98180      sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iTabCur, aToOpen,
98181                                 &iDataCur, &iIdxCur);
98182      assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
98183      assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
98184      if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
98185    }
98186
98187    /* Set up a loop over the rowids/primary-keys that were found in the
98188    ** where-clause loop above.
98189    */
98190    if( eOnePass!=ONEPASS_OFF ){
98191      assert( nKey==nPk );  /* OP_Found will use an unpacked key */
98192      if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
98193        assert( pPk!=0 || pTab->pSelect!=0 );
98194        sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
98195        VdbeCoverage(v);
98196      }
98197    }else if( pPk ){
98198      addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
98199      sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
98200      assert( nKey==0 );  /* OP_Found will use a composite key */
98201    }else{
98202      addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
98203      VdbeCoverage(v);
98204      assert( nKey==1 );
98205    }
98206
98207    /* Delete the row */
98208#ifndef SQLITE_OMIT_VIRTUALTABLE
98209    if( IsVirtual(pTab) ){
98210      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
98211      sqlite3VtabMakeWritable(pParse, pTab);
98212      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
98213      sqlite3VdbeChangeP5(v, OE_Abort);
98214      assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
98215      sqlite3MayAbort(pParse);
98216      if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
98217        pParse->isMultiWrite = 0;
98218      }
98219    }else
98220#endif
98221    {
98222      int count = (pParse->nested==0);    /* True to count changes */
98223      int iIdxNoSeek = -1;
98224      if( bComplex==0 && aiCurOnePass[1]!=iDataCur ){
98225        iIdxNoSeek = aiCurOnePass[1];
98226      }
98227      sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
98228          iKey, nKey, count, OE_Default, eOnePass, iIdxNoSeek);
98229    }
98230
98231    /* End of the loop over all rowids/primary-keys. */
98232    if( eOnePass!=ONEPASS_OFF ){
98233      sqlite3VdbeResolveLabel(v, addrBypass);
98234      sqlite3WhereEnd(pWInfo);
98235    }else if( pPk ){
98236      sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
98237      sqlite3VdbeJumpHere(v, addrLoop);
98238    }else{
98239      sqlite3VdbeGoto(v, addrLoop);
98240      sqlite3VdbeJumpHere(v, addrLoop);
98241    }
98242
98243    /* Close the cursors open on the table and its indexes. */
98244    if( !isView && !IsVirtual(pTab) ){
98245      if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
98246      for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
98247        sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
98248      }
98249    }
98250  } /* End non-truncate path */
98251
98252  /* Update the sqlite_sequence table by storing the content of the
98253  ** maximum rowid counter values recorded while inserting into
98254  ** autoincrement tables.
98255  */
98256  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
98257    sqlite3AutoincrementEnd(pParse);
98258  }
98259
98260  /* Return the number of rows that were deleted. If this routine is
98261  ** generating code because of a call to sqlite3NestedParse(), do not
98262  ** invoke the callback function.
98263  */
98264  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
98265    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
98266    sqlite3VdbeSetNumCols(v, 1);
98267    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
98268  }
98269
98270delete_from_cleanup:
98271  sqlite3AuthContextPop(&sContext);
98272  sqlite3SrcListDelete(db, pTabList);
98273  sqlite3ExprDelete(db, pWhere);
98274  sqlite3DbFree(db, aToOpen);
98275  return;
98276}
98277/* Make sure "isView" and other macros defined above are undefined. Otherwise
98278** they may interfere with compilation of other functions in this file
98279** (or in another file, if this file becomes part of the amalgamation).  */
98280#ifdef isView
98281 #undef isView
98282#endif
98283#ifdef pTrigger
98284 #undef pTrigger
98285#endif
98286
98287/*
98288** This routine generates VDBE code that causes a single row of a
98289** single table to be deleted.  Both the original table entry and
98290** all indices are removed.
98291**
98292** Preconditions:
98293**
98294**   1.  iDataCur is an open cursor on the btree that is the canonical data
98295**       store for the table.  (This will be either the table itself,
98296**       in the case of a rowid table, or the PRIMARY KEY index in the case
98297**       of a WITHOUT ROWID table.)
98298**
98299**   2.  Read/write cursors for all indices of pTab must be open as
98300**       cursor number iIdxCur+i for the i-th index.
98301**
98302**   3.  The primary key for the row to be deleted must be stored in a
98303**       sequence of nPk memory cells starting at iPk.  If nPk==0 that means
98304**       that a search record formed from OP_MakeRecord is contained in the
98305**       single memory location iPk.
98306**
98307** eMode:
98308**   Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
98309**   ONEPASS_MULTI.  If eMode is not ONEPASS_OFF, then the cursor
98310**   iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
98311**   then this function must seek iDataCur to the entry identified by iPk
98312**   and nPk before reading from it.
98313**
98314**   If eMode is ONEPASS_MULTI, then this call is being made as part
98315**   of a ONEPASS delete that affects multiple rows. In this case, if
98316**   iIdxNoSeek is a valid cursor number (>=0), then its position should
98317**   be preserved following the delete operation. Or, if iIdxNoSeek is not
98318**   a valid cursor number, the position of iDataCur should be preserved
98319**   instead.
98320**
98321** iIdxNoSeek:
98322**   If iIdxNoSeek is a valid cursor number (>=0), then it identifies an
98323**   index cursor (from within array of cursors starting at iIdxCur) that
98324**   already points to the index entry to be deleted.
98325*/
98326SQLITE_PRIVATE void sqlite3GenerateRowDelete(
98327  Parse *pParse,     /* Parsing context */
98328  Table *pTab,       /* Table containing the row to be deleted */
98329  Trigger *pTrigger, /* List of triggers to (potentially) fire */
98330  int iDataCur,      /* Cursor from which column data is extracted */
98331  int iIdxCur,       /* First index cursor */
98332  int iPk,           /* First memory cell containing the PRIMARY KEY */
98333  i16 nPk,           /* Number of PRIMARY KEY memory cells */
98334  u8 count,          /* If non-zero, increment the row change counter */
98335  u8 onconf,         /* Default ON CONFLICT policy for triggers */
98336  u8 eMode,          /* ONEPASS_OFF, _SINGLE, or _MULTI.  See above */
98337  int iIdxNoSeek     /* Cursor number of cursor that does not need seeking */
98338){
98339  Vdbe *v = pParse->pVdbe;        /* Vdbe */
98340  int iOld = 0;                   /* First register in OLD.* array */
98341  int iLabel;                     /* Label resolved to end of generated code */
98342  u8 opSeek;                      /* Seek opcode */
98343
98344  /* Vdbe is guaranteed to have been allocated by this stage. */
98345  assert( v );
98346  VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
98347                         iDataCur, iIdxCur, iPk, (int)nPk));
98348
98349  /* Seek cursor iCur to the row to delete. If this row no longer exists
98350  ** (this can happen if a trigger program has already deleted it), do
98351  ** not attempt to delete it or fire any DELETE triggers.  */
98352  iLabel = sqlite3VdbeMakeLabel(v);
98353  opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
98354  if( eMode==ONEPASS_OFF ){
98355    sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
98356    VdbeCoverageIf(v, opSeek==OP_NotExists);
98357    VdbeCoverageIf(v, opSeek==OP_NotFound);
98358  }
98359
98360  /* If there are any triggers to fire, allocate a range of registers to
98361  ** use for the old.* references in the triggers.  */
98362  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
98363    u32 mask;                     /* Mask of OLD.* columns in use */
98364    int iCol;                     /* Iterator used while populating OLD.* */
98365    int addrStart;                /* Start of BEFORE trigger programs */
98366
98367    /* TODO: Could use temporary registers here. Also could attempt to
98368    ** avoid copying the contents of the rowid register.  */
98369    mask = sqlite3TriggerColmask(
98370        pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
98371    );
98372    mask |= sqlite3FkOldmask(pParse, pTab);
98373    iOld = pParse->nMem+1;
98374    pParse->nMem += (1 + pTab->nCol);
98375
98376    /* Populate the OLD.* pseudo-table register array. These values will be
98377    ** used by any BEFORE and AFTER triggers that exist.  */
98378    sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
98379    for(iCol=0; iCol<pTab->nCol; iCol++){
98380      testcase( mask!=0xffffffff && iCol==31 );
98381      testcase( mask!=0xffffffff && iCol==32 );
98382      if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
98383        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
98384      }
98385    }
98386
98387    /* Invoke BEFORE DELETE trigger programs. */
98388    addrStart = sqlite3VdbeCurrentAddr(v);
98389    sqlite3CodeRowTrigger(pParse, pTrigger,
98390        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
98391    );
98392
98393    /* If any BEFORE triggers were coded, then seek the cursor to the
98394    ** row to be deleted again. It may be that the BEFORE triggers moved
98395    ** the cursor or of already deleted the row that the cursor was
98396    ** pointing to.
98397    */
98398    if( addrStart<sqlite3VdbeCurrentAddr(v) ){
98399      sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
98400      VdbeCoverageIf(v, opSeek==OP_NotExists);
98401      VdbeCoverageIf(v, opSeek==OP_NotFound);
98402    }
98403
98404    /* Do FK processing. This call checks that any FK constraints that
98405    ** refer to this table (i.e. constraints attached to other tables)
98406    ** are not violated by deleting this row.  */
98407    sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
98408  }
98409
98410  /* Delete the index and table entries. Skip this step if pTab is really
98411  ** a view (in which case the only effect of the DELETE statement is to
98412  ** fire the INSTEAD OF triggers).  */
98413  if( pTab->pSelect==0 ){
98414    sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
98415    sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
98416    if( count ){
98417      sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
98418    }
98419    if( iIdxNoSeek>=0 ){
98420      sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
98421    }
98422    sqlite3VdbeChangeP5(v, eMode==ONEPASS_MULTI);
98423  }
98424
98425  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
98426  ** handle rows (possibly in other tables) that refer via a foreign key
98427  ** to the row just deleted. */
98428  sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
98429
98430  /* Invoke AFTER DELETE trigger programs. */
98431  sqlite3CodeRowTrigger(pParse, pTrigger,
98432      TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
98433  );
98434
98435  /* Jump here if the row had already been deleted before any BEFORE
98436  ** trigger programs were invoked. Or if a trigger program throws a
98437  ** RAISE(IGNORE) exception.  */
98438  sqlite3VdbeResolveLabel(v, iLabel);
98439  VdbeModuleComment((v, "END: GenRowDel()"));
98440}
98441
98442/*
98443** This routine generates VDBE code that causes the deletion of all
98444** index entries associated with a single row of a single table, pTab
98445**
98446** Preconditions:
98447**
98448**   1.  A read/write cursor "iDataCur" must be open on the canonical storage
98449**       btree for the table pTab.  (This will be either the table itself
98450**       for rowid tables or to the primary key index for WITHOUT ROWID
98451**       tables.)
98452**
98453**   2.  Read/write cursors for all indices of pTab must be open as
98454**       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
98455**       index is the 0-th index.)
98456**
98457**   3.  The "iDataCur" cursor must be already be positioned on the row
98458**       that is to be deleted.
98459*/
98460SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
98461  Parse *pParse,     /* Parsing and code generating context */
98462  Table *pTab,       /* Table containing the row to be deleted */
98463  int iDataCur,      /* Cursor of table holding data. */
98464  int iIdxCur,       /* First index cursor */
98465  int *aRegIdx,      /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
98466  int iIdxNoSeek     /* Do not delete from this cursor */
98467){
98468  int i;             /* Index loop counter */
98469  int r1 = -1;       /* Register holding an index key */
98470  int iPartIdxLabel; /* Jump destination for skipping partial index entries */
98471  Index *pIdx;       /* Current index */
98472  Index *pPrior = 0; /* Prior index */
98473  Vdbe *v;           /* The prepared statement under construction */
98474  Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */
98475
98476  v = pParse->pVdbe;
98477  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
98478  for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
98479    assert( iIdxCur+i!=iDataCur || pPk==pIdx );
98480    if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
98481    if( pIdx==pPk ) continue;
98482    if( iIdxCur+i==iIdxNoSeek ) continue;
98483    VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
98484    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
98485        &iPartIdxLabel, pPrior, r1);
98486    sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
98487        pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
98488    sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
98489    pPrior = pIdx;
98490  }
98491}
98492
98493/*
98494** Generate code that will assemble an index key and stores it in register
98495** regOut.  The key with be for index pIdx which is an index on pTab.
98496** iCur is the index of a cursor open on the pTab table and pointing to
98497** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
98498** iCur must be the cursor of the PRIMARY KEY index.
98499**
98500** Return a register number which is the first in a block of
98501** registers that holds the elements of the index key.  The
98502** block of registers has already been deallocated by the time
98503** this routine returns.
98504**
98505** If *piPartIdxLabel is not NULL, fill it in with a label and jump
98506** to that label if pIdx is a partial index that should be skipped.
98507** The label should be resolved using sqlite3ResolvePartIdxLabel().
98508** A partial index should be skipped if its WHERE clause evaluates
98509** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
98510** will be set to zero which is an empty label that is ignored by
98511** sqlite3ResolvePartIdxLabel().
98512**
98513** The pPrior and regPrior parameters are used to implement a cache to
98514** avoid unnecessary register loads.  If pPrior is not NULL, then it is
98515** a pointer to a different index for which an index key has just been
98516** computed into register regPrior.  If the current pIdx index is generating
98517** its key into the same sequence of registers and if pPrior and pIdx share
98518** a column in common, then the register corresponding to that column already
98519** holds the correct value and the loading of that register is skipped.
98520** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
98521** on a table with multiple indices, and especially with the ROWID or
98522** PRIMARY KEY columns of the index.
98523*/
98524SQLITE_PRIVATE int sqlite3GenerateIndexKey(
98525  Parse *pParse,       /* Parsing context */
98526  Index *pIdx,         /* The index for which to generate a key */
98527  int iDataCur,        /* Cursor number from which to take column data */
98528  int regOut,          /* Put the new key into this register if not 0 */
98529  int prefixOnly,      /* Compute only a unique prefix of the key */
98530  int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
98531  Index *pPrior,       /* Previously generated index key */
98532  int regPrior         /* Register holding previous generated key */
98533){
98534  Vdbe *v = pParse->pVdbe;
98535  int j;
98536  int regBase;
98537  int nCol;
98538
98539  if( piPartIdxLabel ){
98540    if( pIdx->pPartIdxWhere ){
98541      *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
98542      pParse->iSelfTab = iDataCur;
98543      sqlite3ExprCachePush(pParse);
98544      sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
98545                            SQLITE_JUMPIFNULL);
98546    }else{
98547      *piPartIdxLabel = 0;
98548    }
98549  }
98550  nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
98551  regBase = sqlite3GetTempRange(pParse, nCol);
98552  if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
98553  for(j=0; j<nCol; j++){
98554    if( pPrior
98555     && pPrior->aiColumn[j]==pIdx->aiColumn[j]
98556     && pPrior->aiColumn[j]!=XN_EXPR
98557    ){
98558      /* This column was already computed by the previous index */
98559      continue;
98560    }
98561    sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
98562    /* If the column affinity is REAL but the number is an integer, then it
98563    ** might be stored in the table as an integer (using a compact
98564    ** representation) then converted to REAL by an OP_RealAffinity opcode.
98565    ** But we are getting ready to store this value back into an index, where
98566    ** it should be converted by to INTEGER again.  So omit the OP_RealAffinity
98567    ** opcode if it is present */
98568    sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
98569  }
98570  if( regOut ){
98571    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
98572  }
98573  sqlite3ReleaseTempRange(pParse, regBase, nCol);
98574  return regBase;
98575}
98576
98577/*
98578** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
98579** because it was a partial index, then this routine should be called to
98580** resolve that label.
98581*/
98582SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
98583  if( iLabel ){
98584    sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
98585    sqlite3ExprCachePop(pParse);
98586  }
98587}
98588
98589/************** End of delete.c **********************************************/
98590/************** Begin file func.c ********************************************/
98591/*
98592** 2002 February 23
98593**
98594** The author disclaims copyright to this source code.  In place of
98595** a legal notice, here is a blessing:
98596**
98597**    May you do good and not evil.
98598**    May you find forgiveness for yourself and forgive others.
98599**    May you share freely, never taking more than you give.
98600**
98601*************************************************************************
98602** This file contains the C-language implementations for many of the SQL
98603** functions of SQLite.  (Some function, and in particular the date and
98604** time functions, are implemented separately.)
98605*/
98606/* #include "sqliteInt.h" */
98607/* #include <stdlib.h> */
98608/* #include <assert.h> */
98609/* #include "vdbeInt.h" */
98610
98611/*
98612** Return the collating function associated with a function.
98613*/
98614static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
98615  VdbeOp *pOp;
98616  assert( context->pVdbe!=0 );
98617  pOp = &context->pVdbe->aOp[context->iOp-1];
98618  assert( pOp->opcode==OP_CollSeq );
98619  assert( pOp->p4type==P4_COLLSEQ );
98620  return pOp->p4.pColl;
98621}
98622
98623/*
98624** Indicate that the accumulator load should be skipped on this
98625** iteration of the aggregate loop.
98626*/
98627static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
98628  context->skipFlag = 1;
98629}
98630
98631/*
98632** Implementation of the non-aggregate min() and max() functions
98633*/
98634static void minmaxFunc(
98635  sqlite3_context *context,
98636  int argc,
98637  sqlite3_value **argv
98638){
98639  int i;
98640  int mask;    /* 0 for min() or 0xffffffff for max() */
98641  int iBest;
98642  CollSeq *pColl;
98643
98644  assert( argc>1 );
98645  mask = sqlite3_user_data(context)==0 ? 0 : -1;
98646  pColl = sqlite3GetFuncCollSeq(context);
98647  assert( pColl );
98648  assert( mask==-1 || mask==0 );
98649  iBest = 0;
98650  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
98651  for(i=1; i<argc; i++){
98652    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
98653    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
98654      testcase( mask==0 );
98655      iBest = i;
98656    }
98657  }
98658  sqlite3_result_value(context, argv[iBest]);
98659}
98660
98661/*
98662** Return the type of the argument.
98663*/
98664static void typeofFunc(
98665  sqlite3_context *context,
98666  int NotUsed,
98667  sqlite3_value **argv
98668){
98669  const char *z = 0;
98670  UNUSED_PARAMETER(NotUsed);
98671  switch( sqlite3_value_type(argv[0]) ){
98672    case SQLITE_INTEGER: z = "integer"; break;
98673    case SQLITE_TEXT:    z = "text";    break;
98674    case SQLITE_FLOAT:   z = "real";    break;
98675    case SQLITE_BLOB:    z = "blob";    break;
98676    default:             z = "null";    break;
98677  }
98678  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
98679}
98680
98681
98682/*
98683** Implementation of the length() function
98684*/
98685static void lengthFunc(
98686  sqlite3_context *context,
98687  int argc,
98688  sqlite3_value **argv
98689){
98690  int len;
98691
98692  assert( argc==1 );
98693  UNUSED_PARAMETER(argc);
98694  switch( sqlite3_value_type(argv[0]) ){
98695    case SQLITE_BLOB:
98696    case SQLITE_INTEGER:
98697    case SQLITE_FLOAT: {
98698      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
98699      break;
98700    }
98701    case SQLITE_TEXT: {
98702      const unsigned char *z = sqlite3_value_text(argv[0]);
98703      if( z==0 ) return;
98704      len = 0;
98705      while( *z ){
98706        len++;
98707        SQLITE_SKIP_UTF8(z);
98708      }
98709      sqlite3_result_int(context, len);
98710      break;
98711    }
98712    default: {
98713      sqlite3_result_null(context);
98714      break;
98715    }
98716  }
98717}
98718
98719/*
98720** Implementation of the abs() function.
98721**
98722** IMP: R-23979-26855 The abs(X) function returns the absolute value of
98723** the numeric argument X.
98724*/
98725static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
98726  assert( argc==1 );
98727  UNUSED_PARAMETER(argc);
98728  switch( sqlite3_value_type(argv[0]) ){
98729    case SQLITE_INTEGER: {
98730      i64 iVal = sqlite3_value_int64(argv[0]);
98731      if( iVal<0 ){
98732        if( iVal==SMALLEST_INT64 ){
98733          /* IMP: R-31676-45509 If X is the integer -9223372036854775808
98734          ** then abs(X) throws an integer overflow error since there is no
98735          ** equivalent positive 64-bit two complement value. */
98736          sqlite3_result_error(context, "integer overflow", -1);
98737          return;
98738        }
98739        iVal = -iVal;
98740      }
98741      sqlite3_result_int64(context, iVal);
98742      break;
98743    }
98744    case SQLITE_NULL: {
98745      /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
98746      sqlite3_result_null(context);
98747      break;
98748    }
98749    default: {
98750      /* Because sqlite3_value_double() returns 0.0 if the argument is not
98751      ** something that can be converted into a number, we have:
98752      ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
98753      ** that cannot be converted to a numeric value.
98754      */
98755      double rVal = sqlite3_value_double(argv[0]);
98756      if( rVal<0 ) rVal = -rVal;
98757      sqlite3_result_double(context, rVal);
98758      break;
98759    }
98760  }
98761}
98762
98763/*
98764** Implementation of the instr() function.
98765**
98766** instr(haystack,needle) finds the first occurrence of needle
98767** in haystack and returns the number of previous characters plus 1,
98768** or 0 if needle does not occur within haystack.
98769**
98770** If both haystack and needle are BLOBs, then the result is one more than
98771** the number of bytes in haystack prior to the first occurrence of needle,
98772** or 0 if needle never occurs in haystack.
98773*/
98774static void instrFunc(
98775  sqlite3_context *context,
98776  int argc,
98777  sqlite3_value **argv
98778){
98779  const unsigned char *zHaystack;
98780  const unsigned char *zNeedle;
98781  int nHaystack;
98782  int nNeedle;
98783  int typeHaystack, typeNeedle;
98784  int N = 1;
98785  int isText;
98786
98787  UNUSED_PARAMETER(argc);
98788  typeHaystack = sqlite3_value_type(argv[0]);
98789  typeNeedle = sqlite3_value_type(argv[1]);
98790  if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
98791  nHaystack = sqlite3_value_bytes(argv[0]);
98792  nNeedle = sqlite3_value_bytes(argv[1]);
98793  if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
98794    zHaystack = sqlite3_value_blob(argv[0]);
98795    zNeedle = sqlite3_value_blob(argv[1]);
98796    isText = 0;
98797  }else{
98798    zHaystack = sqlite3_value_text(argv[0]);
98799    zNeedle = sqlite3_value_text(argv[1]);
98800    isText = 1;
98801  }
98802  while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
98803    N++;
98804    do{
98805      nHaystack--;
98806      zHaystack++;
98807    }while( isText && (zHaystack[0]&0xc0)==0x80 );
98808  }
98809  if( nNeedle>nHaystack ) N = 0;
98810  sqlite3_result_int(context, N);
98811}
98812
98813/*
98814** Implementation of the printf() function.
98815*/
98816static void printfFunc(
98817  sqlite3_context *context,
98818  int argc,
98819  sqlite3_value **argv
98820){
98821  PrintfArguments x;
98822  StrAccum str;
98823  const char *zFormat;
98824  int n;
98825  sqlite3 *db = sqlite3_context_db_handle(context);
98826
98827  if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
98828    x.nArg = argc-1;
98829    x.nUsed = 0;
98830    x.apArg = argv+1;
98831    sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
98832    sqlite3XPrintf(&str, SQLITE_PRINTF_SQLFUNC, zFormat, &x);
98833    n = str.nChar;
98834    sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
98835                        SQLITE_DYNAMIC);
98836  }
98837}
98838
98839/*
98840** Implementation of the substr() function.
98841**
98842** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
98843** p1 is 1-indexed.  So substr(x,1,1) returns the first character
98844** of x.  If x is text, then we actually count UTF-8 characters.
98845** If x is a blob, then we count bytes.
98846**
98847** If p1 is negative, then we begin abs(p1) from the end of x[].
98848**
98849** If p2 is negative, return the p2 characters preceding p1.
98850*/
98851static void substrFunc(
98852  sqlite3_context *context,
98853  int argc,
98854  sqlite3_value **argv
98855){
98856  const unsigned char *z;
98857  const unsigned char *z2;
98858  int len;
98859  int p0type;
98860  i64 p1, p2;
98861  int negP2 = 0;
98862
98863  assert( argc==3 || argc==2 );
98864  if( sqlite3_value_type(argv[1])==SQLITE_NULL
98865   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
98866  ){
98867    return;
98868  }
98869  p0type = sqlite3_value_type(argv[0]);
98870  p1 = sqlite3_value_int(argv[1]);
98871  if( p0type==SQLITE_BLOB ){
98872    len = sqlite3_value_bytes(argv[0]);
98873    z = sqlite3_value_blob(argv[0]);
98874    if( z==0 ) return;
98875    assert( len==sqlite3_value_bytes(argv[0]) );
98876  }else{
98877    z = sqlite3_value_text(argv[0]);
98878    if( z==0 ) return;
98879    len = 0;
98880    if( p1<0 ){
98881      for(z2=z; *z2; len++){
98882        SQLITE_SKIP_UTF8(z2);
98883      }
98884    }
98885  }
98886#ifdef SQLITE_SUBSTR_COMPATIBILITY
98887  /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
98888  ** as substr(X,1,N) - it returns the first N characters of X.  This
98889  ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
98890  ** from 2009-02-02 for compatibility of applications that exploited the
98891  ** old buggy behavior. */
98892  if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
98893#endif
98894  if( argc==3 ){
98895    p2 = sqlite3_value_int(argv[2]);
98896    if( p2<0 ){
98897      p2 = -p2;
98898      negP2 = 1;
98899    }
98900  }else{
98901    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
98902  }
98903  if( p1<0 ){
98904    p1 += len;
98905    if( p1<0 ){
98906      p2 += p1;
98907      if( p2<0 ) p2 = 0;
98908      p1 = 0;
98909    }
98910  }else if( p1>0 ){
98911    p1--;
98912  }else if( p2>0 ){
98913    p2--;
98914  }
98915  if( negP2 ){
98916    p1 -= p2;
98917    if( p1<0 ){
98918      p2 += p1;
98919      p1 = 0;
98920    }
98921  }
98922  assert( p1>=0 && p2>=0 );
98923  if( p0type!=SQLITE_BLOB ){
98924    while( *z && p1 ){
98925      SQLITE_SKIP_UTF8(z);
98926      p1--;
98927    }
98928    for(z2=z; *z2 && p2; p2--){
98929      SQLITE_SKIP_UTF8(z2);
98930    }
98931    sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
98932                          SQLITE_UTF8);
98933  }else{
98934    if( p1+p2>len ){
98935      p2 = len-p1;
98936      if( p2<0 ) p2 = 0;
98937    }
98938    sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
98939  }
98940}
98941
98942/*
98943** Implementation of the round() function
98944*/
98945#ifndef SQLITE_OMIT_FLOATING_POINT
98946static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
98947  int n = 0;
98948  double r;
98949  char *zBuf;
98950  assert( argc==1 || argc==2 );
98951  if( argc==2 ){
98952    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
98953    n = sqlite3_value_int(argv[1]);
98954    if( n>30 ) n = 30;
98955    if( n<0 ) n = 0;
98956  }
98957  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
98958  r = sqlite3_value_double(argv[0]);
98959  /* If Y==0 and X will fit in a 64-bit int,
98960  ** handle the rounding directly,
98961  ** otherwise use printf.
98962  */
98963  if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
98964    r = (double)((sqlite_int64)(r+0.5));
98965  }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
98966    r = -(double)((sqlite_int64)((-r)+0.5));
98967  }else{
98968    zBuf = sqlite3_mprintf("%.*f",n,r);
98969    if( zBuf==0 ){
98970      sqlite3_result_error_nomem(context);
98971      return;
98972    }
98973    sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
98974    sqlite3_free(zBuf);
98975  }
98976  sqlite3_result_double(context, r);
98977}
98978#endif
98979
98980/*
98981** Allocate nByte bytes of space using sqlite3Malloc(). If the
98982** allocation fails, call sqlite3_result_error_nomem() to notify
98983** the database handle that malloc() has failed and return NULL.
98984** If nByte is larger than the maximum string or blob length, then
98985** raise an SQLITE_TOOBIG exception and return NULL.
98986*/
98987static void *contextMalloc(sqlite3_context *context, i64 nByte){
98988  char *z;
98989  sqlite3 *db = sqlite3_context_db_handle(context);
98990  assert( nByte>0 );
98991  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
98992  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
98993  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
98994    sqlite3_result_error_toobig(context);
98995    z = 0;
98996  }else{
98997    z = sqlite3Malloc(nByte);
98998    if( !z ){
98999      sqlite3_result_error_nomem(context);
99000    }
99001  }
99002  return z;
99003}
99004
99005/*
99006** Implementation of the upper() and lower() SQL functions.
99007*/
99008static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
99009  char *z1;
99010  const char *z2;
99011  int i, n;
99012  UNUSED_PARAMETER(argc);
99013  z2 = (char*)sqlite3_value_text(argv[0]);
99014  n = sqlite3_value_bytes(argv[0]);
99015  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
99016  assert( z2==(char*)sqlite3_value_text(argv[0]) );
99017  if( z2 ){
99018    z1 = contextMalloc(context, ((i64)n)+1);
99019    if( z1 ){
99020      for(i=0; i<n; i++){
99021        z1[i] = (char)sqlite3Toupper(z2[i]);
99022      }
99023      sqlite3_result_text(context, z1, n, sqlite3_free);
99024    }
99025  }
99026}
99027static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
99028  char *z1;
99029  const char *z2;
99030  int i, n;
99031  UNUSED_PARAMETER(argc);
99032  z2 = (char*)sqlite3_value_text(argv[0]);
99033  n = sqlite3_value_bytes(argv[0]);
99034  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
99035  assert( z2==(char*)sqlite3_value_text(argv[0]) );
99036  if( z2 ){
99037    z1 = contextMalloc(context, ((i64)n)+1);
99038    if( z1 ){
99039      for(i=0; i<n; i++){
99040        z1[i] = sqlite3Tolower(z2[i]);
99041      }
99042      sqlite3_result_text(context, z1, n, sqlite3_free);
99043    }
99044  }
99045}
99046
99047/*
99048** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
99049** as VDBE code so that unused argument values do not have to be computed.
99050** However, we still need some kind of function implementation for this
99051** routines in the function table.  The noopFunc macro provides this.
99052** noopFunc will never be called so it doesn't matter what the implementation
99053** is.  We might as well use the "version()" function as a substitute.
99054*/
99055#define noopFunc versionFunc   /* Substitute function - never called */
99056
99057/*
99058** Implementation of random().  Return a random integer.
99059*/
99060static void randomFunc(
99061  sqlite3_context *context,
99062  int NotUsed,
99063  sqlite3_value **NotUsed2
99064){
99065  sqlite_int64 r;
99066  UNUSED_PARAMETER2(NotUsed, NotUsed2);
99067  sqlite3_randomness(sizeof(r), &r);
99068  if( r<0 ){
99069    /* We need to prevent a random number of 0x8000000000000000
99070    ** (or -9223372036854775808) since when you do abs() of that
99071    ** number of you get the same value back again.  To do this
99072    ** in a way that is testable, mask the sign bit off of negative
99073    ** values, resulting in a positive value.  Then take the
99074    ** 2s complement of that positive value.  The end result can
99075    ** therefore be no less than -9223372036854775807.
99076    */
99077    r = -(r & LARGEST_INT64);
99078  }
99079  sqlite3_result_int64(context, r);
99080}
99081
99082/*
99083** Implementation of randomblob(N).  Return a random blob
99084** that is N bytes long.
99085*/
99086static void randomBlob(
99087  sqlite3_context *context,
99088  int argc,
99089  sqlite3_value **argv
99090){
99091  int n;
99092  unsigned char *p;
99093  assert( argc==1 );
99094  UNUSED_PARAMETER(argc);
99095  n = sqlite3_value_int(argv[0]);
99096  if( n<1 ){
99097    n = 1;
99098  }
99099  p = contextMalloc(context, n);
99100  if( p ){
99101    sqlite3_randomness(n, p);
99102    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
99103  }
99104}
99105
99106/*
99107** Implementation of the last_insert_rowid() SQL function.  The return
99108** value is the same as the sqlite3_last_insert_rowid() API function.
99109*/
99110static void last_insert_rowid(
99111  sqlite3_context *context,
99112  int NotUsed,
99113  sqlite3_value **NotUsed2
99114){
99115  sqlite3 *db = sqlite3_context_db_handle(context);
99116  UNUSED_PARAMETER2(NotUsed, NotUsed2);
99117  /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
99118  ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
99119  ** function. */
99120  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
99121}
99122
99123/*
99124** Implementation of the changes() SQL function.
99125**
99126** IMP: R-62073-11209 The changes() SQL function is a wrapper
99127** around the sqlite3_changes() C/C++ function and hence follows the same
99128** rules for counting changes.
99129*/
99130static void changes(
99131  sqlite3_context *context,
99132  int NotUsed,
99133  sqlite3_value **NotUsed2
99134){
99135  sqlite3 *db = sqlite3_context_db_handle(context);
99136  UNUSED_PARAMETER2(NotUsed, NotUsed2);
99137  sqlite3_result_int(context, sqlite3_changes(db));
99138}
99139
99140/*
99141** Implementation of the total_changes() SQL function.  The return value is
99142** the same as the sqlite3_total_changes() API function.
99143*/
99144static void total_changes(
99145  sqlite3_context *context,
99146  int NotUsed,
99147  sqlite3_value **NotUsed2
99148){
99149  sqlite3 *db = sqlite3_context_db_handle(context);
99150  UNUSED_PARAMETER2(NotUsed, NotUsed2);
99151  /* IMP: R-52756-41993 This function is a wrapper around the
99152  ** sqlite3_total_changes() C/C++ interface. */
99153  sqlite3_result_int(context, sqlite3_total_changes(db));
99154}
99155
99156/*
99157** A structure defining how to do GLOB-style comparisons.
99158*/
99159struct compareInfo {
99160  u8 matchAll;
99161  u8 matchOne;
99162  u8 matchSet;
99163  u8 noCase;
99164};
99165
99166/*
99167** For LIKE and GLOB matching on EBCDIC machines, assume that every
99168** character is exactly one byte in size.  Also, provde the Utf8Read()
99169** macro for fast reading of the next character in the common case where
99170** the next character is ASCII.
99171*/
99172#if defined(SQLITE_EBCDIC)
99173# define sqlite3Utf8Read(A)        (*((*A)++))
99174# define Utf8Read(A)               (*(A++))
99175#else
99176# define Utf8Read(A)               (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
99177#endif
99178
99179static const struct compareInfo globInfo = { '*', '?', '[', 0 };
99180/* The correct SQL-92 behavior is for the LIKE operator to ignore
99181** case.  Thus  'a' LIKE 'A' would be true. */
99182static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
99183/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
99184** is case sensitive causing 'a' LIKE 'A' to be false */
99185static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
99186
99187/*
99188** Compare two UTF-8 strings for equality where the first string can
99189** potentially be a "glob" or "like" expression.  Return true (1) if they
99190** are the same and false (0) if they are different.
99191**
99192** Globbing rules:
99193**
99194**      '*'       Matches any sequence of zero or more characters.
99195**
99196**      '?'       Matches exactly one character.
99197**
99198**     [...]      Matches one character from the enclosed list of
99199**                characters.
99200**
99201**     [^...]     Matches one character not in the enclosed list.
99202**
99203** With the [...] and [^...] matching, a ']' character can be included
99204** in the list by making it the first character after '[' or '^'.  A
99205** range of characters can be specified using '-'.  Example:
99206** "[a-z]" matches any single lower-case letter.  To match a '-', make
99207** it the last character in the list.
99208**
99209** Like matching rules:
99210**
99211**      '%'       Matches any sequence of zero or more characters
99212**
99213***     '_'       Matches any one character
99214**
99215**      Ec        Where E is the "esc" character and c is any other
99216**                character, including '%', '_', and esc, match exactly c.
99217**
99218** The comments within this routine usually assume glob matching.
99219**
99220** This routine is usually quick, but can be N**2 in the worst case.
99221*/
99222static int patternCompare(
99223  const u8 *zPattern,              /* The glob pattern */
99224  const u8 *zString,               /* The string to compare against the glob */
99225  const struct compareInfo *pInfo, /* Information about how to do the compare */
99226  u32 esc                          /* The escape character */
99227){
99228  u32 c, c2;                       /* Next pattern and input string chars */
99229  u32 matchOne = pInfo->matchOne;  /* "?" or "_" */
99230  u32 matchAll = pInfo->matchAll;  /* "*" or "%" */
99231  u32 matchOther;                  /* "[" or the escape character */
99232  u8 noCase = pInfo->noCase;       /* True if uppercase==lowercase */
99233  const u8 *zEscaped = 0;          /* One past the last escaped input char */
99234
99235  /* The GLOB operator does not have an ESCAPE clause.  And LIKE does not
99236  ** have the matchSet operator.  So we either have to look for one or
99237  ** the other, never both.  Hence the single variable matchOther is used
99238  ** to store the one we have to look for.
99239  */
99240  matchOther = esc ? esc : pInfo->matchSet;
99241
99242  while( (c = Utf8Read(zPattern))!=0 ){
99243    if( c==matchAll ){  /* Match "*" */
99244      /* Skip over multiple "*" characters in the pattern.  If there
99245      ** are also "?" characters, skip those as well, but consume a
99246      ** single character of the input string for each "?" skipped */
99247      while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
99248        if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
99249          return 0;
99250        }
99251      }
99252      if( c==0 ){
99253        return 1;   /* "*" at the end of the pattern matches */
99254      }else if( c==matchOther ){
99255        if( esc ){
99256          c = sqlite3Utf8Read(&zPattern);
99257          if( c==0 ) return 0;
99258        }else{
99259          /* "[...]" immediately follows the "*".  We have to do a slow
99260          ** recursive search in this case, but it is an unusual case. */
99261          assert( matchOther<0x80 );  /* '[' is a single-byte character */
99262          while( *zString
99263                 && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
99264            SQLITE_SKIP_UTF8(zString);
99265          }
99266          return *zString!=0;
99267        }
99268      }
99269
99270      /* At this point variable c contains the first character of the
99271      ** pattern string past the "*".  Search in the input string for the
99272      ** first matching character and recursively contine the match from
99273      ** that point.
99274      **
99275      ** For a case-insensitive search, set variable cx to be the same as
99276      ** c but in the other case and search the input string for either
99277      ** c or cx.
99278      */
99279      if( c<=0x80 ){
99280        u32 cx;
99281        if( noCase ){
99282          cx = sqlite3Toupper(c);
99283          c = sqlite3Tolower(c);
99284        }else{
99285          cx = c;
99286        }
99287        while( (c2 = *(zString++))!=0 ){
99288          if( c2!=c && c2!=cx ) continue;
99289          if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
99290        }
99291      }else{
99292        while( (c2 = Utf8Read(zString))!=0 ){
99293          if( c2!=c ) continue;
99294          if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
99295        }
99296      }
99297      return 0;
99298    }
99299    if( c==matchOther ){
99300      if( esc ){
99301        c = sqlite3Utf8Read(&zPattern);
99302        if( c==0 ) return 0;
99303        zEscaped = zPattern;
99304      }else{
99305        u32 prior_c = 0;
99306        int seen = 0;
99307        int invert = 0;
99308        c = sqlite3Utf8Read(&zString);
99309        if( c==0 ) return 0;
99310        c2 = sqlite3Utf8Read(&zPattern);
99311        if( c2=='^' ){
99312          invert = 1;
99313          c2 = sqlite3Utf8Read(&zPattern);
99314        }
99315        if( c2==']' ){
99316          if( c==']' ) seen = 1;
99317          c2 = sqlite3Utf8Read(&zPattern);
99318        }
99319        while( c2 && c2!=']' ){
99320          if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
99321            c2 = sqlite3Utf8Read(&zPattern);
99322            if( c>=prior_c && c<=c2 ) seen = 1;
99323            prior_c = 0;
99324          }else{
99325            if( c==c2 ){
99326              seen = 1;
99327            }
99328            prior_c = c2;
99329          }
99330          c2 = sqlite3Utf8Read(&zPattern);
99331        }
99332        if( c2==0 || (seen ^ invert)==0 ){
99333          return 0;
99334        }
99335        continue;
99336      }
99337    }
99338    c2 = Utf8Read(zString);
99339    if( c==c2 ) continue;
99340    if( noCase && c<0x80 && c2<0x80 && sqlite3Tolower(c)==sqlite3Tolower(c2) ){
99341      continue;
99342    }
99343    if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
99344    return 0;
99345  }
99346  return *zString==0;
99347}
99348
99349/*
99350** The sqlite3_strglob() interface.
99351*/
99352SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlobPattern, const char *zString){
99353  return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
99354}
99355
99356/*
99357** Count the number of times that the LIKE operator (or GLOB which is
99358** just a variation of LIKE) gets called.  This is used for testing
99359** only.
99360*/
99361#ifdef SQLITE_TEST
99362SQLITE_API int sqlite3_like_count = 0;
99363#endif
99364
99365
99366/*
99367** Implementation of the like() SQL function.  This function implements
99368** the build-in LIKE operator.  The first argument to the function is the
99369** pattern and the second argument is the string.  So, the SQL statements:
99370**
99371**       A LIKE B
99372**
99373** is implemented as like(B,A).
99374**
99375** This same function (with a different compareInfo structure) computes
99376** the GLOB operator.
99377*/
99378static void likeFunc(
99379  sqlite3_context *context,
99380  int argc,
99381  sqlite3_value **argv
99382){
99383  const unsigned char *zA, *zB;
99384  u32 escape = 0;
99385  int nPat;
99386  sqlite3 *db = sqlite3_context_db_handle(context);
99387
99388  zB = sqlite3_value_text(argv[0]);
99389  zA = sqlite3_value_text(argv[1]);
99390
99391  /* Limit the length of the LIKE or GLOB pattern to avoid problems
99392  ** of deep recursion and N*N behavior in patternCompare().
99393  */
99394  nPat = sqlite3_value_bytes(argv[0]);
99395  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
99396  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
99397  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
99398    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
99399    return;
99400  }
99401  assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
99402
99403  if( argc==3 ){
99404    /* The escape character string must consist of a single UTF-8 character.
99405    ** Otherwise, return an error.
99406    */
99407    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
99408    if( zEsc==0 ) return;
99409    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
99410      sqlite3_result_error(context,
99411          "ESCAPE expression must be a single character", -1);
99412      return;
99413    }
99414    escape = sqlite3Utf8Read(&zEsc);
99415  }
99416  if( zA && zB ){
99417    struct compareInfo *pInfo = sqlite3_user_data(context);
99418#ifdef SQLITE_TEST
99419    sqlite3_like_count++;
99420#endif
99421
99422    sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
99423  }
99424}
99425
99426/*
99427** Implementation of the NULLIF(x,y) function.  The result is the first
99428** argument if the arguments are different.  The result is NULL if the
99429** arguments are equal to each other.
99430*/
99431static void nullifFunc(
99432  sqlite3_context *context,
99433  int NotUsed,
99434  sqlite3_value **argv
99435){
99436  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
99437  UNUSED_PARAMETER(NotUsed);
99438  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
99439    sqlite3_result_value(context, argv[0]);
99440  }
99441}
99442
99443/*
99444** Implementation of the sqlite_version() function.  The result is the version
99445** of the SQLite library that is running.
99446*/
99447static void versionFunc(
99448  sqlite3_context *context,
99449  int NotUsed,
99450  sqlite3_value **NotUsed2
99451){
99452  UNUSED_PARAMETER2(NotUsed, NotUsed2);
99453  /* IMP: R-48699-48617 This function is an SQL wrapper around the
99454  ** sqlite3_libversion() C-interface. */
99455  sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
99456}
99457
99458/*
99459** Implementation of the sqlite_source_id() function. The result is a string
99460** that identifies the particular version of the source code used to build
99461** SQLite.
99462*/
99463static void sourceidFunc(
99464  sqlite3_context *context,
99465  int NotUsed,
99466  sqlite3_value **NotUsed2
99467){
99468  UNUSED_PARAMETER2(NotUsed, NotUsed2);
99469  /* IMP: R-24470-31136 This function is an SQL wrapper around the
99470  ** sqlite3_sourceid() C interface. */
99471  sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
99472}
99473
99474/*
99475** Implementation of the sqlite_log() function.  This is a wrapper around
99476** sqlite3_log().  The return value is NULL.  The function exists purely for
99477** its side-effects.
99478*/
99479static void errlogFunc(
99480  sqlite3_context *context,
99481  int argc,
99482  sqlite3_value **argv
99483){
99484  UNUSED_PARAMETER(argc);
99485  UNUSED_PARAMETER(context);
99486  sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
99487}
99488
99489/*
99490** Implementation of the sqlite_compileoption_used() function.
99491** The result is an integer that identifies if the compiler option
99492** was used to build SQLite.
99493*/
99494#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
99495static void compileoptionusedFunc(
99496  sqlite3_context *context,
99497  int argc,
99498  sqlite3_value **argv
99499){
99500  const char *zOptName;
99501  assert( argc==1 );
99502  UNUSED_PARAMETER(argc);
99503  /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
99504  ** function is a wrapper around the sqlite3_compileoption_used() C/C++
99505  ** function.
99506  */
99507  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
99508    sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
99509  }
99510}
99511#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
99512
99513/*
99514** Implementation of the sqlite_compileoption_get() function.
99515** The result is a string that identifies the compiler options
99516** used to build SQLite.
99517*/
99518#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
99519static void compileoptiongetFunc(
99520  sqlite3_context *context,
99521  int argc,
99522  sqlite3_value **argv
99523){
99524  int n;
99525  assert( argc==1 );
99526  UNUSED_PARAMETER(argc);
99527  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
99528  ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
99529  */
99530  n = sqlite3_value_int(argv[0]);
99531  sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
99532}
99533#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
99534
99535/* Array for converting from half-bytes (nybbles) into ASCII hex
99536** digits. */
99537static const char hexdigits[] = {
99538  '0', '1', '2', '3', '4', '5', '6', '7',
99539  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
99540};
99541
99542/*
99543** Implementation of the QUOTE() function.  This function takes a single
99544** argument.  If the argument is numeric, the return value is the same as
99545** the argument.  If the argument is NULL, the return value is the string
99546** "NULL".  Otherwise, the argument is enclosed in single quotes with
99547** single-quote escapes.
99548*/
99549static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
99550  assert( argc==1 );
99551  UNUSED_PARAMETER(argc);
99552  switch( sqlite3_value_type(argv[0]) ){
99553    case SQLITE_FLOAT: {
99554      double r1, r2;
99555      char zBuf[50];
99556      r1 = sqlite3_value_double(argv[0]);
99557      sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
99558      sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
99559      if( r1!=r2 ){
99560        sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
99561      }
99562      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
99563      break;
99564    }
99565    case SQLITE_INTEGER: {
99566      sqlite3_result_value(context, argv[0]);
99567      break;
99568    }
99569    case SQLITE_BLOB: {
99570      char *zText = 0;
99571      char const *zBlob = sqlite3_value_blob(argv[0]);
99572      int nBlob = sqlite3_value_bytes(argv[0]);
99573      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
99574      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
99575      if( zText ){
99576        int i;
99577        for(i=0; i<nBlob; i++){
99578          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
99579          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
99580        }
99581        zText[(nBlob*2)+2] = '\'';
99582        zText[(nBlob*2)+3] = '\0';
99583        zText[0] = 'X';
99584        zText[1] = '\'';
99585        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
99586        sqlite3_free(zText);
99587      }
99588      break;
99589    }
99590    case SQLITE_TEXT: {
99591      int i,j;
99592      u64 n;
99593      const unsigned char *zArg = sqlite3_value_text(argv[0]);
99594      char *z;
99595
99596      if( zArg==0 ) return;
99597      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
99598      z = contextMalloc(context, ((i64)i)+((i64)n)+3);
99599      if( z ){
99600        z[0] = '\'';
99601        for(i=0, j=1; zArg[i]; i++){
99602          z[j++] = zArg[i];
99603          if( zArg[i]=='\'' ){
99604            z[j++] = '\'';
99605          }
99606        }
99607        z[j++] = '\'';
99608        z[j] = 0;
99609        sqlite3_result_text(context, z, j, sqlite3_free);
99610      }
99611      break;
99612    }
99613    default: {
99614      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
99615      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
99616      break;
99617    }
99618  }
99619}
99620
99621/*
99622** The unicode() function.  Return the integer unicode code-point value
99623** for the first character of the input string.
99624*/
99625static void unicodeFunc(
99626  sqlite3_context *context,
99627  int argc,
99628  sqlite3_value **argv
99629){
99630  const unsigned char *z = sqlite3_value_text(argv[0]);
99631  (void)argc;
99632  if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
99633}
99634
99635/*
99636** The char() function takes zero or more arguments, each of which is
99637** an integer.  It constructs a string where each character of the string
99638** is the unicode character for the corresponding integer argument.
99639*/
99640static void charFunc(
99641  sqlite3_context *context,
99642  int argc,
99643  sqlite3_value **argv
99644){
99645  unsigned char *z, *zOut;
99646  int i;
99647  zOut = z = sqlite3_malloc64( argc*4+1 );
99648  if( z==0 ){
99649    sqlite3_result_error_nomem(context);
99650    return;
99651  }
99652  for(i=0; i<argc; i++){
99653    sqlite3_int64 x;
99654    unsigned c;
99655    x = sqlite3_value_int64(argv[i]);
99656    if( x<0 || x>0x10ffff ) x = 0xfffd;
99657    c = (unsigned)(x & 0x1fffff);
99658    if( c<0x00080 ){
99659      *zOut++ = (u8)(c&0xFF);
99660    }else if( c<0x00800 ){
99661      *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
99662      *zOut++ = 0x80 + (u8)(c & 0x3F);
99663    }else if( c<0x10000 ){
99664      *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
99665      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
99666      *zOut++ = 0x80 + (u8)(c & 0x3F);
99667    }else{
99668      *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
99669      *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
99670      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
99671      *zOut++ = 0x80 + (u8)(c & 0x3F);
99672    }                                                    \
99673  }
99674  sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
99675}
99676
99677/*
99678** The hex() function.  Interpret the argument as a blob.  Return
99679** a hexadecimal rendering as text.
99680*/
99681static void hexFunc(
99682  sqlite3_context *context,
99683  int argc,
99684  sqlite3_value **argv
99685){
99686  int i, n;
99687  const unsigned char *pBlob;
99688  char *zHex, *z;
99689  assert( argc==1 );
99690  UNUSED_PARAMETER(argc);
99691  pBlob = sqlite3_value_blob(argv[0]);
99692  n = sqlite3_value_bytes(argv[0]);
99693  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
99694  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
99695  if( zHex ){
99696    for(i=0; i<n; i++, pBlob++){
99697      unsigned char c = *pBlob;
99698      *(z++) = hexdigits[(c>>4)&0xf];
99699      *(z++) = hexdigits[c&0xf];
99700    }
99701    *z = 0;
99702    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
99703  }
99704}
99705
99706/*
99707** The zeroblob(N) function returns a zero-filled blob of size N bytes.
99708*/
99709static void zeroblobFunc(
99710  sqlite3_context *context,
99711  int argc,
99712  sqlite3_value **argv
99713){
99714  i64 n;
99715  int rc;
99716  assert( argc==1 );
99717  UNUSED_PARAMETER(argc);
99718  n = sqlite3_value_int64(argv[0]);
99719  if( n<0 ) n = 0;
99720  rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
99721  if( rc ){
99722    sqlite3_result_error_code(context, rc);
99723  }
99724}
99725
99726/*
99727** The replace() function.  Three arguments are all strings: call
99728** them A, B, and C. The result is also a string which is derived
99729** from A by replacing every occurrence of B with C.  The match
99730** must be exact.  Collating sequences are not used.
99731*/
99732static void replaceFunc(
99733  sqlite3_context *context,
99734  int argc,
99735  sqlite3_value **argv
99736){
99737  const unsigned char *zStr;        /* The input string A */
99738  const unsigned char *zPattern;    /* The pattern string B */
99739  const unsigned char *zRep;        /* The replacement string C */
99740  unsigned char *zOut;              /* The output */
99741  int nStr;                /* Size of zStr */
99742  int nPattern;            /* Size of zPattern */
99743  int nRep;                /* Size of zRep */
99744  i64 nOut;                /* Maximum size of zOut */
99745  int loopLimit;           /* Last zStr[] that might match zPattern[] */
99746  int i, j;                /* Loop counters */
99747
99748  assert( argc==3 );
99749  UNUSED_PARAMETER(argc);
99750  zStr = sqlite3_value_text(argv[0]);
99751  if( zStr==0 ) return;
99752  nStr = sqlite3_value_bytes(argv[0]);
99753  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
99754  zPattern = sqlite3_value_text(argv[1]);
99755  if( zPattern==0 ){
99756    assert( sqlite3_value_type(argv[1])==SQLITE_NULL
99757            || sqlite3_context_db_handle(context)->mallocFailed );
99758    return;
99759  }
99760  if( zPattern[0]==0 ){
99761    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
99762    sqlite3_result_value(context, argv[0]);
99763    return;
99764  }
99765  nPattern = sqlite3_value_bytes(argv[1]);
99766  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
99767  zRep = sqlite3_value_text(argv[2]);
99768  if( zRep==0 ) return;
99769  nRep = sqlite3_value_bytes(argv[2]);
99770  assert( zRep==sqlite3_value_text(argv[2]) );
99771  nOut = nStr + 1;
99772  assert( nOut<SQLITE_MAX_LENGTH );
99773  zOut = contextMalloc(context, (i64)nOut);
99774  if( zOut==0 ){
99775    return;
99776  }
99777  loopLimit = nStr - nPattern;
99778  for(i=j=0; i<=loopLimit; i++){
99779    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
99780      zOut[j++] = zStr[i];
99781    }else{
99782      u8 *zOld;
99783      sqlite3 *db = sqlite3_context_db_handle(context);
99784      nOut += nRep - nPattern;
99785      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
99786      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
99787      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
99788        sqlite3_result_error_toobig(context);
99789        sqlite3_free(zOut);
99790        return;
99791      }
99792      zOld = zOut;
99793      zOut = sqlite3_realloc64(zOut, (int)nOut);
99794      if( zOut==0 ){
99795        sqlite3_result_error_nomem(context);
99796        sqlite3_free(zOld);
99797        return;
99798      }
99799      memcpy(&zOut[j], zRep, nRep);
99800      j += nRep;
99801      i += nPattern-1;
99802    }
99803  }
99804  assert( j+nStr-i+1==nOut );
99805  memcpy(&zOut[j], &zStr[i], nStr-i);
99806  j += nStr - i;
99807  assert( j<=nOut );
99808  zOut[j] = 0;
99809  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
99810}
99811
99812/*
99813** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
99814** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
99815*/
99816static void trimFunc(
99817  sqlite3_context *context,
99818  int argc,
99819  sqlite3_value **argv
99820){
99821  const unsigned char *zIn;         /* Input string */
99822  const unsigned char *zCharSet;    /* Set of characters to trim */
99823  int nIn;                          /* Number of bytes in input */
99824  int flags;                        /* 1: trimleft  2: trimright  3: trim */
99825  int i;                            /* Loop counter */
99826  unsigned char *aLen = 0;          /* Length of each character in zCharSet */
99827  unsigned char **azChar = 0;       /* Individual characters in zCharSet */
99828  int nChar;                        /* Number of characters in zCharSet */
99829
99830  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
99831    return;
99832  }
99833  zIn = sqlite3_value_text(argv[0]);
99834  if( zIn==0 ) return;
99835  nIn = sqlite3_value_bytes(argv[0]);
99836  assert( zIn==sqlite3_value_text(argv[0]) );
99837  if( argc==1 ){
99838    static const unsigned char lenOne[] = { 1 };
99839    static unsigned char * const azOne[] = { (u8*)" " };
99840    nChar = 1;
99841    aLen = (u8*)lenOne;
99842    azChar = (unsigned char **)azOne;
99843    zCharSet = 0;
99844  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
99845    return;
99846  }else{
99847    const unsigned char *z;
99848    for(z=zCharSet, nChar=0; *z; nChar++){
99849      SQLITE_SKIP_UTF8(z);
99850    }
99851    if( nChar>0 ){
99852      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
99853      if( azChar==0 ){
99854        return;
99855      }
99856      aLen = (unsigned char*)&azChar[nChar];
99857      for(z=zCharSet, nChar=0; *z; nChar++){
99858        azChar[nChar] = (unsigned char *)z;
99859        SQLITE_SKIP_UTF8(z);
99860        aLen[nChar] = (u8)(z - azChar[nChar]);
99861      }
99862    }
99863  }
99864  if( nChar>0 ){
99865    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
99866    if( flags & 1 ){
99867      while( nIn>0 ){
99868        int len = 0;
99869        for(i=0; i<nChar; i++){
99870          len = aLen[i];
99871          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
99872        }
99873        if( i>=nChar ) break;
99874        zIn += len;
99875        nIn -= len;
99876      }
99877    }
99878    if( flags & 2 ){
99879      while( nIn>0 ){
99880        int len = 0;
99881        for(i=0; i<nChar; i++){
99882          len = aLen[i];
99883          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
99884        }
99885        if( i>=nChar ) break;
99886        nIn -= len;
99887      }
99888    }
99889    if( zCharSet ){
99890      sqlite3_free(azChar);
99891    }
99892  }
99893  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
99894}
99895
99896
99897/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
99898** is only available if the SQLITE_SOUNDEX compile-time option is used
99899** when SQLite is built.
99900*/
99901#ifdef SQLITE_SOUNDEX
99902/*
99903** Compute the soundex encoding of a word.
99904**
99905** IMP: R-59782-00072 The soundex(X) function returns a string that is the
99906** soundex encoding of the string X.
99907*/
99908static void soundexFunc(
99909  sqlite3_context *context,
99910  int argc,
99911  sqlite3_value **argv
99912){
99913  char zResult[8];
99914  const u8 *zIn;
99915  int i, j;
99916  static const unsigned char iCode[] = {
99917    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
99918    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
99919    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
99920    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
99921    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
99922    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
99923    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
99924    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
99925  };
99926  assert( argc==1 );
99927  zIn = (u8*)sqlite3_value_text(argv[0]);
99928  if( zIn==0 ) zIn = (u8*)"";
99929  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
99930  if( zIn[i] ){
99931    u8 prevcode = iCode[zIn[i]&0x7f];
99932    zResult[0] = sqlite3Toupper(zIn[i]);
99933    for(j=1; j<4 && zIn[i]; i++){
99934      int code = iCode[zIn[i]&0x7f];
99935      if( code>0 ){
99936        if( code!=prevcode ){
99937          prevcode = code;
99938          zResult[j++] = code + '0';
99939        }
99940      }else{
99941        prevcode = 0;
99942      }
99943    }
99944    while( j<4 ){
99945      zResult[j++] = '0';
99946    }
99947    zResult[j] = 0;
99948    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
99949  }else{
99950    /* IMP: R-64894-50321 The string "?000" is returned if the argument
99951    ** is NULL or contains no ASCII alphabetic characters. */
99952    sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
99953  }
99954}
99955#endif /* SQLITE_SOUNDEX */
99956
99957#ifndef SQLITE_OMIT_LOAD_EXTENSION
99958/*
99959** A function that loads a shared-library extension then returns NULL.
99960*/
99961static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
99962  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
99963  const char *zProc;
99964  sqlite3 *db = sqlite3_context_db_handle(context);
99965  char *zErrMsg = 0;
99966
99967  if( argc==2 ){
99968    zProc = (const char *)sqlite3_value_text(argv[1]);
99969  }else{
99970    zProc = 0;
99971  }
99972  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
99973    sqlite3_result_error(context, zErrMsg, -1);
99974    sqlite3_free(zErrMsg);
99975  }
99976}
99977#endif
99978
99979
99980/*
99981** An instance of the following structure holds the context of a
99982** sum() or avg() aggregate computation.
99983*/
99984typedef struct SumCtx SumCtx;
99985struct SumCtx {
99986  double rSum;      /* Floating point sum */
99987  i64 iSum;         /* Integer sum */
99988  i64 cnt;          /* Number of elements summed */
99989  u8 overflow;      /* True if integer overflow seen */
99990  u8 approx;        /* True if non-integer value was input to the sum */
99991};
99992
99993/*
99994** Routines used to compute the sum, average, and total.
99995**
99996** The SUM() function follows the (broken) SQL standard which means
99997** that it returns NULL if it sums over no inputs.  TOTAL returns
99998** 0.0 in that case.  In addition, TOTAL always returns a float where
99999** SUM might return an integer if it never encounters a floating point
100000** value.  TOTAL never fails, but SUM might through an exception if
100001** it overflows an integer.
100002*/
100003static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
100004  SumCtx *p;
100005  int type;
100006  assert( argc==1 );
100007  UNUSED_PARAMETER(argc);
100008  p = sqlite3_aggregate_context(context, sizeof(*p));
100009  type = sqlite3_value_numeric_type(argv[0]);
100010  if( p && type!=SQLITE_NULL ){
100011    p->cnt++;
100012    if( type==SQLITE_INTEGER ){
100013      i64 v = sqlite3_value_int64(argv[0]);
100014      p->rSum += v;
100015      if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
100016        p->overflow = 1;
100017      }
100018    }else{
100019      p->rSum += sqlite3_value_double(argv[0]);
100020      p->approx = 1;
100021    }
100022  }
100023}
100024static void sumFinalize(sqlite3_context *context){
100025  SumCtx *p;
100026  p = sqlite3_aggregate_context(context, 0);
100027  if( p && p->cnt>0 ){
100028    if( p->overflow ){
100029      sqlite3_result_error(context,"integer overflow",-1);
100030    }else if( p->approx ){
100031      sqlite3_result_double(context, p->rSum);
100032    }else{
100033      sqlite3_result_int64(context, p->iSum);
100034    }
100035  }
100036}
100037static void avgFinalize(sqlite3_context *context){
100038  SumCtx *p;
100039  p = sqlite3_aggregate_context(context, 0);
100040  if( p && p->cnt>0 ){
100041    sqlite3_result_double(context, p->rSum/(double)p->cnt);
100042  }
100043}
100044static void totalFinalize(sqlite3_context *context){
100045  SumCtx *p;
100046  p = sqlite3_aggregate_context(context, 0);
100047  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
100048  sqlite3_result_double(context, p ? p->rSum : (double)0);
100049}
100050
100051/*
100052** The following structure keeps track of state information for the
100053** count() aggregate function.
100054*/
100055typedef struct CountCtx CountCtx;
100056struct CountCtx {
100057  i64 n;
100058};
100059
100060/*
100061** Routines to implement the count() aggregate function.
100062*/
100063static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
100064  CountCtx *p;
100065  p = sqlite3_aggregate_context(context, sizeof(*p));
100066  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
100067    p->n++;
100068  }
100069
100070#ifndef SQLITE_OMIT_DEPRECATED
100071  /* The sqlite3_aggregate_count() function is deprecated.  But just to make
100072  ** sure it still operates correctly, verify that its count agrees with our
100073  ** internal count when using count(*) and when the total count can be
100074  ** expressed as a 32-bit integer. */
100075  assert( argc==1 || p==0 || p->n>0x7fffffff
100076          || p->n==sqlite3_aggregate_count(context) );
100077#endif
100078}
100079static void countFinalize(sqlite3_context *context){
100080  CountCtx *p;
100081  p = sqlite3_aggregate_context(context, 0);
100082  sqlite3_result_int64(context, p ? p->n : 0);
100083}
100084
100085/*
100086** Routines to implement min() and max() aggregate functions.
100087*/
100088static void minmaxStep(
100089  sqlite3_context *context,
100090  int NotUsed,
100091  sqlite3_value **argv
100092){
100093  Mem *pArg  = (Mem *)argv[0];
100094  Mem *pBest;
100095  UNUSED_PARAMETER(NotUsed);
100096
100097  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
100098  if( !pBest ) return;
100099
100100  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
100101    if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
100102  }else if( pBest->flags ){
100103    int max;
100104    int cmp;
100105    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
100106    /* This step function is used for both the min() and max() aggregates,
100107    ** the only difference between the two being that the sense of the
100108    ** comparison is inverted. For the max() aggregate, the
100109    ** sqlite3_user_data() function returns (void *)-1. For min() it
100110    ** returns (void *)db, where db is the sqlite3* database pointer.
100111    ** Therefore the next statement sets variable 'max' to 1 for the max()
100112    ** aggregate, or 0 for min().
100113    */
100114    max = sqlite3_user_data(context)!=0;
100115    cmp = sqlite3MemCompare(pBest, pArg, pColl);
100116    if( (max && cmp<0) || (!max && cmp>0) ){
100117      sqlite3VdbeMemCopy(pBest, pArg);
100118    }else{
100119      sqlite3SkipAccumulatorLoad(context);
100120    }
100121  }else{
100122    pBest->db = sqlite3_context_db_handle(context);
100123    sqlite3VdbeMemCopy(pBest, pArg);
100124  }
100125}
100126static void minMaxFinalize(sqlite3_context *context){
100127  sqlite3_value *pRes;
100128  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
100129  if( pRes ){
100130    if( pRes->flags ){
100131      sqlite3_result_value(context, pRes);
100132    }
100133    sqlite3VdbeMemRelease(pRes);
100134  }
100135}
100136
100137/*
100138** group_concat(EXPR, ?SEPARATOR?)
100139*/
100140static void groupConcatStep(
100141  sqlite3_context *context,
100142  int argc,
100143  sqlite3_value **argv
100144){
100145  const char *zVal;
100146  StrAccum *pAccum;
100147  const char *zSep;
100148  int nVal, nSep;
100149  assert( argc==1 || argc==2 );
100150  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
100151  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
100152
100153  if( pAccum ){
100154    sqlite3 *db = sqlite3_context_db_handle(context);
100155    int firstTerm = pAccum->mxAlloc==0;
100156    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
100157    if( !firstTerm ){
100158      if( argc==2 ){
100159        zSep = (char*)sqlite3_value_text(argv[1]);
100160        nSep = sqlite3_value_bytes(argv[1]);
100161      }else{
100162        zSep = ",";
100163        nSep = 1;
100164      }
100165      if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
100166    }
100167    zVal = (char*)sqlite3_value_text(argv[0]);
100168    nVal = sqlite3_value_bytes(argv[0]);
100169    if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
100170  }
100171}
100172static void groupConcatFinalize(sqlite3_context *context){
100173  StrAccum *pAccum;
100174  pAccum = sqlite3_aggregate_context(context, 0);
100175  if( pAccum ){
100176    if( pAccum->accError==STRACCUM_TOOBIG ){
100177      sqlite3_result_error_toobig(context);
100178    }else if( pAccum->accError==STRACCUM_NOMEM ){
100179      sqlite3_result_error_nomem(context);
100180    }else{
100181      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
100182                          sqlite3_free);
100183    }
100184  }
100185}
100186
100187/*
100188** This routine does per-connection function registration.  Most
100189** of the built-in functions above are part of the global function set.
100190** This routine only deals with those that are not global.
100191*/
100192SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
100193  int rc = sqlite3_overload_function(db, "MATCH", 2);
100194  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
100195  if( rc==SQLITE_NOMEM ){
100196    db->mallocFailed = 1;
100197  }
100198}
100199
100200/*
100201** Set the LIKEOPT flag on the 2-argument function with the given name.
100202*/
100203static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
100204  FuncDef *pDef;
100205  pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
100206                             2, SQLITE_UTF8, 0);
100207  if( ALWAYS(pDef) ){
100208    pDef->funcFlags |= flagVal;
100209  }
100210}
100211
100212/*
100213** Register the built-in LIKE and GLOB functions.  The caseSensitive
100214** parameter determines whether or not the LIKE operator is case
100215** sensitive.  GLOB is always case sensitive.
100216*/
100217SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
100218  struct compareInfo *pInfo;
100219  if( caseSensitive ){
100220    pInfo = (struct compareInfo*)&likeInfoAlt;
100221  }else{
100222    pInfo = (struct compareInfo*)&likeInfoNorm;
100223  }
100224  sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
100225  sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
100226  sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
100227      (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
100228  setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
100229  setLikeOptFlag(db, "like",
100230      caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
100231}
100232
100233/*
100234** pExpr points to an expression which implements a function.  If
100235** it is appropriate to apply the LIKE optimization to that function
100236** then set aWc[0] through aWc[2] to the wildcard characters and
100237** return TRUE.  If the function is not a LIKE-style function then
100238** return FALSE.
100239**
100240** *pIsNocase is set to true if uppercase and lowercase are equivalent for
100241** the function (default for LIKE).  If the function makes the distinction
100242** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
100243** false.
100244*/
100245SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
100246  FuncDef *pDef;
100247  if( pExpr->op!=TK_FUNCTION
100248   || !pExpr->x.pList
100249   || pExpr->x.pList->nExpr!=2
100250  ){
100251    return 0;
100252  }
100253  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
100254  pDef = sqlite3FindFunction(db, pExpr->u.zToken,
100255                             sqlite3Strlen30(pExpr->u.zToken),
100256                             2, SQLITE_UTF8, 0);
100257  if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
100258    return 0;
100259  }
100260
100261  /* The memcpy() statement assumes that the wildcard characters are
100262  ** the first three statements in the compareInfo structure.  The
100263  ** asserts() that follow verify that assumption
100264  */
100265  memcpy(aWc, pDef->pUserData, 3);
100266  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
100267  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
100268  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
100269  *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
100270  return 1;
100271}
100272
100273/*
100274** All of the FuncDef structures in the aBuiltinFunc[] array above
100275** to the global function hash table.  This occurs at start-time (as
100276** a consequence of calling sqlite3_initialize()).
100277**
100278** After this routine runs
100279*/
100280SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
100281  /*
100282  ** The following array holds FuncDef structures for all of the functions
100283  ** defined in this file.
100284  **
100285  ** The array cannot be constant since changes are made to the
100286  ** FuncDef.pHash elements at start-time.  The elements of this array
100287  ** are read-only after initialization is complete.
100288  */
100289  static SQLITE_WSD FuncDef aBuiltinFunc[] = {
100290    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
100291    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
100292    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
100293    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
100294    FUNCTION(trim,               1, 3, 0, trimFunc         ),
100295    FUNCTION(trim,               2, 3, 0, trimFunc         ),
100296    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
100297    FUNCTION(min,                0, 0, 1, 0                ),
100298    AGGREGATE2(min,              1, 0, 1, minmaxStep,      minMaxFinalize,
100299                                          SQLITE_FUNC_MINMAX ),
100300    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
100301    FUNCTION(max,                0, 1, 1, 0                ),
100302    AGGREGATE2(max,              1, 1, 1, minmaxStep,      minMaxFinalize,
100303                                          SQLITE_FUNC_MINMAX ),
100304    FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
100305    FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
100306    FUNCTION(instr,              2, 0, 0, instrFunc        ),
100307    FUNCTION(substr,             2, 0, 0, substrFunc       ),
100308    FUNCTION(substr,             3, 0, 0, substrFunc       ),
100309    FUNCTION(printf,            -1, 0, 0, printfFunc       ),
100310    FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
100311    FUNCTION(char,              -1, 0, 0, charFunc         ),
100312    FUNCTION(abs,                1, 0, 0, absFunc          ),
100313#ifndef SQLITE_OMIT_FLOATING_POINT
100314    FUNCTION(round,              1, 0, 0, roundFunc        ),
100315    FUNCTION(round,              2, 0, 0, roundFunc        ),
100316#endif
100317    FUNCTION(upper,              1, 0, 0, upperFunc        ),
100318    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
100319    FUNCTION(coalesce,           1, 0, 0, 0                ),
100320    FUNCTION(coalesce,           0, 0, 0, 0                ),
100321    FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
100322    FUNCTION(hex,                1, 0, 0, hexFunc          ),
100323    FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
100324    FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
100325    FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
100326    FUNCTION2(likely,            1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
100327    VFUNCTION(random,            0, 0, 0, randomFunc       ),
100328    VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
100329    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
100330    DFUNCTION(sqlite_version,    0, 0, 0, versionFunc      ),
100331    DFUNCTION(sqlite_source_id,  0, 0, 0, sourceidFunc     ),
100332    FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
100333#if SQLITE_USER_AUTHENTICATION
100334    FUNCTION(sqlite_crypt,       2, 0, 0, sqlite3CryptFunc ),
100335#endif
100336#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
100337    DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
100338    DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
100339#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
100340    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
100341    VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
100342    VFUNCTION(changes,           0, 0, 0, changes          ),
100343    VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
100344    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
100345    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
100346  #ifdef SQLITE_SOUNDEX
100347    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
100348  #endif
100349  #ifndef SQLITE_OMIT_LOAD_EXTENSION
100350    VFUNCTION(load_extension,    1, 0, 0, loadExt          ),
100351    VFUNCTION(load_extension,    2, 0, 0, loadExt          ),
100352  #endif
100353    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
100354    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
100355    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
100356    AGGREGATE2(count,            0, 0, 0, countStep,       countFinalize,
100357               SQLITE_FUNC_COUNT  ),
100358    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
100359    AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
100360    AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
100361
100362    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
100363  #ifdef SQLITE_CASE_SENSITIVE_LIKE
100364    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
100365    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
100366  #else
100367    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
100368    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
100369  #endif
100370  };
100371
100372  int i;
100373  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
100374  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
100375
100376  for(i=0; i<ArraySize(aBuiltinFunc); i++){
100377    sqlite3FuncDefInsert(pHash, &aFunc[i]);
100378  }
100379  sqlite3RegisterDateTimeFunctions();
100380#ifndef SQLITE_OMIT_ALTERTABLE
100381  sqlite3AlterFunctions();
100382#endif
100383#if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
100384  sqlite3AnalyzeFunctions();
100385#endif
100386}
100387
100388/************** End of func.c ************************************************/
100389/************** Begin file fkey.c ********************************************/
100390/*
100391**
100392** The author disclaims copyright to this source code.  In place of
100393** a legal notice, here is a blessing:
100394**
100395**    May you do good and not evil.
100396**    May you find forgiveness for yourself and forgive others.
100397**    May you share freely, never taking more than you give.
100398**
100399*************************************************************************
100400** This file contains code used by the compiler to add foreign key
100401** support to compiled SQL statements.
100402*/
100403/* #include "sqliteInt.h" */
100404
100405#ifndef SQLITE_OMIT_FOREIGN_KEY
100406#ifndef SQLITE_OMIT_TRIGGER
100407
100408/*
100409** Deferred and Immediate FKs
100410** --------------------------
100411**
100412** Foreign keys in SQLite come in two flavours: deferred and immediate.
100413** If an immediate foreign key constraint is violated,
100414** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
100415** statement transaction rolled back. If a
100416** deferred foreign key constraint is violated, no action is taken
100417** immediately. However if the application attempts to commit the
100418** transaction before fixing the constraint violation, the attempt fails.
100419**
100420** Deferred constraints are implemented using a simple counter associated
100421** with the database handle. The counter is set to zero each time a
100422** database transaction is opened. Each time a statement is executed
100423** that causes a foreign key violation, the counter is incremented. Each
100424** time a statement is executed that removes an existing violation from
100425** the database, the counter is decremented. When the transaction is
100426** committed, the commit fails if the current value of the counter is
100427** greater than zero. This scheme has two big drawbacks:
100428**
100429**   * When a commit fails due to a deferred foreign key constraint,
100430**     there is no way to tell which foreign constraint is not satisfied,
100431**     or which row it is not satisfied for.
100432**
100433**   * If the database contains foreign key violations when the
100434**     transaction is opened, this may cause the mechanism to malfunction.
100435**
100436** Despite these problems, this approach is adopted as it seems simpler
100437** than the alternatives.
100438**
100439** INSERT operations:
100440**
100441**   I.1) For each FK for which the table is the child table, search
100442**        the parent table for a match. If none is found increment the
100443**        constraint counter.
100444**
100445**   I.2) For each FK for which the table is the parent table,
100446**        search the child table for rows that correspond to the new
100447**        row in the parent table. Decrement the counter for each row
100448**        found (as the constraint is now satisfied).
100449**
100450** DELETE operations:
100451**
100452**   D.1) For each FK for which the table is the child table,
100453**        search the parent table for a row that corresponds to the
100454**        deleted row in the child table. If such a row is not found,
100455**        decrement the counter.
100456**
100457**   D.2) For each FK for which the table is the parent table, search
100458**        the child table for rows that correspond to the deleted row
100459**        in the parent table. For each found increment the counter.
100460**
100461** UPDATE operations:
100462**
100463**   An UPDATE command requires that all 4 steps above are taken, but only
100464**   for FK constraints for which the affected columns are actually
100465**   modified (values must be compared at runtime).
100466**
100467** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
100468** This simplifies the implementation a bit.
100469**
100470** For the purposes of immediate FK constraints, the OR REPLACE conflict
100471** resolution is considered to delete rows before the new row is inserted.
100472** If a delete caused by OR REPLACE violates an FK constraint, an exception
100473** is thrown, even if the FK constraint would be satisfied after the new
100474** row is inserted.
100475**
100476** Immediate constraints are usually handled similarly. The only difference
100477** is that the counter used is stored as part of each individual statement
100478** object (struct Vdbe). If, after the statement has run, its immediate
100479** constraint counter is greater than zero,
100480** it returns SQLITE_CONSTRAINT_FOREIGNKEY
100481** and the statement transaction is rolled back. An exception is an INSERT
100482** statement that inserts a single row only (no triggers). In this case,
100483** instead of using a counter, an exception is thrown immediately if the
100484** INSERT violates a foreign key constraint. This is necessary as such
100485** an INSERT does not open a statement transaction.
100486**
100487** TODO: How should dropping a table be handled? How should renaming a
100488** table be handled?
100489**
100490**
100491** Query API Notes
100492** ---------------
100493**
100494** Before coding an UPDATE or DELETE row operation, the code-generator
100495** for those two operations needs to know whether or not the operation
100496** requires any FK processing and, if so, which columns of the original
100497** row are required by the FK processing VDBE code (i.e. if FKs were
100498** implemented using triggers, which of the old.* columns would be
100499** accessed). No information is required by the code-generator before
100500** coding an INSERT operation. The functions used by the UPDATE/DELETE
100501** generation code to query for this information are:
100502**
100503**   sqlite3FkRequired() - Test to see if FK processing is required.
100504**   sqlite3FkOldmask()  - Query for the set of required old.* columns.
100505**
100506**
100507** Externally accessible module functions
100508** --------------------------------------
100509**
100510**   sqlite3FkCheck()    - Check for foreign key violations.
100511**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
100512**   sqlite3FkDelete()   - Delete an FKey structure.
100513*/
100514
100515/*
100516** VDBE Calling Convention
100517** -----------------------
100518**
100519** Example:
100520**
100521**   For the following INSERT statement:
100522**
100523**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
100524**     INSERT INTO t1 VALUES(1, 2, 3.1);
100525**
100526**   Register (x):        2    (type integer)
100527**   Register (x+1):      1    (type integer)
100528**   Register (x+2):      NULL (type NULL)
100529**   Register (x+3):      3.1  (type real)
100530*/
100531
100532/*
100533** A foreign key constraint requires that the key columns in the parent
100534** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
100535** Given that pParent is the parent table for foreign key constraint pFKey,
100536** search the schema for a unique index on the parent key columns.
100537**
100538** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
100539** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
100540** is set to point to the unique index.
100541**
100542** If the parent key consists of a single column (the foreign key constraint
100543** is not a composite foreign key), output variable *paiCol is set to NULL.
100544** Otherwise, it is set to point to an allocated array of size N, where
100545** N is the number of columns in the parent key. The first element of the
100546** array is the index of the child table column that is mapped by the FK
100547** constraint to the parent table column stored in the left-most column
100548** of index *ppIdx. The second element of the array is the index of the
100549** child table column that corresponds to the second left-most column of
100550** *ppIdx, and so on.
100551**
100552** If the required index cannot be found, either because:
100553**
100554**   1) The named parent key columns do not exist, or
100555**
100556**   2) The named parent key columns do exist, but are not subject to a
100557**      UNIQUE or PRIMARY KEY constraint, or
100558**
100559**   3) No parent key columns were provided explicitly as part of the
100560**      foreign key definition, and the parent table does not have a
100561**      PRIMARY KEY, or
100562**
100563**   4) No parent key columns were provided explicitly as part of the
100564**      foreign key definition, and the PRIMARY KEY of the parent table
100565**      consists of a different number of columns to the child key in
100566**      the child table.
100567**
100568** then non-zero is returned, and a "foreign key mismatch" error loaded
100569** into pParse. If an OOM error occurs, non-zero is returned and the
100570** pParse->db->mallocFailed flag is set.
100571*/
100572SQLITE_PRIVATE int sqlite3FkLocateIndex(
100573  Parse *pParse,                  /* Parse context to store any error in */
100574  Table *pParent,                 /* Parent table of FK constraint pFKey */
100575  FKey *pFKey,                    /* Foreign key to find index for */
100576  Index **ppIdx,                  /* OUT: Unique index on parent table */
100577  int **paiCol                    /* OUT: Map of index columns in pFKey */
100578){
100579  Index *pIdx = 0;                    /* Value to return via *ppIdx */
100580  int *aiCol = 0;                     /* Value to return via *paiCol */
100581  int nCol = pFKey->nCol;             /* Number of columns in parent key */
100582  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
100583
100584  /* The caller is responsible for zeroing output parameters. */
100585  assert( ppIdx && *ppIdx==0 );
100586  assert( !paiCol || *paiCol==0 );
100587  assert( pParse );
100588
100589  /* If this is a non-composite (single column) foreign key, check if it
100590  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
100591  ** and *paiCol set to zero and return early.
100592  **
100593  ** Otherwise, for a composite foreign key (more than one column), allocate
100594  ** space for the aiCol array (returned via output parameter *paiCol).
100595  ** Non-composite foreign keys do not require the aiCol array.
100596  */
100597  if( nCol==1 ){
100598    /* The FK maps to the IPK if any of the following are true:
100599    **
100600    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
100601    **      mapped to the primary key of table pParent, or
100602    **   2) The FK is explicitly mapped to a column declared as INTEGER
100603    **      PRIMARY KEY.
100604    */
100605    if( pParent->iPKey>=0 ){
100606      if( !zKey ) return 0;
100607      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
100608    }
100609  }else if( paiCol ){
100610    assert( nCol>1 );
100611    aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
100612    if( !aiCol ) return 1;
100613    *paiCol = aiCol;
100614  }
100615
100616  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
100617    if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
100618      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
100619      ** of columns. If each indexed column corresponds to a foreign key
100620      ** column of pFKey, then this index is a winner.  */
100621
100622      if( zKey==0 ){
100623        /* If zKey is NULL, then this foreign key is implicitly mapped to
100624        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
100625        ** identified by the test.  */
100626        if( IsPrimaryKeyIndex(pIdx) ){
100627          if( aiCol ){
100628            int i;
100629            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
100630          }
100631          break;
100632        }
100633      }else{
100634        /* If zKey is non-NULL, then this foreign key was declared to
100635        ** map to an explicit list of columns in table pParent. Check if this
100636        ** index matches those columns. Also, check that the index uses
100637        ** the default collation sequences for each column. */
100638        int i, j;
100639        for(i=0; i<nCol; i++){
100640          i16 iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
100641          char *zDfltColl;                  /* Def. collation for column */
100642          char *zIdxCol;                    /* Name of indexed column */
100643
100644          if( iCol<0 ) break; /* No foreign keys against expression indexes */
100645
100646          /* If the index uses a collation sequence that is different from
100647          ** the default collation sequence for the column, this index is
100648          ** unusable. Bail out early in this case.  */
100649          zDfltColl = pParent->aCol[iCol].zColl;
100650          if( !zDfltColl ){
100651            zDfltColl = "BINARY";
100652          }
100653          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
100654
100655          zIdxCol = pParent->aCol[iCol].zName;
100656          for(j=0; j<nCol; j++){
100657            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
100658              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
100659              break;
100660            }
100661          }
100662          if( j==nCol ) break;
100663        }
100664        if( i==nCol ) break;      /* pIdx is usable */
100665      }
100666    }
100667  }
100668
100669  if( !pIdx ){
100670    if( !pParse->disableTriggers ){
100671      sqlite3ErrorMsg(pParse,
100672           "foreign key mismatch - \"%w\" referencing \"%w\"",
100673           pFKey->pFrom->zName, pFKey->zTo);
100674    }
100675    sqlite3DbFree(pParse->db, aiCol);
100676    return 1;
100677  }
100678
100679  *ppIdx = pIdx;
100680  return 0;
100681}
100682
100683/*
100684** This function is called when a row is inserted into or deleted from the
100685** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
100686** on the child table of pFKey, this function is invoked twice for each row
100687** affected - once to "delete" the old row, and then again to "insert" the
100688** new row.
100689**
100690** Each time it is called, this function generates VDBE code to locate the
100691** row in the parent table that corresponds to the row being inserted into
100692** or deleted from the child table. If the parent row can be found, no
100693** special action is taken. Otherwise, if the parent row can *not* be
100694** found in the parent table:
100695**
100696**   Operation | FK type   | Action taken
100697**   --------------------------------------------------------------------------
100698**   INSERT      immediate   Increment the "immediate constraint counter".
100699**
100700**   DELETE      immediate   Decrement the "immediate constraint counter".
100701**
100702**   INSERT      deferred    Increment the "deferred constraint counter".
100703**
100704**   DELETE      deferred    Decrement the "deferred constraint counter".
100705**
100706** These operations are identified in the comment at the top of this file
100707** (fkey.c) as "I.1" and "D.1".
100708*/
100709static void fkLookupParent(
100710  Parse *pParse,        /* Parse context */
100711  int iDb,              /* Index of database housing pTab */
100712  Table *pTab,          /* Parent table of FK pFKey */
100713  Index *pIdx,          /* Unique index on parent key columns in pTab */
100714  FKey *pFKey,          /* Foreign key constraint */
100715  int *aiCol,           /* Map from parent key columns to child table columns */
100716  int regData,          /* Address of array containing child table row */
100717  int nIncr,            /* Increment constraint counter by this */
100718  int isIgnore          /* If true, pretend pTab contains all NULL values */
100719){
100720  int i;                                    /* Iterator variable */
100721  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
100722  int iCur = pParse->nTab - 1;              /* Cursor number to use */
100723  int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
100724
100725  /* If nIncr is less than zero, then check at runtime if there are any
100726  ** outstanding constraints to resolve. If there are not, there is no need
100727  ** to check if deleting this row resolves any outstanding violations.
100728  **
100729  ** Check if any of the key columns in the child table row are NULL. If
100730  ** any are, then the constraint is considered satisfied. No need to
100731  ** search for a matching row in the parent table.  */
100732  if( nIncr<0 ){
100733    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
100734    VdbeCoverage(v);
100735  }
100736  for(i=0; i<pFKey->nCol; i++){
100737    int iReg = aiCol[i] + regData + 1;
100738    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
100739  }
100740
100741  if( isIgnore==0 ){
100742    if( pIdx==0 ){
100743      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
100744      ** column of the parent table (table pTab).  */
100745      int iMustBeInt;               /* Address of MustBeInt instruction */
100746      int regTemp = sqlite3GetTempReg(pParse);
100747
100748      /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
100749      ** apply the affinity of the parent key). If this fails, then there
100750      ** is no matching parent key. Before using MustBeInt, make a copy of
100751      ** the value. Otherwise, the value inserted into the child key column
100752      ** will have INTEGER affinity applied to it, which may not be correct.  */
100753      sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
100754      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
100755      VdbeCoverage(v);
100756
100757      /* If the parent table is the same as the child table, and we are about
100758      ** to increment the constraint-counter (i.e. this is an INSERT operation),
100759      ** then check if the row being inserted matches itself. If so, do not
100760      ** increment the constraint-counter.  */
100761      if( pTab==pFKey->pFrom && nIncr==1 ){
100762        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
100763        sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
100764      }
100765
100766      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
100767      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
100768      sqlite3VdbeGoto(v, iOk);
100769      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
100770      sqlite3VdbeJumpHere(v, iMustBeInt);
100771      sqlite3ReleaseTempReg(pParse, regTemp);
100772    }else{
100773      int nCol = pFKey->nCol;
100774      int regTemp = sqlite3GetTempRange(pParse, nCol);
100775      int regRec = sqlite3GetTempReg(pParse);
100776
100777      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
100778      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
100779      for(i=0; i<nCol; i++){
100780        sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
100781      }
100782
100783      /* If the parent table is the same as the child table, and we are about
100784      ** to increment the constraint-counter (i.e. this is an INSERT operation),
100785      ** then check if the row being inserted matches itself. If so, do not
100786      ** increment the constraint-counter.
100787      **
100788      ** If any of the parent-key values are NULL, then the row cannot match
100789      ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
100790      ** of the parent-key values are NULL (at this point it is known that
100791      ** none of the child key values are).
100792      */
100793      if( pTab==pFKey->pFrom && nIncr==1 ){
100794        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
100795        for(i=0; i<nCol; i++){
100796          int iChild = aiCol[i]+1+regData;
100797          int iParent = pIdx->aiColumn[i]+1+regData;
100798          assert( pIdx->aiColumn[i]>=0 );
100799          assert( aiCol[i]!=pTab->iPKey );
100800          if( pIdx->aiColumn[i]==pTab->iPKey ){
100801            /* The parent key is a composite key that includes the IPK column */
100802            iParent = regData;
100803          }
100804          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
100805          sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
100806        }
100807        sqlite3VdbeGoto(v, iOk);
100808      }
100809
100810      sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
100811                        sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
100812      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
100813
100814      sqlite3ReleaseTempReg(pParse, regRec);
100815      sqlite3ReleaseTempRange(pParse, regTemp, nCol);
100816    }
100817  }
100818
100819  if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
100820   && !pParse->pToplevel
100821   && !pParse->isMultiWrite
100822  ){
100823    /* Special case: If this is an INSERT statement that will insert exactly
100824    ** one row into the table, raise a constraint immediately instead of
100825    ** incrementing a counter. This is necessary as the VM code is being
100826    ** generated for will not open a statement transaction.  */
100827    assert( nIncr==1 );
100828    sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
100829        OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
100830  }else{
100831    if( nIncr>0 && pFKey->isDeferred==0 ){
100832      sqlite3MayAbort(pParse);
100833    }
100834    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
100835  }
100836
100837  sqlite3VdbeResolveLabel(v, iOk);
100838  sqlite3VdbeAddOp1(v, OP_Close, iCur);
100839}
100840
100841
100842/*
100843** Return an Expr object that refers to a memory register corresponding
100844** to column iCol of table pTab.
100845**
100846** regBase is the first of an array of register that contains the data
100847** for pTab.  regBase itself holds the rowid.  regBase+1 holds the first
100848** column.  regBase+2 holds the second column, and so forth.
100849*/
100850static Expr *exprTableRegister(
100851  Parse *pParse,     /* Parsing and code generating context */
100852  Table *pTab,       /* The table whose content is at r[regBase]... */
100853  int regBase,       /* Contents of table pTab */
100854  i16 iCol           /* Which column of pTab is desired */
100855){
100856  Expr *pExpr;
100857  Column *pCol;
100858  const char *zColl;
100859  sqlite3 *db = pParse->db;
100860
100861  pExpr = sqlite3Expr(db, TK_REGISTER, 0);
100862  if( pExpr ){
100863    if( iCol>=0 && iCol!=pTab->iPKey ){
100864      pCol = &pTab->aCol[iCol];
100865      pExpr->iTable = regBase + iCol + 1;
100866      pExpr->affinity = pCol->affinity;
100867      zColl = pCol->zColl;
100868      if( zColl==0 ) zColl = db->pDfltColl->zName;
100869      pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
100870    }else{
100871      pExpr->iTable = regBase;
100872      pExpr->affinity = SQLITE_AFF_INTEGER;
100873    }
100874  }
100875  return pExpr;
100876}
100877
100878/*
100879** Return an Expr object that refers to column iCol of table pTab which
100880** has cursor iCur.
100881*/
100882static Expr *exprTableColumn(
100883  sqlite3 *db,      /* The database connection */
100884  Table *pTab,      /* The table whose column is desired */
100885  int iCursor,      /* The open cursor on the table */
100886  i16 iCol          /* The column that is wanted */
100887){
100888  Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
100889  if( pExpr ){
100890    pExpr->pTab = pTab;
100891    pExpr->iTable = iCursor;
100892    pExpr->iColumn = iCol;
100893  }
100894  return pExpr;
100895}
100896
100897/*
100898** This function is called to generate code executed when a row is deleted
100899** from the parent table of foreign key constraint pFKey and, if pFKey is
100900** deferred, when a row is inserted into the same table. When generating
100901** code for an SQL UPDATE operation, this function may be called twice -
100902** once to "delete" the old row and once to "insert" the new row.
100903**
100904** Parameter nIncr is passed -1 when inserting a row (as this may decrease
100905** the number of FK violations in the db) or +1 when deleting one (as this
100906** may increase the number of FK constraint problems).
100907**
100908** The code generated by this function scans through the rows in the child
100909** table that correspond to the parent table row being deleted or inserted.
100910** For each child row found, one of the following actions is taken:
100911**
100912**   Operation | FK type   | Action taken
100913**   --------------------------------------------------------------------------
100914**   DELETE      immediate   Increment the "immediate constraint counter".
100915**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
100916**                           throw a "FOREIGN KEY constraint failed" exception.
100917**
100918**   INSERT      immediate   Decrement the "immediate constraint counter".
100919**
100920**   DELETE      deferred    Increment the "deferred constraint counter".
100921**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
100922**                           throw a "FOREIGN KEY constraint failed" exception.
100923**
100924**   INSERT      deferred    Decrement the "deferred constraint counter".
100925**
100926** These operations are identified in the comment at the top of this file
100927** (fkey.c) as "I.2" and "D.2".
100928*/
100929static void fkScanChildren(
100930  Parse *pParse,                  /* Parse context */
100931  SrcList *pSrc,                  /* The child table to be scanned */
100932  Table *pTab,                    /* The parent table */
100933  Index *pIdx,                    /* Index on parent covering the foreign key */
100934  FKey *pFKey,                    /* The foreign key linking pSrc to pTab */
100935  int *aiCol,                     /* Map from pIdx cols to child table cols */
100936  int regData,                    /* Parent row data starts here */
100937  int nIncr                       /* Amount to increment deferred counter by */
100938){
100939  sqlite3 *db = pParse->db;       /* Database handle */
100940  int i;                          /* Iterator variable */
100941  Expr *pWhere = 0;               /* WHERE clause to scan with */
100942  NameContext sNameContext;       /* Context used to resolve WHERE clause */
100943  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
100944  int iFkIfZero = 0;              /* Address of OP_FkIfZero */
100945  Vdbe *v = sqlite3GetVdbe(pParse);
100946
100947  assert( pIdx==0 || pIdx->pTable==pTab );
100948  assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
100949  assert( pIdx!=0 || pFKey->nCol==1 );
100950  assert( pIdx!=0 || HasRowid(pTab) );
100951
100952  if( nIncr<0 ){
100953    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
100954    VdbeCoverage(v);
100955  }
100956
100957  /* Create an Expr object representing an SQL expression like:
100958  **
100959  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
100960  **
100961  ** The collation sequence used for the comparison should be that of
100962  ** the parent key columns. The affinity of the parent key column should
100963  ** be applied to each child key value before the comparison takes place.
100964  */
100965  for(i=0; i<pFKey->nCol; i++){
100966    Expr *pLeft;                  /* Value from parent table row */
100967    Expr *pRight;                 /* Column ref to child table */
100968    Expr *pEq;                    /* Expression (pLeft = pRight) */
100969    i16 iCol;                     /* Index of column in child table */
100970    const char *zCol;             /* Name of column in child table */
100971
100972    iCol = pIdx ? pIdx->aiColumn[i] : -1;
100973    pLeft = exprTableRegister(pParse, pTab, regData, iCol);
100974    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
100975    assert( iCol>=0 );
100976    zCol = pFKey->pFrom->aCol[iCol].zName;
100977    pRight = sqlite3Expr(db, TK_ID, zCol);
100978    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
100979    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
100980  }
100981
100982  /* If the child table is the same as the parent table, then add terms
100983  ** to the WHERE clause that prevent this entry from being scanned.
100984  ** The added WHERE clause terms are like this:
100985  **
100986  **     $current_rowid!=rowid
100987  **     NOT( $current_a==a AND $current_b==b AND ... )
100988  **
100989  ** The first form is used for rowid tables.  The second form is used
100990  ** for WITHOUT ROWID tables.  In the second form, the primary key is
100991  ** (a,b,...)
100992  */
100993  if( pTab==pFKey->pFrom && nIncr>0 ){
100994    Expr *pNe;                    /* Expression (pLeft != pRight) */
100995    Expr *pLeft;                  /* Value from parent table row */
100996    Expr *pRight;                 /* Column ref to child table */
100997    if( HasRowid(pTab) ){
100998      pLeft = exprTableRegister(pParse, pTab, regData, -1);
100999      pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
101000      pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
101001    }else{
101002      Expr *pEq, *pAll = 0;
101003      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
101004      assert( pIdx!=0 );
101005      for(i=0; i<pPk->nKeyCol; i++){
101006        i16 iCol = pIdx->aiColumn[i];
101007        assert( iCol>=0 );
101008        pLeft = exprTableRegister(pParse, pTab, regData, iCol);
101009        pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
101010        pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
101011        pAll = sqlite3ExprAnd(db, pAll, pEq);
101012      }
101013      pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
101014    }
101015    pWhere = sqlite3ExprAnd(db, pWhere, pNe);
101016  }
101017
101018  /* Resolve the references in the WHERE clause. */
101019  memset(&sNameContext, 0, sizeof(NameContext));
101020  sNameContext.pSrcList = pSrc;
101021  sNameContext.pParse = pParse;
101022  sqlite3ResolveExprNames(&sNameContext, pWhere);
101023
101024  /* Create VDBE to loop through the entries in pSrc that match the WHERE
101025  ** clause. For each row found, increment either the deferred or immediate
101026  ** foreign key constraint counter. */
101027  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
101028  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
101029  if( pWInfo ){
101030    sqlite3WhereEnd(pWInfo);
101031  }
101032
101033  /* Clean up the WHERE clause constructed above. */
101034  sqlite3ExprDelete(db, pWhere);
101035  if( iFkIfZero ){
101036    sqlite3VdbeJumpHere(v, iFkIfZero);
101037  }
101038}
101039
101040/*
101041** This function returns a linked list of FKey objects (connected by
101042** FKey.pNextTo) holding all children of table pTab.  For example,
101043** given the following schema:
101044**
101045**   CREATE TABLE t1(a PRIMARY KEY);
101046**   CREATE TABLE t2(b REFERENCES t1(a);
101047**
101048** Calling this function with table "t1" as an argument returns a pointer
101049** to the FKey structure representing the foreign key constraint on table
101050** "t2". Calling this function with "t2" as the argument would return a
101051** NULL pointer (as there are no FK constraints for which t2 is the parent
101052** table).
101053*/
101054SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
101055  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
101056}
101057
101058/*
101059** The second argument is a Trigger structure allocated by the
101060** fkActionTrigger() routine. This function deletes the Trigger structure
101061** and all of its sub-components.
101062**
101063** The Trigger structure or any of its sub-components may be allocated from
101064** the lookaside buffer belonging to database handle dbMem.
101065*/
101066static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
101067  if( p ){
101068    TriggerStep *pStep = p->step_list;
101069    sqlite3ExprDelete(dbMem, pStep->pWhere);
101070    sqlite3ExprListDelete(dbMem, pStep->pExprList);
101071    sqlite3SelectDelete(dbMem, pStep->pSelect);
101072    sqlite3ExprDelete(dbMem, p->pWhen);
101073    sqlite3DbFree(dbMem, p);
101074  }
101075}
101076
101077/*
101078** This function is called to generate code that runs when table pTab is
101079** being dropped from the database. The SrcList passed as the second argument
101080** to this function contains a single entry guaranteed to resolve to
101081** table pTab.
101082**
101083** Normally, no code is required. However, if either
101084**
101085**   (a) The table is the parent table of a FK constraint, or
101086**   (b) The table is the child table of a deferred FK constraint and it is
101087**       determined at runtime that there are outstanding deferred FK
101088**       constraint violations in the database,
101089**
101090** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
101091** the table from the database. Triggers are disabled while running this
101092** DELETE, but foreign key actions are not.
101093*/
101094SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
101095  sqlite3 *db = pParse->db;
101096  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
101097    int iSkip = 0;
101098    Vdbe *v = sqlite3GetVdbe(pParse);
101099
101100    assert( v );                  /* VDBE has already been allocated */
101101    if( sqlite3FkReferences(pTab)==0 ){
101102      /* Search for a deferred foreign key constraint for which this table
101103      ** is the child table. If one cannot be found, return without
101104      ** generating any VDBE code. If one can be found, then jump over
101105      ** the entire DELETE if there are no outstanding deferred constraints
101106      ** when this statement is run.  */
101107      FKey *p;
101108      for(p=pTab->pFKey; p; p=p->pNextFrom){
101109        if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
101110      }
101111      if( !p ) return;
101112      iSkip = sqlite3VdbeMakeLabel(v);
101113      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
101114    }
101115
101116    pParse->disableTriggers = 1;
101117    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
101118    pParse->disableTriggers = 0;
101119
101120    /* If the DELETE has generated immediate foreign key constraint
101121    ** violations, halt the VDBE and return an error at this point, before
101122    ** any modifications to the schema are made. This is because statement
101123    ** transactions are not able to rollback schema changes.
101124    **
101125    ** If the SQLITE_DeferFKs flag is set, then this is not required, as
101126    ** the statement transaction will not be rolled back even if FK
101127    ** constraints are violated.
101128    */
101129    if( (db->flags & SQLITE_DeferFKs)==0 ){
101130      sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
101131      VdbeCoverage(v);
101132      sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
101133          OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
101134    }
101135
101136    if( iSkip ){
101137      sqlite3VdbeResolveLabel(v, iSkip);
101138    }
101139  }
101140}
101141
101142
101143/*
101144** The second argument points to an FKey object representing a foreign key
101145** for which pTab is the child table. An UPDATE statement against pTab
101146** is currently being processed. For each column of the table that is
101147** actually updated, the corresponding element in the aChange[] array
101148** is zero or greater (if a column is unmodified the corresponding element
101149** is set to -1). If the rowid column is modified by the UPDATE statement
101150** the bChngRowid argument is non-zero.
101151**
101152** This function returns true if any of the columns that are part of the
101153** child key for FK constraint *p are modified.
101154*/
101155static int fkChildIsModified(
101156  Table *pTab,                    /* Table being updated */
101157  FKey *p,                        /* Foreign key for which pTab is the child */
101158  int *aChange,                   /* Array indicating modified columns */
101159  int bChngRowid                  /* True if rowid is modified by this update */
101160){
101161  int i;
101162  for(i=0; i<p->nCol; i++){
101163    int iChildKey = p->aCol[i].iFrom;
101164    if( aChange[iChildKey]>=0 ) return 1;
101165    if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
101166  }
101167  return 0;
101168}
101169
101170/*
101171** The second argument points to an FKey object representing a foreign key
101172** for which pTab is the parent table. An UPDATE statement against pTab
101173** is currently being processed. For each column of the table that is
101174** actually updated, the corresponding element in the aChange[] array
101175** is zero or greater (if a column is unmodified the corresponding element
101176** is set to -1). If the rowid column is modified by the UPDATE statement
101177** the bChngRowid argument is non-zero.
101178**
101179** This function returns true if any of the columns that are part of the
101180** parent key for FK constraint *p are modified.
101181*/
101182static int fkParentIsModified(
101183  Table *pTab,
101184  FKey *p,
101185  int *aChange,
101186  int bChngRowid
101187){
101188  int i;
101189  for(i=0; i<p->nCol; i++){
101190    char *zKey = p->aCol[i].zCol;
101191    int iKey;
101192    for(iKey=0; iKey<pTab->nCol; iKey++){
101193      if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
101194        Column *pCol = &pTab->aCol[iKey];
101195        if( zKey ){
101196          if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
101197        }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
101198          return 1;
101199        }
101200      }
101201    }
101202  }
101203  return 0;
101204}
101205
101206/*
101207** Return true if the parser passed as the first argument is being
101208** used to code a trigger that is really a "SET NULL" action belonging
101209** to trigger pFKey.
101210*/
101211static int isSetNullAction(Parse *pParse, FKey *pFKey){
101212  Parse *pTop = sqlite3ParseToplevel(pParse);
101213  if( pTop->pTriggerPrg ){
101214    Trigger *p = pTop->pTriggerPrg->pTrigger;
101215    if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
101216     || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
101217    ){
101218      return 1;
101219    }
101220  }
101221  return 0;
101222}
101223
101224/*
101225** This function is called when inserting, deleting or updating a row of
101226** table pTab to generate VDBE code to perform foreign key constraint
101227** processing for the operation.
101228**
101229** For a DELETE operation, parameter regOld is passed the index of the
101230** first register in an array of (pTab->nCol+1) registers containing the
101231** rowid of the row being deleted, followed by each of the column values
101232** of the row being deleted, from left to right. Parameter regNew is passed
101233** zero in this case.
101234**
101235** For an INSERT operation, regOld is passed zero and regNew is passed the
101236** first register of an array of (pTab->nCol+1) registers containing the new
101237** row data.
101238**
101239** For an UPDATE operation, this function is called twice. Once before
101240** the original record is deleted from the table using the calling convention
101241** described for DELETE. Then again after the original record is deleted
101242** but before the new record is inserted using the INSERT convention.
101243*/
101244SQLITE_PRIVATE void sqlite3FkCheck(
101245  Parse *pParse,                  /* Parse context */
101246  Table *pTab,                    /* Row is being deleted from this table */
101247  int regOld,                     /* Previous row data is stored here */
101248  int regNew,                     /* New row data is stored here */
101249  int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
101250  int bChngRowid                  /* True if rowid is UPDATEd */
101251){
101252  sqlite3 *db = pParse->db;       /* Database handle */
101253  FKey *pFKey;                    /* Used to iterate through FKs */
101254  int iDb;                        /* Index of database containing pTab */
101255  const char *zDb;                /* Name of database containing pTab */
101256  int isIgnoreErrors = pParse->disableTriggers;
101257
101258  /* Exactly one of regOld and regNew should be non-zero. */
101259  assert( (regOld==0)!=(regNew==0) );
101260
101261  /* If foreign-keys are disabled, this function is a no-op. */
101262  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
101263
101264  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
101265  zDb = db->aDb[iDb].zName;
101266
101267  /* Loop through all the foreign key constraints for which pTab is the
101268  ** child table (the table that the foreign key definition is part of).  */
101269  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
101270    Table *pTo;                   /* Parent table of foreign key pFKey */
101271    Index *pIdx = 0;              /* Index on key columns in pTo */
101272    int *aiFree = 0;
101273    int *aiCol;
101274    int iCol;
101275    int i;
101276    int bIgnore = 0;
101277
101278    if( aChange
101279     && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
101280     && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
101281    ){
101282      continue;
101283    }
101284
101285    /* Find the parent table of this foreign key. Also find a unique index
101286    ** on the parent key columns in the parent table. If either of these
101287    ** schema items cannot be located, set an error in pParse and return
101288    ** early.  */
101289    if( pParse->disableTriggers ){
101290      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
101291    }else{
101292      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
101293    }
101294    if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
101295      assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
101296      if( !isIgnoreErrors || db->mallocFailed ) return;
101297      if( pTo==0 ){
101298        /* If isIgnoreErrors is true, then a table is being dropped. In this
101299        ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
101300        ** before actually dropping it in order to check FK constraints.
101301        ** If the parent table of an FK constraint on the current table is
101302        ** missing, behave as if it is empty. i.e. decrement the relevant
101303        ** FK counter for each row of the current table with non-NULL keys.
101304        */
101305        Vdbe *v = sqlite3GetVdbe(pParse);
101306        int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
101307        for(i=0; i<pFKey->nCol; i++){
101308          int iReg = pFKey->aCol[i].iFrom + regOld + 1;
101309          sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
101310        }
101311        sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
101312      }
101313      continue;
101314    }
101315    assert( pFKey->nCol==1 || (aiFree && pIdx) );
101316
101317    if( aiFree ){
101318      aiCol = aiFree;
101319    }else{
101320      iCol = pFKey->aCol[0].iFrom;
101321      aiCol = &iCol;
101322    }
101323    for(i=0; i<pFKey->nCol; i++){
101324      if( aiCol[i]==pTab->iPKey ){
101325        aiCol[i] = -1;
101326      }
101327      assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
101328#ifndef SQLITE_OMIT_AUTHORIZATION
101329      /* Request permission to read the parent key columns. If the
101330      ** authorization callback returns SQLITE_IGNORE, behave as if any
101331      ** values read from the parent table are NULL. */
101332      if( db->xAuth ){
101333        int rcauth;
101334        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
101335        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
101336        bIgnore = (rcauth==SQLITE_IGNORE);
101337      }
101338#endif
101339    }
101340
101341    /* Take a shared-cache advisory read-lock on the parent table. Allocate
101342    ** a cursor to use to search the unique index on the parent key columns
101343    ** in the parent table.  */
101344    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
101345    pParse->nTab++;
101346
101347    if( regOld!=0 ){
101348      /* A row is being removed from the child table. Search for the parent.
101349      ** If the parent does not exist, removing the child row resolves an
101350      ** outstanding foreign key constraint violation. */
101351      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
101352    }
101353    if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
101354      /* A row is being added to the child table. If a parent row cannot
101355      ** be found, adding the child row has violated the FK constraint.
101356      **
101357      ** If this operation is being performed as part of a trigger program
101358      ** that is actually a "SET NULL" action belonging to this very
101359      ** foreign key, then omit this scan altogether. As all child key
101360      ** values are guaranteed to be NULL, it is not possible for adding
101361      ** this row to cause an FK violation.  */
101362      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
101363    }
101364
101365    sqlite3DbFree(db, aiFree);
101366  }
101367
101368  /* Loop through all the foreign key constraints that refer to this table.
101369  ** (the "child" constraints) */
101370  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
101371    Index *pIdx = 0;              /* Foreign key index for pFKey */
101372    SrcList *pSrc;
101373    int *aiCol = 0;
101374
101375    if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
101376      continue;
101377    }
101378
101379    if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
101380     && !pParse->pToplevel && !pParse->isMultiWrite
101381    ){
101382      assert( regOld==0 && regNew!=0 );
101383      /* Inserting a single row into a parent table cannot cause (or fix)
101384      ** an immediate foreign key violation. So do nothing in this case.  */
101385      continue;
101386    }
101387
101388    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
101389      if( !isIgnoreErrors || db->mallocFailed ) return;
101390      continue;
101391    }
101392    assert( aiCol || pFKey->nCol==1 );
101393
101394    /* Create a SrcList structure containing the child table.  We need the
101395    ** child table as a SrcList for sqlite3WhereBegin() */
101396    pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
101397    if( pSrc ){
101398      struct SrcList_item *pItem = pSrc->a;
101399      pItem->pTab = pFKey->pFrom;
101400      pItem->zName = pFKey->pFrom->zName;
101401      pItem->pTab->nRef++;
101402      pItem->iCursor = pParse->nTab++;
101403
101404      if( regNew!=0 ){
101405        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
101406      }
101407      if( regOld!=0 ){
101408        int eAction = pFKey->aAction[aChange!=0];
101409        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
101410        /* If this is a deferred FK constraint, or a CASCADE or SET NULL
101411        ** action applies, then any foreign key violations caused by
101412        ** removing the parent key will be rectified by the action trigger.
101413        ** So do not set the "may-abort" flag in this case.
101414        **
101415        ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
101416        ** may-abort flag will eventually be set on this statement anyway
101417        ** (when this function is called as part of processing the UPDATE
101418        ** within the action trigger).
101419        **
101420        ** Note 2: At first glance it may seem like SQLite could simply omit
101421        ** all OP_FkCounter related scans when either CASCADE or SET NULL
101422        ** applies. The trouble starts if the CASCADE or SET NULL action
101423        ** trigger causes other triggers or action rules attached to the
101424        ** child table to fire. In these cases the fk constraint counters
101425        ** might be set incorrectly if any OP_FkCounter related scans are
101426        ** omitted.  */
101427        if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
101428          sqlite3MayAbort(pParse);
101429        }
101430      }
101431      pItem->zName = 0;
101432      sqlite3SrcListDelete(db, pSrc);
101433    }
101434    sqlite3DbFree(db, aiCol);
101435  }
101436}
101437
101438#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
101439
101440/*
101441** This function is called before generating code to update or delete a
101442** row contained in table pTab.
101443*/
101444SQLITE_PRIVATE u32 sqlite3FkOldmask(
101445  Parse *pParse,                  /* Parse context */
101446  Table *pTab                     /* Table being modified */
101447){
101448  u32 mask = 0;
101449  if( pParse->db->flags&SQLITE_ForeignKeys ){
101450    FKey *p;
101451    int i;
101452    for(p=pTab->pFKey; p; p=p->pNextFrom){
101453      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
101454    }
101455    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
101456      Index *pIdx = 0;
101457      sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
101458      if( pIdx ){
101459        for(i=0; i<pIdx->nKeyCol; i++){
101460          assert( pIdx->aiColumn[i]>=0 );
101461          mask |= COLUMN_MASK(pIdx->aiColumn[i]);
101462        }
101463      }
101464    }
101465  }
101466  return mask;
101467}
101468
101469
101470/*
101471** This function is called before generating code to update or delete a
101472** row contained in table pTab. If the operation is a DELETE, then
101473** parameter aChange is passed a NULL value. For an UPDATE, aChange points
101474** to an array of size N, where N is the number of columns in table pTab.
101475** If the i'th column is not modified by the UPDATE, then the corresponding
101476** entry in the aChange[] array is set to -1. If the column is modified,
101477** the value is 0 or greater. Parameter chngRowid is set to true if the
101478** UPDATE statement modifies the rowid fields of the table.
101479**
101480** If any foreign key processing will be required, this function returns
101481** true. If there is no foreign key related processing, this function
101482** returns false.
101483*/
101484SQLITE_PRIVATE int sqlite3FkRequired(
101485  Parse *pParse,                  /* Parse context */
101486  Table *pTab,                    /* Table being modified */
101487  int *aChange,                   /* Non-NULL for UPDATE operations */
101488  int chngRowid                   /* True for UPDATE that affects rowid */
101489){
101490  if( pParse->db->flags&SQLITE_ForeignKeys ){
101491    if( !aChange ){
101492      /* A DELETE operation. Foreign key processing is required if the
101493      ** table in question is either the child or parent table for any
101494      ** foreign key constraint.  */
101495      return (sqlite3FkReferences(pTab) || pTab->pFKey);
101496    }else{
101497      /* This is an UPDATE. Foreign key processing is only required if the
101498      ** operation modifies one or more child or parent key columns. */
101499      FKey *p;
101500
101501      /* Check if any child key columns are being modified. */
101502      for(p=pTab->pFKey; p; p=p->pNextFrom){
101503        if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
101504      }
101505
101506      /* Check if any parent key columns are being modified. */
101507      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
101508        if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
101509      }
101510    }
101511  }
101512  return 0;
101513}
101514
101515/*
101516** This function is called when an UPDATE or DELETE operation is being
101517** compiled on table pTab, which is the parent table of foreign-key pFKey.
101518** If the current operation is an UPDATE, then the pChanges parameter is
101519** passed a pointer to the list of columns being modified. If it is a
101520** DELETE, pChanges is passed a NULL pointer.
101521**
101522** It returns a pointer to a Trigger structure containing a trigger
101523** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
101524** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
101525** returned (these actions require no special handling by the triggers
101526** sub-system, code for them is created by fkScanChildren()).
101527**
101528** For example, if pFKey is the foreign key and pTab is table "p" in
101529** the following schema:
101530**
101531**   CREATE TABLE p(pk PRIMARY KEY);
101532**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
101533**
101534** then the returned trigger structure is equivalent to:
101535**
101536**   CREATE TRIGGER ... DELETE ON p BEGIN
101537**     DELETE FROM c WHERE ck = old.pk;
101538**   END;
101539**
101540** The returned pointer is cached as part of the foreign key object. It
101541** is eventually freed along with the rest of the foreign key object by
101542** sqlite3FkDelete().
101543*/
101544static Trigger *fkActionTrigger(
101545  Parse *pParse,                  /* Parse context */
101546  Table *pTab,                    /* Table being updated or deleted from */
101547  FKey *pFKey,                    /* Foreign key to get action for */
101548  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
101549){
101550  sqlite3 *db = pParse->db;       /* Database handle */
101551  int action;                     /* One of OE_None, OE_Cascade etc. */
101552  Trigger *pTrigger;              /* Trigger definition to return */
101553  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
101554
101555  action = pFKey->aAction[iAction];
101556  pTrigger = pFKey->apTrigger[iAction];
101557
101558  if( action!=OE_None && !pTrigger ){
101559    u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
101560    char const *zFrom;            /* Name of child table */
101561    int nFrom;                    /* Length in bytes of zFrom */
101562    Index *pIdx = 0;              /* Parent key index for this FK */
101563    int *aiCol = 0;               /* child table cols -> parent key cols */
101564    TriggerStep *pStep = 0;        /* First (only) step of trigger program */
101565    Expr *pWhere = 0;             /* WHERE clause of trigger step */
101566    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
101567    Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
101568    int i;                        /* Iterator variable */
101569    Expr *pWhen = 0;              /* WHEN clause for the trigger */
101570
101571    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
101572    assert( aiCol || pFKey->nCol==1 );
101573
101574    for(i=0; i<pFKey->nCol; i++){
101575      Token tOld = { "old", 3 };  /* Literal "old" token */
101576      Token tNew = { "new", 3 };  /* Literal "new" token */
101577      Token tFromCol;             /* Name of column in child table */
101578      Token tToCol;               /* Name of column in parent table */
101579      int iFromCol;               /* Idx of column in child table */
101580      Expr *pEq;                  /* tFromCol = OLD.tToCol */
101581
101582      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
101583      assert( iFromCol>=0 );
101584      assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
101585      assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
101586      tToCol.z = pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName;
101587      tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
101588
101589      tToCol.n = sqlite3Strlen30(tToCol.z);
101590      tFromCol.n = sqlite3Strlen30(tFromCol.z);
101591
101592      /* Create the expression "OLD.zToCol = zFromCol". It is important
101593      ** that the "OLD.zToCol" term is on the LHS of the = operator, so
101594      ** that the affinity and collation sequence associated with the
101595      ** parent table are used for the comparison. */
101596      pEq = sqlite3PExpr(pParse, TK_EQ,
101597          sqlite3PExpr(pParse, TK_DOT,
101598            sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
101599            sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
101600          , 0),
101601          sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
101602      , 0);
101603      pWhere = sqlite3ExprAnd(db, pWhere, pEq);
101604
101605      /* For ON UPDATE, construct the next term of the WHEN clause.
101606      ** The final WHEN clause will be like this:
101607      **
101608      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
101609      */
101610      if( pChanges ){
101611        pEq = sqlite3PExpr(pParse, TK_IS,
101612            sqlite3PExpr(pParse, TK_DOT,
101613              sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
101614              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
101615              0),
101616            sqlite3PExpr(pParse, TK_DOT,
101617              sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
101618              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
101619              0),
101620            0);
101621        pWhen = sqlite3ExprAnd(db, pWhen, pEq);
101622      }
101623
101624      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
101625        Expr *pNew;
101626        if( action==OE_Cascade ){
101627          pNew = sqlite3PExpr(pParse, TK_DOT,
101628            sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
101629            sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
101630          , 0);
101631        }else if( action==OE_SetDflt ){
101632          Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
101633          if( pDflt ){
101634            pNew = sqlite3ExprDup(db, pDflt, 0);
101635          }else{
101636            pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
101637          }
101638        }else{
101639          pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
101640        }
101641        pList = sqlite3ExprListAppend(pParse, pList, pNew);
101642        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
101643      }
101644    }
101645    sqlite3DbFree(db, aiCol);
101646
101647    zFrom = pFKey->pFrom->zName;
101648    nFrom = sqlite3Strlen30(zFrom);
101649
101650    if( action==OE_Restrict ){
101651      Token tFrom;
101652      Expr *pRaise;
101653
101654      tFrom.z = zFrom;
101655      tFrom.n = nFrom;
101656      pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
101657      if( pRaise ){
101658        pRaise->affinity = OE_Abort;
101659      }
101660      pSelect = sqlite3SelectNew(pParse,
101661          sqlite3ExprListAppend(pParse, 0, pRaise),
101662          sqlite3SrcListAppend(db, 0, &tFrom, 0),
101663          pWhere,
101664          0, 0, 0, 0, 0, 0
101665      );
101666      pWhere = 0;
101667    }
101668
101669    /* Disable lookaside memory allocation */
101670    enableLookaside = db->lookaside.bEnabled;
101671    db->lookaside.bEnabled = 0;
101672
101673    pTrigger = (Trigger *)sqlite3DbMallocZero(db,
101674        sizeof(Trigger) +         /* struct Trigger */
101675        sizeof(TriggerStep) +     /* Single step in trigger program */
101676        nFrom + 1                 /* Space for pStep->zTarget */
101677    );
101678    if( pTrigger ){
101679      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
101680      pStep->zTarget = (char *)&pStep[1];
101681      memcpy((char *)pStep->zTarget, zFrom, nFrom);
101682
101683      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
101684      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
101685      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
101686      if( pWhen ){
101687        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
101688        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
101689      }
101690    }
101691
101692    /* Re-enable the lookaside buffer, if it was disabled earlier. */
101693    db->lookaside.bEnabled = enableLookaside;
101694
101695    sqlite3ExprDelete(db, pWhere);
101696    sqlite3ExprDelete(db, pWhen);
101697    sqlite3ExprListDelete(db, pList);
101698    sqlite3SelectDelete(db, pSelect);
101699    if( db->mallocFailed==1 ){
101700      fkTriggerDelete(db, pTrigger);
101701      return 0;
101702    }
101703    assert( pStep!=0 );
101704
101705    switch( action ){
101706      case OE_Restrict:
101707        pStep->op = TK_SELECT;
101708        break;
101709      case OE_Cascade:
101710        if( !pChanges ){
101711          pStep->op = TK_DELETE;
101712          break;
101713        }
101714      default:
101715        pStep->op = TK_UPDATE;
101716    }
101717    pStep->pTrig = pTrigger;
101718    pTrigger->pSchema = pTab->pSchema;
101719    pTrigger->pTabSchema = pTab->pSchema;
101720    pFKey->apTrigger[iAction] = pTrigger;
101721    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
101722  }
101723
101724  return pTrigger;
101725}
101726
101727/*
101728** This function is called when deleting or updating a row to implement
101729** any required CASCADE, SET NULL or SET DEFAULT actions.
101730*/
101731SQLITE_PRIVATE void sqlite3FkActions(
101732  Parse *pParse,                  /* Parse context */
101733  Table *pTab,                    /* Table being updated or deleted from */
101734  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
101735  int regOld,                     /* Address of array containing old row */
101736  int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
101737  int bChngRowid                  /* True if rowid is UPDATEd */
101738){
101739  /* If foreign-key support is enabled, iterate through all FKs that
101740  ** refer to table pTab. If there is an action associated with the FK
101741  ** for this operation (either update or delete), invoke the associated
101742  ** trigger sub-program.  */
101743  if( pParse->db->flags&SQLITE_ForeignKeys ){
101744    FKey *pFKey;                  /* Iterator variable */
101745    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
101746      if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
101747        Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
101748        if( pAct ){
101749          sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
101750        }
101751      }
101752    }
101753  }
101754}
101755
101756#endif /* ifndef SQLITE_OMIT_TRIGGER */
101757
101758/*
101759** Free all memory associated with foreign key definitions attached to
101760** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
101761** hash table.
101762*/
101763SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
101764  FKey *pFKey;                    /* Iterator variable */
101765  FKey *pNext;                    /* Copy of pFKey->pNextFrom */
101766
101767  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
101768  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
101769
101770    /* Remove the FK from the fkeyHash hash table. */
101771    if( !db || db->pnBytesFreed==0 ){
101772      if( pFKey->pPrevTo ){
101773        pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
101774      }else{
101775        void *p = (void *)pFKey->pNextTo;
101776        const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
101777        sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
101778      }
101779      if( pFKey->pNextTo ){
101780        pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
101781      }
101782    }
101783
101784    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
101785    ** classified as either immediate or deferred.
101786    */
101787    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
101788
101789    /* Delete any triggers created to implement actions for this FK. */
101790#ifndef SQLITE_OMIT_TRIGGER
101791    fkTriggerDelete(db, pFKey->apTrigger[0]);
101792    fkTriggerDelete(db, pFKey->apTrigger[1]);
101793#endif
101794
101795    pNext = pFKey->pNextFrom;
101796    sqlite3DbFree(db, pFKey);
101797  }
101798}
101799#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
101800
101801/************** End of fkey.c ************************************************/
101802/************** Begin file insert.c ******************************************/
101803/*
101804** 2001 September 15
101805**
101806** The author disclaims copyright to this source code.  In place of
101807** a legal notice, here is a blessing:
101808**
101809**    May you do good and not evil.
101810**    May you find forgiveness for yourself and forgive others.
101811**    May you share freely, never taking more than you give.
101812**
101813*************************************************************************
101814** This file contains C code routines that are called by the parser
101815** to handle INSERT statements in SQLite.
101816*/
101817/* #include "sqliteInt.h" */
101818
101819/*
101820** Generate code that will
101821**
101822**   (1) acquire a lock for table pTab then
101823**   (2) open pTab as cursor iCur.
101824**
101825** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
101826** for that table that is actually opened.
101827*/
101828SQLITE_PRIVATE void sqlite3OpenTable(
101829  Parse *pParse,  /* Generate code into this VDBE */
101830  int iCur,       /* The cursor number of the table */
101831  int iDb,        /* The database index in sqlite3.aDb[] */
101832  Table *pTab,    /* The table to be opened */
101833  int opcode      /* OP_OpenRead or OP_OpenWrite */
101834){
101835  Vdbe *v;
101836  assert( !IsVirtual(pTab) );
101837  v = sqlite3GetVdbe(pParse);
101838  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
101839  sqlite3TableLock(pParse, iDb, pTab->tnum,
101840                   (opcode==OP_OpenWrite)?1:0, pTab->zName);
101841  if( HasRowid(pTab) ){
101842    sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
101843    VdbeComment((v, "%s", pTab->zName));
101844  }else{
101845    Index *pPk = sqlite3PrimaryKeyIndex(pTab);
101846    assert( pPk!=0 );
101847    assert( pPk->tnum==pTab->tnum );
101848    sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
101849    sqlite3VdbeSetP4KeyInfo(pParse, pPk);
101850    VdbeComment((v, "%s", pTab->zName));
101851  }
101852}
101853
101854/*
101855** Return a pointer to the column affinity string associated with index
101856** pIdx. A column affinity string has one character for each column in
101857** the table, according to the affinity of the column:
101858**
101859**  Character      Column affinity
101860**  ------------------------------
101861**  'A'            BLOB
101862**  'B'            TEXT
101863**  'C'            NUMERIC
101864**  'D'            INTEGER
101865**  'F'            REAL
101866**
101867** An extra 'D' is appended to the end of the string to cover the
101868** rowid that appears as the last column in every index.
101869**
101870** Memory for the buffer containing the column index affinity string
101871** is managed along with the rest of the Index structure. It will be
101872** released when sqlite3DeleteIndex() is called.
101873*/
101874SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
101875  if( !pIdx->zColAff ){
101876    /* The first time a column affinity string for a particular index is
101877    ** required, it is allocated and populated here. It is then stored as
101878    ** a member of the Index structure for subsequent use.
101879    **
101880    ** The column affinity string will eventually be deleted by
101881    ** sqliteDeleteIndex() when the Index structure itself is cleaned
101882    ** up.
101883    */
101884    int n;
101885    Table *pTab = pIdx->pTable;
101886    pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
101887    if( !pIdx->zColAff ){
101888      db->mallocFailed = 1;
101889      return 0;
101890    }
101891    for(n=0; n<pIdx->nColumn; n++){
101892      i16 x = pIdx->aiColumn[n];
101893      if( x>=0 ){
101894        pIdx->zColAff[n] = pTab->aCol[x].affinity;
101895      }else if( x==XN_ROWID ){
101896        pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
101897      }else{
101898        char aff;
101899        assert( x==XN_EXPR );
101900        assert( pIdx->aColExpr!=0 );
101901        aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
101902        if( aff==0 ) aff = SQLITE_AFF_BLOB;
101903        pIdx->zColAff[n] = aff;
101904      }
101905    }
101906    pIdx->zColAff[n] = 0;
101907  }
101908
101909  return pIdx->zColAff;
101910}
101911
101912/*
101913** Compute the affinity string for table pTab, if it has not already been
101914** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
101915**
101916** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
101917** if iReg>0 then code an OP_Affinity opcode that will set the affinities
101918** for register iReg and following.  Or if affinities exists and iReg==0,
101919** then just set the P4 operand of the previous opcode (which should  be
101920** an OP_MakeRecord) to the affinity string.
101921**
101922** A column affinity string has one character per column:
101923**
101924**  Character      Column affinity
101925**  ------------------------------
101926**  'A'            BLOB
101927**  'B'            TEXT
101928**  'C'            NUMERIC
101929**  'D'            INTEGER
101930**  'E'            REAL
101931*/
101932SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
101933  int i;
101934  char *zColAff = pTab->zColAff;
101935  if( zColAff==0 ){
101936    sqlite3 *db = sqlite3VdbeDb(v);
101937    zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
101938    if( !zColAff ){
101939      db->mallocFailed = 1;
101940      return;
101941    }
101942
101943    for(i=0; i<pTab->nCol; i++){
101944      zColAff[i] = pTab->aCol[i].affinity;
101945    }
101946    do{
101947      zColAff[i--] = 0;
101948    }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
101949    pTab->zColAff = zColAff;
101950  }
101951  i = sqlite3Strlen30(zColAff);
101952  if( i ){
101953    if( iReg ){
101954      sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
101955    }else{
101956      sqlite3VdbeChangeP4(v, -1, zColAff, i);
101957    }
101958  }
101959}
101960
101961/*
101962** Return non-zero if the table pTab in database iDb or any of its indices
101963** have been opened at any point in the VDBE program. This is used to see if
101964** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
101965** run without using a temporary table for the results of the SELECT.
101966*/
101967static int readsTable(Parse *p, int iDb, Table *pTab){
101968  Vdbe *v = sqlite3GetVdbe(p);
101969  int i;
101970  int iEnd = sqlite3VdbeCurrentAddr(v);
101971#ifndef SQLITE_OMIT_VIRTUALTABLE
101972  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
101973#endif
101974
101975  for(i=1; i<iEnd; i++){
101976    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
101977    assert( pOp!=0 );
101978    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
101979      Index *pIndex;
101980      int tnum = pOp->p2;
101981      if( tnum==pTab->tnum ){
101982        return 1;
101983      }
101984      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
101985        if( tnum==pIndex->tnum ){
101986          return 1;
101987        }
101988      }
101989    }
101990#ifndef SQLITE_OMIT_VIRTUALTABLE
101991    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
101992      assert( pOp->p4.pVtab!=0 );
101993      assert( pOp->p4type==P4_VTAB );
101994      return 1;
101995    }
101996#endif
101997  }
101998  return 0;
101999}
102000
102001#ifndef SQLITE_OMIT_AUTOINCREMENT
102002/*
102003** Locate or create an AutoincInfo structure associated with table pTab
102004** which is in database iDb.  Return the register number for the register
102005** that holds the maximum rowid.
102006**
102007** There is at most one AutoincInfo structure per table even if the
102008** same table is autoincremented multiple times due to inserts within
102009** triggers.  A new AutoincInfo structure is created if this is the
102010** first use of table pTab.  On 2nd and subsequent uses, the original
102011** AutoincInfo structure is used.
102012**
102013** Three memory locations are allocated:
102014**
102015**   (1)  Register to hold the name of the pTab table.
102016**   (2)  Register to hold the maximum ROWID of pTab.
102017**   (3)  Register to hold the rowid in sqlite_sequence of pTab
102018**
102019** The 2nd register is the one that is returned.  That is all the
102020** insert routine needs to know about.
102021*/
102022static int autoIncBegin(
102023  Parse *pParse,      /* Parsing context */
102024  int iDb,            /* Index of the database holding pTab */
102025  Table *pTab         /* The table we are writing to */
102026){
102027  int memId = 0;      /* Register holding maximum rowid */
102028  if( pTab->tabFlags & TF_Autoincrement ){
102029    Parse *pToplevel = sqlite3ParseToplevel(pParse);
102030    AutoincInfo *pInfo;
102031
102032    pInfo = pToplevel->pAinc;
102033    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
102034    if( pInfo==0 ){
102035      pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
102036      if( pInfo==0 ) return 0;
102037      pInfo->pNext = pToplevel->pAinc;
102038      pToplevel->pAinc = pInfo;
102039      pInfo->pTab = pTab;
102040      pInfo->iDb = iDb;
102041      pToplevel->nMem++;                  /* Register to hold name of table */
102042      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
102043      pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
102044    }
102045    memId = pInfo->regCtr;
102046  }
102047  return memId;
102048}
102049
102050/*
102051** This routine generates code that will initialize all of the
102052** register used by the autoincrement tracker.
102053*/
102054SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
102055  AutoincInfo *p;            /* Information about an AUTOINCREMENT */
102056  sqlite3 *db = pParse->db;  /* The database connection */
102057  Db *pDb;                   /* Database only autoinc table */
102058  int memId;                 /* Register holding max rowid */
102059  int addr;                  /* A VDBE address */
102060  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
102061
102062  /* This routine is never called during trigger-generation.  It is
102063  ** only called from the top-level */
102064  assert( pParse->pTriggerTab==0 );
102065  assert( sqlite3IsToplevel(pParse) );
102066
102067  assert( v );   /* We failed long ago if this is not so */
102068  for(p = pParse->pAinc; p; p = p->pNext){
102069    pDb = &db->aDb[p->iDb];
102070    memId = p->regCtr;
102071    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
102072    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
102073    sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
102074    addr = sqlite3VdbeCurrentAddr(v);
102075    sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
102076    sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v);
102077    sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
102078    sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v);
102079    sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
102080    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
102081    sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
102082    sqlite3VdbeGoto(v, addr+9);
102083    sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v);
102084    sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
102085    sqlite3VdbeAddOp0(v, OP_Close);
102086  }
102087}
102088
102089/*
102090** Update the maximum rowid for an autoincrement calculation.
102091**
102092** This routine should be called when the top of the stack holds a
102093** new rowid that is about to be inserted.  If that new rowid is
102094** larger than the maximum rowid in the memId memory cell, then the
102095** memory cell is updated.  The stack is unchanged.
102096*/
102097static void autoIncStep(Parse *pParse, int memId, int regRowid){
102098  if( memId>0 ){
102099    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
102100  }
102101}
102102
102103/*
102104** This routine generates the code needed to write autoincrement
102105** maximum rowid values back into the sqlite_sequence register.
102106** Every statement that might do an INSERT into an autoincrement
102107** table (either directly or through triggers) needs to call this
102108** routine just before the "exit" code.
102109*/
102110SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
102111  AutoincInfo *p;
102112  Vdbe *v = pParse->pVdbe;
102113  sqlite3 *db = pParse->db;
102114
102115  assert( v );
102116  for(p = pParse->pAinc; p; p = p->pNext){
102117    Db *pDb = &db->aDb[p->iDb];
102118    int addr1;
102119    int iRec;
102120    int memId = p->regCtr;
102121
102122    iRec = sqlite3GetTempReg(pParse);
102123    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
102124    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
102125    addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v);
102126    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
102127    sqlite3VdbeJumpHere(v, addr1);
102128    sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
102129    sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
102130    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
102131    sqlite3VdbeAddOp0(v, OP_Close);
102132    sqlite3ReleaseTempReg(pParse, iRec);
102133  }
102134}
102135#else
102136/*
102137** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
102138** above are all no-ops
102139*/
102140# define autoIncBegin(A,B,C) (0)
102141# define autoIncStep(A,B,C)
102142#endif /* SQLITE_OMIT_AUTOINCREMENT */
102143
102144
102145/* Forward declaration */
102146static int xferOptimization(
102147  Parse *pParse,        /* Parser context */
102148  Table *pDest,         /* The table we are inserting into */
102149  Select *pSelect,      /* A SELECT statement to use as the data source */
102150  int onError,          /* How to handle constraint errors */
102151  int iDbDest           /* The database of pDest */
102152);
102153
102154/*
102155** This routine is called to handle SQL of the following forms:
102156**
102157**    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
102158**    insert into TABLE (IDLIST) select
102159**    insert into TABLE (IDLIST) default values
102160**
102161** The IDLIST following the table name is always optional.  If omitted,
102162** then a list of all (non-hidden) columns for the table is substituted.
102163** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
102164** is omitted.
102165**
102166** For the pSelect parameter holds the values to be inserted for the
102167** first two forms shown above.  A VALUES clause is really just short-hand
102168** for a SELECT statement that omits the FROM clause and everything else
102169** that follows.  If the pSelect parameter is NULL, that means that the
102170** DEFAULT VALUES form of the INSERT statement is intended.
102171**
102172** The code generated follows one of four templates.  For a simple
102173** insert with data coming from a single-row VALUES clause, the code executes
102174** once straight down through.  Pseudo-code follows (we call this
102175** the "1st template"):
102176**
102177**         open write cursor to <table> and its indices
102178**         put VALUES clause expressions into registers
102179**         write the resulting record into <table>
102180**         cleanup
102181**
102182** The three remaining templates assume the statement is of the form
102183**
102184**   INSERT INTO <table> SELECT ...
102185**
102186** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
102187** in other words if the SELECT pulls all columns from a single table
102188** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
102189** if <table2> and <table1> are distinct tables but have identical
102190** schemas, including all the same indices, then a special optimization
102191** is invoked that copies raw records from <table2> over to <table1>.
102192** See the xferOptimization() function for the implementation of this
102193** template.  This is the 2nd template.
102194**
102195**         open a write cursor to <table>
102196**         open read cursor on <table2>
102197**         transfer all records in <table2> over to <table>
102198**         close cursors
102199**         foreach index on <table>
102200**           open a write cursor on the <table> index
102201**           open a read cursor on the corresponding <table2> index
102202**           transfer all records from the read to the write cursors
102203**           close cursors
102204**         end foreach
102205**
102206** The 3rd template is for when the second template does not apply
102207** and the SELECT clause does not read from <table> at any time.
102208** The generated code follows this template:
102209**
102210**         X <- A
102211**         goto B
102212**      A: setup for the SELECT
102213**         loop over the rows in the SELECT
102214**           load values into registers R..R+n
102215**           yield X
102216**         end loop
102217**         cleanup after the SELECT
102218**         end-coroutine X
102219**      B: open write cursor to <table> and its indices
102220**      C: yield X, at EOF goto D
102221**         insert the select result into <table> from R..R+n
102222**         goto C
102223**      D: cleanup
102224**
102225** The 4th template is used if the insert statement takes its
102226** values from a SELECT but the data is being inserted into a table
102227** that is also read as part of the SELECT.  In the third form,
102228** we have to use an intermediate table to store the results of
102229** the select.  The template is like this:
102230**
102231**         X <- A
102232**         goto B
102233**      A: setup for the SELECT
102234**         loop over the tables in the SELECT
102235**           load value into register R..R+n
102236**           yield X
102237**         end loop
102238**         cleanup after the SELECT
102239**         end co-routine R
102240**      B: open temp table
102241**      L: yield X, at EOF goto M
102242**         insert row from R..R+n into temp table
102243**         goto L
102244**      M: open write cursor to <table> and its indices
102245**         rewind temp table
102246**      C: loop over rows of intermediate table
102247**           transfer values form intermediate table into <table>
102248**         end loop
102249**      D: cleanup
102250*/
102251SQLITE_PRIVATE void sqlite3Insert(
102252  Parse *pParse,        /* Parser context */
102253  SrcList *pTabList,    /* Name of table into which we are inserting */
102254  Select *pSelect,      /* A SELECT statement to use as the data source */
102255  IdList *pColumn,      /* Column names corresponding to IDLIST. */
102256  int onError           /* How to handle constraint errors */
102257){
102258  sqlite3 *db;          /* The main database structure */
102259  Table *pTab;          /* The table to insert into.  aka TABLE */
102260  char *zTab;           /* Name of the table into which we are inserting */
102261  const char *zDb;      /* Name of the database holding this table */
102262  int i, j, idx;        /* Loop counters */
102263  Vdbe *v;              /* Generate code into this virtual machine */
102264  Index *pIdx;          /* For looping over indices of the table */
102265  int nColumn;          /* Number of columns in the data */
102266  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
102267  int iDataCur = 0;     /* VDBE cursor that is the main data repository */
102268  int iIdxCur = 0;      /* First index cursor */
102269  int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
102270  int endOfLoop;        /* Label for the end of the insertion loop */
102271  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
102272  int addrInsTop = 0;   /* Jump to label "D" */
102273  int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
102274  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
102275  int iDb;              /* Index of database holding TABLE */
102276  Db *pDb;              /* The database containing table being inserted into */
102277  u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
102278  u8 appendFlag = 0;    /* True if the insert is likely to be an append */
102279  u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
102280  u8 bIdListInOrder;    /* True if IDLIST is in table order */
102281  ExprList *pList = 0;  /* List of VALUES() to be inserted  */
102282
102283  /* Register allocations */
102284  int regFromSelect = 0;/* Base register for data coming from SELECT */
102285  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
102286  int regRowCount = 0;  /* Memory cell used for the row counter */
102287  int regIns;           /* Block of regs holding rowid+data being inserted */
102288  int regRowid;         /* registers holding insert rowid */
102289  int regData;          /* register holding first column to insert */
102290  int *aRegIdx = 0;     /* One register allocated to each index */
102291
102292#ifndef SQLITE_OMIT_TRIGGER
102293  int isView;                 /* True if attempting to insert into a view */
102294  Trigger *pTrigger;          /* List of triggers on pTab, if required */
102295  int tmask;                  /* Mask of trigger times */
102296#endif
102297
102298  db = pParse->db;
102299  memset(&dest, 0, sizeof(dest));
102300  if( pParse->nErr || db->mallocFailed ){
102301    goto insert_cleanup;
102302  }
102303
102304  /* If the Select object is really just a simple VALUES() list with a
102305  ** single row (the common case) then keep that one row of values
102306  ** and discard the other (unused) parts of the pSelect object
102307  */
102308  if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
102309    pList = pSelect->pEList;
102310    pSelect->pEList = 0;
102311    sqlite3SelectDelete(db, pSelect);
102312    pSelect = 0;
102313  }
102314
102315  /* Locate the table into which we will be inserting new information.
102316  */
102317  assert( pTabList->nSrc==1 );
102318  zTab = pTabList->a[0].zName;
102319  if( NEVER(zTab==0) ) goto insert_cleanup;
102320  pTab = sqlite3SrcListLookup(pParse, pTabList);
102321  if( pTab==0 ){
102322    goto insert_cleanup;
102323  }
102324  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
102325  assert( iDb<db->nDb );
102326  pDb = &db->aDb[iDb];
102327  zDb = pDb->zName;
102328  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
102329    goto insert_cleanup;
102330  }
102331  withoutRowid = !HasRowid(pTab);
102332
102333  /* Figure out if we have any triggers and if the table being
102334  ** inserted into is a view
102335  */
102336#ifndef SQLITE_OMIT_TRIGGER
102337  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
102338  isView = pTab->pSelect!=0;
102339#else
102340# define pTrigger 0
102341# define tmask 0
102342# define isView 0
102343#endif
102344#ifdef SQLITE_OMIT_VIEW
102345# undef isView
102346# define isView 0
102347#endif
102348  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
102349
102350  /* If pTab is really a view, make sure it has been initialized.
102351  ** ViewGetColumnNames() is a no-op if pTab is not a view.
102352  */
102353  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
102354    goto insert_cleanup;
102355  }
102356
102357  /* Cannot insert into a read-only table.
102358  */
102359  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
102360    goto insert_cleanup;
102361  }
102362
102363  /* Allocate a VDBE
102364  */
102365  v = sqlite3GetVdbe(pParse);
102366  if( v==0 ) goto insert_cleanup;
102367  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
102368  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
102369
102370#ifndef SQLITE_OMIT_XFER_OPT
102371  /* If the statement is of the form
102372  **
102373  **       INSERT INTO <table1> SELECT * FROM <table2>;
102374  **
102375  ** Then special optimizations can be applied that make the transfer
102376  ** very fast and which reduce fragmentation of indices.
102377  **
102378  ** This is the 2nd template.
102379  */
102380  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
102381    assert( !pTrigger );
102382    assert( pList==0 );
102383    goto insert_end;
102384  }
102385#endif /* SQLITE_OMIT_XFER_OPT */
102386
102387  /* If this is an AUTOINCREMENT table, look up the sequence number in the
102388  ** sqlite_sequence table and store it in memory cell regAutoinc.
102389  */
102390  regAutoinc = autoIncBegin(pParse, iDb, pTab);
102391
102392  /* Allocate registers for holding the rowid of the new row,
102393  ** the content of the new row, and the assembled row record.
102394  */
102395  regRowid = regIns = pParse->nMem+1;
102396  pParse->nMem += pTab->nCol + 1;
102397  if( IsVirtual(pTab) ){
102398    regRowid++;
102399    pParse->nMem++;
102400  }
102401  regData = regRowid+1;
102402
102403  /* If the INSERT statement included an IDLIST term, then make sure
102404  ** all elements of the IDLIST really are columns of the table and
102405  ** remember the column indices.
102406  **
102407  ** If the table has an INTEGER PRIMARY KEY column and that column
102408  ** is named in the IDLIST, then record in the ipkColumn variable
102409  ** the index into IDLIST of the primary key column.  ipkColumn is
102410  ** the index of the primary key as it appears in IDLIST, not as
102411  ** is appears in the original table.  (The index of the INTEGER
102412  ** PRIMARY KEY in the original table is pTab->iPKey.)
102413  */
102414  bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
102415  if( pColumn ){
102416    for(i=0; i<pColumn->nId; i++){
102417      pColumn->a[i].idx = -1;
102418    }
102419    for(i=0; i<pColumn->nId; i++){
102420      for(j=0; j<pTab->nCol; j++){
102421        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
102422          pColumn->a[i].idx = j;
102423          if( i!=j ) bIdListInOrder = 0;
102424          if( j==pTab->iPKey ){
102425            ipkColumn = i;  assert( !withoutRowid );
102426          }
102427          break;
102428        }
102429      }
102430      if( j>=pTab->nCol ){
102431        if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
102432          ipkColumn = i;
102433          bIdListInOrder = 0;
102434        }else{
102435          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
102436              pTabList, 0, pColumn->a[i].zName);
102437          pParse->checkSchema = 1;
102438          goto insert_cleanup;
102439        }
102440      }
102441    }
102442  }
102443
102444  /* Figure out how many columns of data are supplied.  If the data
102445  ** is coming from a SELECT statement, then generate a co-routine that
102446  ** produces a single row of the SELECT on each invocation.  The
102447  ** co-routine is the common header to the 3rd and 4th templates.
102448  */
102449  if( pSelect ){
102450    /* Data is coming from a SELECT or from a multi-row VALUES clause.
102451    ** Generate a co-routine to run the SELECT. */
102452    int regYield;       /* Register holding co-routine entry-point */
102453    int addrTop;        /* Top of the co-routine */
102454    int rc;             /* Result code */
102455
102456    regYield = ++pParse->nMem;
102457    addrTop = sqlite3VdbeCurrentAddr(v) + 1;
102458    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
102459    sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
102460    dest.iSdst = bIdListInOrder ? regData : 0;
102461    dest.nSdst = pTab->nCol;
102462    rc = sqlite3Select(pParse, pSelect, &dest);
102463    regFromSelect = dest.iSdst;
102464    if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
102465    sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
102466    sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
102467    assert( pSelect->pEList );
102468    nColumn = pSelect->pEList->nExpr;
102469
102470    /* Set useTempTable to TRUE if the result of the SELECT statement
102471    ** should be written into a temporary table (template 4).  Set to
102472    ** FALSE if each output row of the SELECT can be written directly into
102473    ** the destination table (template 3).
102474    **
102475    ** A temp table must be used if the table being updated is also one
102476    ** of the tables being read by the SELECT statement.  Also use a
102477    ** temp table in the case of row triggers.
102478    */
102479    if( pTrigger || readsTable(pParse, iDb, pTab) ){
102480      useTempTable = 1;
102481    }
102482
102483    if( useTempTable ){
102484      /* Invoke the coroutine to extract information from the SELECT
102485      ** and add it to a transient table srcTab.  The code generated
102486      ** here is from the 4th template:
102487      **
102488      **      B: open temp table
102489      **      L: yield X, goto M at EOF
102490      **         insert row from R..R+n into temp table
102491      **         goto L
102492      **      M: ...
102493      */
102494      int regRec;          /* Register to hold packed record */
102495      int regTempRowid;    /* Register to hold temp table ROWID */
102496      int addrL;           /* Label "L" */
102497
102498      srcTab = pParse->nTab++;
102499      regRec = sqlite3GetTempReg(pParse);
102500      regTempRowid = sqlite3GetTempReg(pParse);
102501      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
102502      addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
102503      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
102504      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
102505      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
102506      sqlite3VdbeGoto(v, addrL);
102507      sqlite3VdbeJumpHere(v, addrL);
102508      sqlite3ReleaseTempReg(pParse, regRec);
102509      sqlite3ReleaseTempReg(pParse, regTempRowid);
102510    }
102511  }else{
102512    /* This is the case if the data for the INSERT is coming from a
102513    ** single-row VALUES clause
102514    */
102515    NameContext sNC;
102516    memset(&sNC, 0, sizeof(sNC));
102517    sNC.pParse = pParse;
102518    srcTab = -1;
102519    assert( useTempTable==0 );
102520    if( pList ){
102521      nColumn = pList->nExpr;
102522      if( sqlite3ResolveExprListNames(&sNC, pList) ){
102523        goto insert_cleanup;
102524      }
102525    }else{
102526      nColumn = 0;
102527    }
102528  }
102529
102530  /* If there is no IDLIST term but the table has an integer primary
102531  ** key, the set the ipkColumn variable to the integer primary key
102532  ** column index in the original table definition.
102533  */
102534  if( pColumn==0 && nColumn>0 ){
102535    ipkColumn = pTab->iPKey;
102536  }
102537
102538  /* Make sure the number of columns in the source data matches the number
102539  ** of columns to be inserted into the table.
102540  */
102541  if( IsVirtual(pTab) ){
102542    for(i=0; i<pTab->nCol; i++){
102543      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
102544    }
102545  }
102546  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
102547    sqlite3ErrorMsg(pParse,
102548       "table %S has %d columns but %d values were supplied",
102549       pTabList, 0, pTab->nCol-nHidden, nColumn);
102550    goto insert_cleanup;
102551  }
102552  if( pColumn!=0 && nColumn!=pColumn->nId ){
102553    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
102554    goto insert_cleanup;
102555  }
102556
102557  /* Initialize the count of rows to be inserted
102558  */
102559  if( db->flags & SQLITE_CountRows ){
102560    regRowCount = ++pParse->nMem;
102561    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
102562  }
102563
102564  /* If this is not a view, open the table and and all indices */
102565  if( !isView ){
102566    int nIdx;
102567    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0,
102568                                      &iDataCur, &iIdxCur);
102569    aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
102570    if( aRegIdx==0 ){
102571      goto insert_cleanup;
102572    }
102573    for(i=0; i<nIdx; i++){
102574      aRegIdx[i] = ++pParse->nMem;
102575    }
102576  }
102577
102578  /* This is the top of the main insertion loop */
102579  if( useTempTable ){
102580    /* This block codes the top of loop only.  The complete loop is the
102581    ** following pseudocode (template 4):
102582    **
102583    **         rewind temp table, if empty goto D
102584    **      C: loop over rows of intermediate table
102585    **           transfer values form intermediate table into <table>
102586    **         end loop
102587    **      D: ...
102588    */
102589    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
102590    addrCont = sqlite3VdbeCurrentAddr(v);
102591  }else if( pSelect ){
102592    /* This block codes the top of loop only.  The complete loop is the
102593    ** following pseudocode (template 3):
102594    **
102595    **      C: yield X, at EOF goto D
102596    **         insert the select result into <table> from R..R+n
102597    **         goto C
102598    **      D: ...
102599    */
102600    addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
102601    VdbeCoverage(v);
102602  }
102603
102604  /* Run the BEFORE and INSTEAD OF triggers, if there are any
102605  */
102606  endOfLoop = sqlite3VdbeMakeLabel(v);
102607  if( tmask & TRIGGER_BEFORE ){
102608    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
102609
102610    /* build the NEW.* reference row.  Note that if there is an INTEGER
102611    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
102612    ** translated into a unique ID for the row.  But on a BEFORE trigger,
102613    ** we do not know what the unique ID will be (because the insert has
102614    ** not happened yet) so we substitute a rowid of -1
102615    */
102616    if( ipkColumn<0 ){
102617      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
102618    }else{
102619      int addr1;
102620      assert( !withoutRowid );
102621      if( useTempTable ){
102622        sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
102623      }else{
102624        assert( pSelect==0 );  /* Otherwise useTempTable is true */
102625        sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
102626      }
102627      addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
102628      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
102629      sqlite3VdbeJumpHere(v, addr1);
102630      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
102631    }
102632
102633    /* Cannot have triggers on a virtual table. If it were possible,
102634    ** this block would have to account for hidden column.
102635    */
102636    assert( !IsVirtual(pTab) );
102637
102638    /* Create the new column data
102639    */
102640    for(i=0; i<pTab->nCol; i++){
102641      if( pColumn==0 ){
102642        j = i;
102643      }else{
102644        for(j=0; j<pColumn->nId; j++){
102645          if( pColumn->a[j].idx==i ) break;
102646        }
102647      }
102648      if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
102649        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
102650      }else if( useTempTable ){
102651        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
102652      }else{
102653        assert( pSelect==0 ); /* Otherwise useTempTable is true */
102654        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
102655      }
102656    }
102657
102658    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
102659    ** do not attempt any conversions before assembling the record.
102660    ** If this is a real table, attempt conversions as required by the
102661    ** table column affinities.
102662    */
102663    if( !isView ){
102664      sqlite3TableAffinity(v, pTab, regCols+1);
102665    }
102666
102667    /* Fire BEFORE or INSTEAD OF triggers */
102668    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
102669        pTab, regCols-pTab->nCol-1, onError, endOfLoop);
102670
102671    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
102672  }
102673
102674  /* Compute the content of the next row to insert into a range of
102675  ** registers beginning at regIns.
102676  */
102677  if( !isView ){
102678    if( IsVirtual(pTab) ){
102679      /* The row that the VUpdate opcode will delete: none */
102680      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
102681    }
102682    if( ipkColumn>=0 ){
102683      if( useTempTable ){
102684        sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
102685      }else if( pSelect ){
102686        sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
102687      }else{
102688        VdbeOp *pOp;
102689        sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
102690        pOp = sqlite3VdbeGetOp(v, -1);
102691        if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
102692          appendFlag = 1;
102693          pOp->opcode = OP_NewRowid;
102694          pOp->p1 = iDataCur;
102695          pOp->p2 = regRowid;
102696          pOp->p3 = regAutoinc;
102697        }
102698      }
102699      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
102700      ** to generate a unique primary key value.
102701      */
102702      if( !appendFlag ){
102703        int addr1;
102704        if( !IsVirtual(pTab) ){
102705          addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
102706          sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
102707          sqlite3VdbeJumpHere(v, addr1);
102708        }else{
102709          addr1 = sqlite3VdbeCurrentAddr(v);
102710          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
102711        }
102712        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
102713      }
102714    }else if( IsVirtual(pTab) || withoutRowid ){
102715      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
102716    }else{
102717      sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
102718      appendFlag = 1;
102719    }
102720    autoIncStep(pParse, regAutoinc, regRowid);
102721
102722    /* Compute data for all columns of the new entry, beginning
102723    ** with the first column.
102724    */
102725    nHidden = 0;
102726    for(i=0; i<pTab->nCol; i++){
102727      int iRegStore = regRowid+1+i;
102728      if( i==pTab->iPKey ){
102729        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
102730        ** Whenever this column is read, the rowid will be substituted
102731        ** in its place.  Hence, fill this column with a NULL to avoid
102732        ** taking up data space with information that will never be used.
102733        ** As there may be shallow copies of this value, make it a soft-NULL */
102734        sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
102735        continue;
102736      }
102737      if( pColumn==0 ){
102738        if( IsHiddenColumn(&pTab->aCol[i]) ){
102739          assert( IsVirtual(pTab) );
102740          j = -1;
102741          nHidden++;
102742        }else{
102743          j = i - nHidden;
102744        }
102745      }else{
102746        for(j=0; j<pColumn->nId; j++){
102747          if( pColumn->a[j].idx==i ) break;
102748        }
102749      }
102750      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
102751        sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
102752      }else if( useTempTable ){
102753        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
102754      }else if( pSelect ){
102755        if( regFromSelect!=regData ){
102756          sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
102757        }
102758      }else{
102759        sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
102760      }
102761    }
102762
102763    /* Generate code to check constraints and generate index keys and
102764    ** do the insertion.
102765    */
102766#ifndef SQLITE_OMIT_VIRTUALTABLE
102767    if( IsVirtual(pTab) ){
102768      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
102769      sqlite3VtabMakeWritable(pParse, pTab);
102770      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
102771      sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
102772      sqlite3MayAbort(pParse);
102773    }else
102774#endif
102775    {
102776      int isReplace;    /* Set to true if constraints may cause a replace */
102777      sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
102778          regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
102779      );
102780      sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
102781      sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
102782                               regIns, aRegIdx, 0, appendFlag, isReplace==0);
102783    }
102784  }
102785
102786  /* Update the count of rows that are inserted
102787  */
102788  if( (db->flags & SQLITE_CountRows)!=0 ){
102789    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
102790  }
102791
102792  if( pTrigger ){
102793    /* Code AFTER triggers */
102794    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
102795        pTab, regData-2-pTab->nCol, onError, endOfLoop);
102796  }
102797
102798  /* The bottom of the main insertion loop, if the data source
102799  ** is a SELECT statement.
102800  */
102801  sqlite3VdbeResolveLabel(v, endOfLoop);
102802  if( useTempTable ){
102803    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
102804    sqlite3VdbeJumpHere(v, addrInsTop);
102805    sqlite3VdbeAddOp1(v, OP_Close, srcTab);
102806  }else if( pSelect ){
102807    sqlite3VdbeGoto(v, addrCont);
102808    sqlite3VdbeJumpHere(v, addrInsTop);
102809  }
102810
102811  if( !IsVirtual(pTab) && !isView ){
102812    /* Close all tables opened */
102813    if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
102814    for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
102815      sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
102816    }
102817  }
102818
102819insert_end:
102820  /* Update the sqlite_sequence table by storing the content of the
102821  ** maximum rowid counter values recorded while inserting into
102822  ** autoincrement tables.
102823  */
102824  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
102825    sqlite3AutoincrementEnd(pParse);
102826  }
102827
102828  /*
102829  ** Return the number of rows inserted. If this routine is
102830  ** generating code because of a call to sqlite3NestedParse(), do not
102831  ** invoke the callback function.
102832  */
102833  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
102834    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
102835    sqlite3VdbeSetNumCols(v, 1);
102836    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
102837  }
102838
102839insert_cleanup:
102840  sqlite3SrcListDelete(db, pTabList);
102841  sqlite3ExprListDelete(db, pList);
102842  sqlite3SelectDelete(db, pSelect);
102843  sqlite3IdListDelete(db, pColumn);
102844  sqlite3DbFree(db, aRegIdx);
102845}
102846
102847/* Make sure "isView" and other macros defined above are undefined. Otherwise
102848** they may interfere with compilation of other functions in this file
102849** (or in another file, if this file becomes part of the amalgamation).  */
102850#ifdef isView
102851 #undef isView
102852#endif
102853#ifdef pTrigger
102854 #undef pTrigger
102855#endif
102856#ifdef tmask
102857 #undef tmask
102858#endif
102859
102860/*
102861** Generate code to do constraint checks prior to an INSERT or an UPDATE
102862** on table pTab.
102863**
102864** The regNewData parameter is the first register in a range that contains
102865** the data to be inserted or the data after the update.  There will be
102866** pTab->nCol+1 registers in this range.  The first register (the one
102867** that regNewData points to) will contain the new rowid, or NULL in the
102868** case of a WITHOUT ROWID table.  The second register in the range will
102869** contain the content of the first table column.  The third register will
102870** contain the content of the second table column.  And so forth.
102871**
102872** The regOldData parameter is similar to regNewData except that it contains
102873** the data prior to an UPDATE rather than afterwards.  regOldData is zero
102874** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
102875** checking regOldData for zero.
102876**
102877** For an UPDATE, the pkChng boolean is true if the true primary key (the
102878** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
102879** might be modified by the UPDATE.  If pkChng is false, then the key of
102880** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
102881**
102882** For an INSERT, the pkChng boolean indicates whether or not the rowid
102883** was explicitly specified as part of the INSERT statement.  If pkChng
102884** is zero, it means that the either rowid is computed automatically or
102885** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
102886** pkChng will only be true if the INSERT statement provides an integer
102887** value for either the rowid column or its INTEGER PRIMARY KEY alias.
102888**
102889** The code generated by this routine will store new index entries into
102890** registers identified by aRegIdx[].  No index entry is created for
102891** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
102892** the same as the order of indices on the linked list of indices
102893** at pTab->pIndex.
102894**
102895** The caller must have already opened writeable cursors on the main
102896** table and all applicable indices (that is to say, all indices for which
102897** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
102898** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
102899** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
102900** for the first index in the pTab->pIndex list.  Cursors for other indices
102901** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
102902**
102903** This routine also generates code to check constraints.  NOT NULL,
102904** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
102905** then the appropriate action is performed.  There are five possible
102906** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
102907**
102908**  Constraint type  Action       What Happens
102909**  ---------------  ----------   ----------------------------------------
102910**  any              ROLLBACK     The current transaction is rolled back and
102911**                                sqlite3_step() returns immediately with a
102912**                                return code of SQLITE_CONSTRAINT.
102913**
102914**  any              ABORT        Back out changes from the current command
102915**                                only (do not do a complete rollback) then
102916**                                cause sqlite3_step() to return immediately
102917**                                with SQLITE_CONSTRAINT.
102918**
102919**  any              FAIL         Sqlite3_step() returns immediately with a
102920**                                return code of SQLITE_CONSTRAINT.  The
102921**                                transaction is not rolled back and any
102922**                                changes to prior rows are retained.
102923**
102924**  any              IGNORE       The attempt in insert or update the current
102925**                                row is skipped, without throwing an error.
102926**                                Processing continues with the next row.
102927**                                (There is an immediate jump to ignoreDest.)
102928**
102929**  NOT NULL         REPLACE      The NULL value is replace by the default
102930**                                value for that column.  If the default value
102931**                                is NULL, the action is the same as ABORT.
102932**
102933**  UNIQUE           REPLACE      The other row that conflicts with the row
102934**                                being inserted is removed.
102935**
102936**  CHECK            REPLACE      Illegal.  The results in an exception.
102937**
102938** Which action to take is determined by the overrideError parameter.
102939** Or if overrideError==OE_Default, then the pParse->onError parameter
102940** is used.  Or if pParse->onError==OE_Default then the onError value
102941** for the constraint is used.
102942*/
102943SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
102944  Parse *pParse,       /* The parser context */
102945  Table *pTab,         /* The table being inserted or updated */
102946  int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
102947  int iDataCur,        /* Canonical data cursor (main table or PK index) */
102948  int iIdxCur,         /* First index cursor */
102949  int regNewData,      /* First register in a range holding values to insert */
102950  int regOldData,      /* Previous content.  0 for INSERTs */
102951  u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
102952  u8 overrideError,    /* Override onError to this if not OE_Default */
102953  int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
102954  int *pbMayReplace    /* OUT: Set to true if constraint may cause a replace */
102955){
102956  Vdbe *v;             /* VDBE under constrution */
102957  Index *pIdx;         /* Pointer to one of the indices */
102958  Index *pPk = 0;      /* The PRIMARY KEY index */
102959  sqlite3 *db;         /* Database connection */
102960  int i;               /* loop counter */
102961  int ix;              /* Index loop counter */
102962  int nCol;            /* Number of columns */
102963  int onError;         /* Conflict resolution strategy */
102964  int addr1;           /* Address of jump instruction */
102965  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
102966  int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
102967  int ipkTop = 0;      /* Top of the rowid change constraint check */
102968  int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
102969  u8 isUpdate;         /* True if this is an UPDATE operation */
102970  u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
102971  int regRowid = -1;   /* Register holding ROWID value */
102972
102973  isUpdate = regOldData!=0;
102974  db = pParse->db;
102975  v = sqlite3GetVdbe(pParse);
102976  assert( v!=0 );
102977  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
102978  nCol = pTab->nCol;
102979
102980  /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
102981  ** normal rowid tables.  nPkField is the number of key fields in the
102982  ** pPk index or 1 for a rowid table.  In other words, nPkField is the
102983  ** number of fields in the true primary key of the table. */
102984  if( HasRowid(pTab) ){
102985    pPk = 0;
102986    nPkField = 1;
102987  }else{
102988    pPk = sqlite3PrimaryKeyIndex(pTab);
102989    nPkField = pPk->nKeyCol;
102990  }
102991
102992  /* Record that this module has started */
102993  VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
102994                     iDataCur, iIdxCur, regNewData, regOldData, pkChng));
102995
102996  /* Test all NOT NULL constraints.
102997  */
102998  for(i=0; i<nCol; i++){
102999    if( i==pTab->iPKey ){
103000      continue;
103001    }
103002    onError = pTab->aCol[i].notNull;
103003    if( onError==OE_None ) continue;
103004    if( overrideError!=OE_Default ){
103005      onError = overrideError;
103006    }else if( onError==OE_Default ){
103007      onError = OE_Abort;
103008    }
103009    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
103010      onError = OE_Abort;
103011    }
103012    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
103013        || onError==OE_Ignore || onError==OE_Replace );
103014    switch( onError ){
103015      case OE_Abort:
103016        sqlite3MayAbort(pParse);
103017        /* Fall through */
103018      case OE_Rollback:
103019      case OE_Fail: {
103020        char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
103021                                    pTab->aCol[i].zName);
103022        sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
103023                          regNewData+1+i, zMsg, P4_DYNAMIC);
103024        sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
103025        VdbeCoverage(v);
103026        break;
103027      }
103028      case OE_Ignore: {
103029        sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
103030        VdbeCoverage(v);
103031        break;
103032      }
103033      default: {
103034        assert( onError==OE_Replace );
103035        addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
103036           VdbeCoverage(v);
103037        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
103038        sqlite3VdbeJumpHere(v, addr1);
103039        break;
103040      }
103041    }
103042  }
103043
103044  /* Test all CHECK constraints
103045  */
103046#ifndef SQLITE_OMIT_CHECK
103047  if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
103048    ExprList *pCheck = pTab->pCheck;
103049    pParse->ckBase = regNewData+1;
103050    onError = overrideError!=OE_Default ? overrideError : OE_Abort;
103051    for(i=0; i<pCheck->nExpr; i++){
103052      int allOk = sqlite3VdbeMakeLabel(v);
103053      sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
103054      if( onError==OE_Ignore ){
103055        sqlite3VdbeGoto(v, ignoreDest);
103056      }else{
103057        char *zName = pCheck->a[i].zName;
103058        if( zName==0 ) zName = pTab->zName;
103059        if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
103060        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
103061                              onError, zName, P4_TRANSIENT,
103062                              P5_ConstraintCheck);
103063      }
103064      sqlite3VdbeResolveLabel(v, allOk);
103065    }
103066  }
103067#endif /* !defined(SQLITE_OMIT_CHECK) */
103068
103069  /* If rowid is changing, make sure the new rowid does not previously
103070  ** exist in the table.
103071  */
103072  if( pkChng && pPk==0 ){
103073    int addrRowidOk = sqlite3VdbeMakeLabel(v);
103074
103075    /* Figure out what action to take in case of a rowid collision */
103076    onError = pTab->keyConf;
103077    if( overrideError!=OE_Default ){
103078      onError = overrideError;
103079    }else if( onError==OE_Default ){
103080      onError = OE_Abort;
103081    }
103082
103083    if( isUpdate ){
103084      /* pkChng!=0 does not mean that the rowid has change, only that
103085      ** it might have changed.  Skip the conflict logic below if the rowid
103086      ** is unchanged. */
103087      sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
103088      sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
103089      VdbeCoverage(v);
103090    }
103091
103092    /* If the response to a rowid conflict is REPLACE but the response
103093    ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
103094    ** to defer the running of the rowid conflict checking until after
103095    ** the UNIQUE constraints have run.
103096    */
103097    if( onError==OE_Replace && overrideError!=OE_Replace ){
103098      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
103099        if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
103100          ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
103101          break;
103102        }
103103      }
103104    }
103105
103106    /* Check to see if the new rowid already exists in the table.  Skip
103107    ** the following conflict logic if it does not. */
103108    sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
103109    VdbeCoverage(v);
103110
103111    /* Generate code that deals with a rowid collision */
103112    switch( onError ){
103113      default: {
103114        onError = OE_Abort;
103115        /* Fall thru into the next case */
103116      }
103117      case OE_Rollback:
103118      case OE_Abort:
103119      case OE_Fail: {
103120        sqlite3RowidConstraint(pParse, onError, pTab);
103121        break;
103122      }
103123      case OE_Replace: {
103124        /* If there are DELETE triggers on this table and the
103125        ** recursive-triggers flag is set, call GenerateRowDelete() to
103126        ** remove the conflicting row from the table. This will fire
103127        ** the triggers and remove both the table and index b-tree entries.
103128        **
103129        ** Otherwise, if there are no triggers or the recursive-triggers
103130        ** flag is not set, but the table has one or more indexes, call
103131        ** GenerateRowIndexDelete(). This removes the index b-tree entries
103132        ** only. The table b-tree entry will be replaced by the new entry
103133        ** when it is inserted.
103134        **
103135        ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
103136        ** also invoke MultiWrite() to indicate that this VDBE may require
103137        ** statement rollback (if the statement is aborted after the delete
103138        ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
103139        ** but being more selective here allows statements like:
103140        **
103141        **   REPLACE INTO t(rowid) VALUES($newrowid)
103142        **
103143        ** to run without a statement journal if there are no indexes on the
103144        ** table.
103145        */
103146        Trigger *pTrigger = 0;
103147        if( db->flags&SQLITE_RecTriggers ){
103148          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
103149        }
103150        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
103151          sqlite3MultiWrite(pParse);
103152          sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
103153                                   regNewData, 1, 0, OE_Replace,
103154                                   ONEPASS_SINGLE, -1);
103155        }else{
103156          if( pTab->pIndex ){
103157            sqlite3MultiWrite(pParse);
103158            sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
103159          }
103160        }
103161        seenReplace = 1;
103162        break;
103163      }
103164      case OE_Ignore: {
103165        /*assert( seenReplace==0 );*/
103166        sqlite3VdbeGoto(v, ignoreDest);
103167        break;
103168      }
103169    }
103170    sqlite3VdbeResolveLabel(v, addrRowidOk);
103171    if( ipkTop ){
103172      ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
103173      sqlite3VdbeJumpHere(v, ipkTop);
103174    }
103175  }
103176
103177  /* Test all UNIQUE constraints by creating entries for each UNIQUE
103178  ** index and making sure that duplicate entries do not already exist.
103179  ** Compute the revised record entries for indices as we go.
103180  **
103181  ** This loop also handles the case of the PRIMARY KEY index for a
103182  ** WITHOUT ROWID table.
103183  */
103184  for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
103185    int regIdx;          /* Range of registers hold conent for pIdx */
103186    int regR;            /* Range of registers holding conflicting PK */
103187    int iThisCur;        /* Cursor for this UNIQUE index */
103188    int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
103189
103190    if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
103191    if( bAffinityDone==0 ){
103192      sqlite3TableAffinity(v, pTab, regNewData+1);
103193      bAffinityDone = 1;
103194    }
103195    iThisCur = iIdxCur+ix;
103196    addrUniqueOk = sqlite3VdbeMakeLabel(v);
103197
103198    /* Skip partial indices for which the WHERE clause is not true */
103199    if( pIdx->pPartIdxWhere ){
103200      sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
103201      pParse->ckBase = regNewData+1;
103202      sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
103203                            SQLITE_JUMPIFNULL);
103204      pParse->ckBase = 0;
103205    }
103206
103207    /* Create a record for this index entry as it should appear after
103208    ** the insert or update.  Store that record in the aRegIdx[ix] register
103209    */
103210    regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
103211    for(i=0; i<pIdx->nColumn; i++){
103212      int iField = pIdx->aiColumn[i];
103213      int x;
103214      if( iField==XN_EXPR ){
103215        pParse->ckBase = regNewData+1;
103216        sqlite3ExprCode(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
103217        pParse->ckBase = 0;
103218        VdbeComment((v, "%s column %d", pIdx->zName, i));
103219      }else{
103220        if( iField==XN_ROWID || iField==pTab->iPKey ){
103221          if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
103222          x = regNewData;
103223          regRowid =  pIdx->pPartIdxWhere ? -1 : regIdx+i;
103224        }else{
103225          x = iField + regNewData + 1;
103226        }
103227        sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
103228        VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
103229      }
103230    }
103231    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
103232    VdbeComment((v, "for %s", pIdx->zName));
103233    sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
103234
103235    /* In an UPDATE operation, if this index is the PRIMARY KEY index
103236    ** of a WITHOUT ROWID table and there has been no change the
103237    ** primary key, then no collision is possible.  The collision detection
103238    ** logic below can all be skipped. */
103239    if( isUpdate && pPk==pIdx && pkChng==0 ){
103240      sqlite3VdbeResolveLabel(v, addrUniqueOk);
103241      continue;
103242    }
103243
103244    /* Find out what action to take in case there is a uniqueness conflict */
103245    onError = pIdx->onError;
103246    if( onError==OE_None ){
103247      sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
103248      sqlite3VdbeResolveLabel(v, addrUniqueOk);
103249      continue;  /* pIdx is not a UNIQUE index */
103250    }
103251    if( overrideError!=OE_Default ){
103252      onError = overrideError;
103253    }else if( onError==OE_Default ){
103254      onError = OE_Abort;
103255    }
103256
103257    /* Check to see if the new index entry will be unique */
103258    sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
103259                         regIdx, pIdx->nKeyCol); VdbeCoverage(v);
103260
103261    /* Generate code to handle collisions */
103262    regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
103263    if( isUpdate || onError==OE_Replace ){
103264      if( HasRowid(pTab) ){
103265        sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
103266        /* Conflict only if the rowid of the existing index entry
103267        ** is different from old-rowid */
103268        if( isUpdate ){
103269          sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
103270          sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
103271          VdbeCoverage(v);
103272        }
103273      }else{
103274        int x;
103275        /* Extract the PRIMARY KEY from the end of the index entry and
103276        ** store it in registers regR..regR+nPk-1 */
103277        if( pIdx!=pPk ){
103278          for(i=0; i<pPk->nKeyCol; i++){
103279            assert( pPk->aiColumn[i]>=0 );
103280            x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
103281            sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
103282            VdbeComment((v, "%s.%s", pTab->zName,
103283                         pTab->aCol[pPk->aiColumn[i]].zName));
103284          }
103285        }
103286        if( isUpdate ){
103287          /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
103288          ** table, only conflict if the new PRIMARY KEY values are actually
103289          ** different from the old.
103290          **
103291          ** For a UNIQUE index, only conflict if the PRIMARY KEY values
103292          ** of the matched index row are different from the original PRIMARY
103293          ** KEY values of this row before the update.  */
103294          int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
103295          int op = OP_Ne;
103296          int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
103297
103298          for(i=0; i<pPk->nKeyCol; i++){
103299            char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
103300            x = pPk->aiColumn[i];
103301            assert( x>=0 );
103302            if( i==(pPk->nKeyCol-1) ){
103303              addrJump = addrUniqueOk;
103304              op = OP_Eq;
103305            }
103306            sqlite3VdbeAddOp4(v, op,
103307                regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
103308            );
103309            sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
103310            VdbeCoverageIf(v, op==OP_Eq);
103311            VdbeCoverageIf(v, op==OP_Ne);
103312          }
103313        }
103314      }
103315    }
103316
103317    /* Generate code that executes if the new index entry is not unique */
103318    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
103319        || onError==OE_Ignore || onError==OE_Replace );
103320    switch( onError ){
103321      case OE_Rollback:
103322      case OE_Abort:
103323      case OE_Fail: {
103324        sqlite3UniqueConstraint(pParse, onError, pIdx);
103325        break;
103326      }
103327      case OE_Ignore: {
103328        sqlite3VdbeGoto(v, ignoreDest);
103329        break;
103330      }
103331      default: {
103332        Trigger *pTrigger = 0;
103333        assert( onError==OE_Replace );
103334        sqlite3MultiWrite(pParse);
103335        if( db->flags&SQLITE_RecTriggers ){
103336          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
103337        }
103338        sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
103339            regR, nPkField, 0, OE_Replace,
103340            (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), -1);
103341        seenReplace = 1;
103342        break;
103343      }
103344    }
103345    sqlite3VdbeResolveLabel(v, addrUniqueOk);
103346    sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
103347    if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
103348  }
103349  if( ipkTop ){
103350    sqlite3VdbeGoto(v, ipkTop+1);
103351    sqlite3VdbeJumpHere(v, ipkBottom);
103352  }
103353
103354  *pbMayReplace = seenReplace;
103355  VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
103356}
103357
103358/*
103359** This routine generates code to finish the INSERT or UPDATE operation
103360** that was started by a prior call to sqlite3GenerateConstraintChecks.
103361** A consecutive range of registers starting at regNewData contains the
103362** rowid and the content to be inserted.
103363**
103364** The arguments to this routine should be the same as the first six
103365** arguments to sqlite3GenerateConstraintChecks.
103366*/
103367SQLITE_PRIVATE void sqlite3CompleteInsertion(
103368  Parse *pParse,      /* The parser context */
103369  Table *pTab,        /* the table into which we are inserting */
103370  int iDataCur,       /* Cursor of the canonical data source */
103371  int iIdxCur,        /* First index cursor */
103372  int regNewData,     /* Range of content */
103373  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
103374  int isUpdate,       /* True for UPDATE, False for INSERT */
103375  int appendBias,     /* True if this is likely to be an append */
103376  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
103377){
103378  Vdbe *v;            /* Prepared statements under construction */
103379  Index *pIdx;        /* An index being inserted or updated */
103380  u8 pik_flags;       /* flag values passed to the btree insert */
103381  int regData;        /* Content registers (after the rowid) */
103382  int regRec;         /* Register holding assembled record for the table */
103383  int i;              /* Loop counter */
103384  u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
103385
103386  v = sqlite3GetVdbe(pParse);
103387  assert( v!=0 );
103388  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
103389  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
103390    if( aRegIdx[i]==0 ) continue;
103391    bAffinityDone = 1;
103392    if( pIdx->pPartIdxWhere ){
103393      sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
103394      VdbeCoverage(v);
103395    }
103396    sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
103397    pik_flags = 0;
103398    if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
103399    if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
103400      assert( pParse->nested==0 );
103401      pik_flags |= OPFLAG_NCHANGE;
103402    }
103403    if( pik_flags )  sqlite3VdbeChangeP5(v, pik_flags);
103404  }
103405  if( !HasRowid(pTab) ) return;
103406  regData = regNewData + 1;
103407  regRec = sqlite3GetTempReg(pParse);
103408  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
103409  if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
103410  sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
103411  if( pParse->nested ){
103412    pik_flags = 0;
103413  }else{
103414    pik_flags = OPFLAG_NCHANGE;
103415    pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
103416  }
103417  if( appendBias ){
103418    pik_flags |= OPFLAG_APPEND;
103419  }
103420  if( useSeekResult ){
103421    pik_flags |= OPFLAG_USESEEKRESULT;
103422  }
103423  sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
103424  if( !pParse->nested ){
103425    sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
103426  }
103427  sqlite3VdbeChangeP5(v, pik_flags);
103428}
103429
103430/*
103431** Allocate cursors for the pTab table and all its indices and generate
103432** code to open and initialized those cursors.
103433**
103434** The cursor for the object that contains the complete data (normally
103435** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
103436** ROWID table) is returned in *piDataCur.  The first index cursor is
103437** returned in *piIdxCur.  The number of indices is returned.
103438**
103439** Use iBase as the first cursor (either the *piDataCur for rowid tables
103440** or the first index for WITHOUT ROWID tables) if it is non-negative.
103441** If iBase is negative, then allocate the next available cursor.
103442**
103443** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
103444** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
103445** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
103446** pTab->pIndex list.
103447**
103448** If pTab is a virtual table, then this routine is a no-op and the
103449** *piDataCur and *piIdxCur values are left uninitialized.
103450*/
103451SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
103452  Parse *pParse,   /* Parsing context */
103453  Table *pTab,     /* Table to be opened */
103454  int op,          /* OP_OpenRead or OP_OpenWrite */
103455  int iBase,       /* Use this for the table cursor, if there is one */
103456  u8 *aToOpen,     /* If not NULL: boolean for each table and index */
103457  int *piDataCur,  /* Write the database source cursor number here */
103458  int *piIdxCur    /* Write the first index cursor number here */
103459){
103460  int i;
103461  int iDb;
103462  int iDataCur;
103463  Index *pIdx;
103464  Vdbe *v;
103465
103466  assert( op==OP_OpenRead || op==OP_OpenWrite );
103467  if( IsVirtual(pTab) ){
103468    /* This routine is a no-op for virtual tables. Leave the output
103469    ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
103470    ** can detect if they are used by mistake in the caller. */
103471    return 0;
103472  }
103473  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
103474  v = sqlite3GetVdbe(pParse);
103475  assert( v!=0 );
103476  if( iBase<0 ) iBase = pParse->nTab;
103477  iDataCur = iBase++;
103478  if( piDataCur ) *piDataCur = iDataCur;
103479  if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
103480    sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
103481  }else{
103482    sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
103483  }
103484  if( piIdxCur ) *piIdxCur = iBase;
103485  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
103486    int iIdxCur = iBase++;
103487    assert( pIdx->pSchema==pTab->pSchema );
103488    if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){
103489      *piDataCur = iIdxCur;
103490    }
103491    if( aToOpen==0 || aToOpen[i+1] ){
103492      sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
103493      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
103494      VdbeComment((v, "%s", pIdx->zName));
103495    }
103496  }
103497  if( iBase>pParse->nTab ) pParse->nTab = iBase;
103498  return i;
103499}
103500
103501
103502#ifdef SQLITE_TEST
103503/*
103504** The following global variable is incremented whenever the
103505** transfer optimization is used.  This is used for testing
103506** purposes only - to make sure the transfer optimization really
103507** is happening when it is supposed to.
103508*/
103509SQLITE_API int sqlite3_xferopt_count;
103510#endif /* SQLITE_TEST */
103511
103512
103513#ifndef SQLITE_OMIT_XFER_OPT
103514/*
103515** Check to collation names to see if they are compatible.
103516*/
103517static int xferCompatibleCollation(const char *z1, const char *z2){
103518  if( z1==0 ){
103519    return z2==0;
103520  }
103521  if( z2==0 ){
103522    return 0;
103523  }
103524  return sqlite3StrICmp(z1, z2)==0;
103525}
103526
103527
103528/*
103529** Check to see if index pSrc is compatible as a source of data
103530** for index pDest in an insert transfer optimization.  The rules
103531** for a compatible index:
103532**
103533**    *   The index is over the same set of columns
103534**    *   The same DESC and ASC markings occurs on all columns
103535**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
103536**    *   The same collating sequence on each column
103537**    *   The index has the exact same WHERE clause
103538*/
103539static int xferCompatibleIndex(Index *pDest, Index *pSrc){
103540  int i;
103541  assert( pDest && pSrc );
103542  assert( pDest->pTable!=pSrc->pTable );
103543  if( pDest->nKeyCol!=pSrc->nKeyCol ){
103544    return 0;   /* Different number of columns */
103545  }
103546  if( pDest->onError!=pSrc->onError ){
103547    return 0;   /* Different conflict resolution strategies */
103548  }
103549  for(i=0; i<pSrc->nKeyCol; i++){
103550    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
103551      return 0;   /* Different columns indexed */
103552    }
103553    if( pSrc->aiColumn[i]==XN_EXPR ){
103554      assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
103555      if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr,
103556                             pDest->aColExpr->a[i].pExpr, -1)!=0 ){
103557        return 0;   /* Different expressions in the index */
103558      }
103559    }
103560    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
103561      return 0;   /* Different sort orders */
103562    }
103563    if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
103564      return 0;   /* Different collating sequences */
103565    }
103566  }
103567  if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
103568    return 0;     /* Different WHERE clauses */
103569  }
103570
103571  /* If no test above fails then the indices must be compatible */
103572  return 1;
103573}
103574
103575/*
103576** Attempt the transfer optimization on INSERTs of the form
103577**
103578**     INSERT INTO tab1 SELECT * FROM tab2;
103579**
103580** The xfer optimization transfers raw records from tab2 over to tab1.
103581** Columns are not decoded and reassembled, which greatly improves
103582** performance.  Raw index records are transferred in the same way.
103583**
103584** The xfer optimization is only attempted if tab1 and tab2 are compatible.
103585** There are lots of rules for determining compatibility - see comments
103586** embedded in the code for details.
103587**
103588** This routine returns TRUE if the optimization is guaranteed to be used.
103589** Sometimes the xfer optimization will only work if the destination table
103590** is empty - a factor that can only be determined at run-time.  In that
103591** case, this routine generates code for the xfer optimization but also
103592** does a test to see if the destination table is empty and jumps over the
103593** xfer optimization code if the test fails.  In that case, this routine
103594** returns FALSE so that the caller will know to go ahead and generate
103595** an unoptimized transfer.  This routine also returns FALSE if there
103596** is no chance that the xfer optimization can be applied.
103597**
103598** This optimization is particularly useful at making VACUUM run faster.
103599*/
103600static int xferOptimization(
103601  Parse *pParse,        /* Parser context */
103602  Table *pDest,         /* The table we are inserting into */
103603  Select *pSelect,      /* A SELECT statement to use as the data source */
103604  int onError,          /* How to handle constraint errors */
103605  int iDbDest           /* The database of pDest */
103606){
103607  sqlite3 *db = pParse->db;
103608  ExprList *pEList;                /* The result set of the SELECT */
103609  Table *pSrc;                     /* The table in the FROM clause of SELECT */
103610  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
103611  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
103612  int i;                           /* Loop counter */
103613  int iDbSrc;                      /* The database of pSrc */
103614  int iSrc, iDest;                 /* Cursors from source and destination */
103615  int addr1, addr2;                /* Loop addresses */
103616  int emptyDestTest = 0;           /* Address of test for empty pDest */
103617  int emptySrcTest = 0;            /* Address of test for empty pSrc */
103618  Vdbe *v;                         /* The VDBE we are building */
103619  int regAutoinc;                  /* Memory register used by AUTOINC */
103620  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
103621  int regData, regRowid;           /* Registers holding data and rowid */
103622
103623  if( pSelect==0 ){
103624    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
103625  }
103626  if( pParse->pWith || pSelect->pWith ){
103627    /* Do not attempt to process this query if there are an WITH clauses
103628    ** attached to it. Proceeding may generate a false "no such table: xxx"
103629    ** error if pSelect reads from a CTE named "xxx".  */
103630    return 0;
103631  }
103632  if( sqlite3TriggerList(pParse, pDest) ){
103633    return 0;   /* tab1 must not have triggers */
103634  }
103635#ifndef SQLITE_OMIT_VIRTUALTABLE
103636  if( pDest->tabFlags & TF_Virtual ){
103637    return 0;   /* tab1 must not be a virtual table */
103638  }
103639#endif
103640  if( onError==OE_Default ){
103641    if( pDest->iPKey>=0 ) onError = pDest->keyConf;
103642    if( onError==OE_Default ) onError = OE_Abort;
103643  }
103644  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
103645  if( pSelect->pSrc->nSrc!=1 ){
103646    return 0;   /* FROM clause must have exactly one term */
103647  }
103648  if( pSelect->pSrc->a[0].pSelect ){
103649    return 0;   /* FROM clause cannot contain a subquery */
103650  }
103651  if( pSelect->pWhere ){
103652    return 0;   /* SELECT may not have a WHERE clause */
103653  }
103654  if( pSelect->pOrderBy ){
103655    return 0;   /* SELECT may not have an ORDER BY clause */
103656  }
103657  /* Do not need to test for a HAVING clause.  If HAVING is present but
103658  ** there is no ORDER BY, we will get an error. */
103659  if( pSelect->pGroupBy ){
103660    return 0;   /* SELECT may not have a GROUP BY clause */
103661  }
103662  if( pSelect->pLimit ){
103663    return 0;   /* SELECT may not have a LIMIT clause */
103664  }
103665  assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
103666  if( pSelect->pPrior ){
103667    return 0;   /* SELECT may not be a compound query */
103668  }
103669  if( pSelect->selFlags & SF_Distinct ){
103670    return 0;   /* SELECT may not be DISTINCT */
103671  }
103672  pEList = pSelect->pEList;
103673  assert( pEList!=0 );
103674  if( pEList->nExpr!=1 ){
103675    return 0;   /* The result set must have exactly one column */
103676  }
103677  assert( pEList->a[0].pExpr );
103678  if( pEList->a[0].pExpr->op!=TK_ALL ){
103679    return 0;   /* The result set must be the special operator "*" */
103680  }
103681
103682  /* At this point we have established that the statement is of the
103683  ** correct syntactic form to participate in this optimization.  Now
103684  ** we have to check the semantics.
103685  */
103686  pItem = pSelect->pSrc->a;
103687  pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
103688  if( pSrc==0 ){
103689    return 0;   /* FROM clause does not contain a real table */
103690  }
103691  if( pSrc==pDest ){
103692    return 0;   /* tab1 and tab2 may not be the same table */
103693  }
103694  if( HasRowid(pDest)!=HasRowid(pSrc) ){
103695    return 0;   /* source and destination must both be WITHOUT ROWID or not */
103696  }
103697#ifndef SQLITE_OMIT_VIRTUALTABLE
103698  if( pSrc->tabFlags & TF_Virtual ){
103699    return 0;   /* tab2 must not be a virtual table */
103700  }
103701#endif
103702  if( pSrc->pSelect ){
103703    return 0;   /* tab2 may not be a view */
103704  }
103705  if( pDest->nCol!=pSrc->nCol ){
103706    return 0;   /* Number of columns must be the same in tab1 and tab2 */
103707  }
103708  if( pDest->iPKey!=pSrc->iPKey ){
103709    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
103710  }
103711  for(i=0; i<pDest->nCol; i++){
103712    Column *pDestCol = &pDest->aCol[i];
103713    Column *pSrcCol = &pSrc->aCol[i];
103714    if( pDestCol->affinity!=pSrcCol->affinity ){
103715      return 0;    /* Affinity must be the same on all columns */
103716    }
103717    if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){
103718      return 0;    /* Collating sequence must be the same on all columns */
103719    }
103720    if( pDestCol->notNull && !pSrcCol->notNull ){
103721      return 0;    /* tab2 must be NOT NULL if tab1 is */
103722    }
103723    /* Default values for second and subsequent columns need to match. */
103724    if( i>0
103725     && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0)
103726         || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0))
103727    ){
103728      return 0;    /* Default values must be the same for all columns */
103729    }
103730  }
103731  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
103732    if( IsUniqueIndex(pDestIdx) ){
103733      destHasUniqueIdx = 1;
103734    }
103735    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
103736      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
103737    }
103738    if( pSrcIdx==0 ){
103739      return 0;    /* pDestIdx has no corresponding index in pSrc */
103740    }
103741  }
103742#ifndef SQLITE_OMIT_CHECK
103743  if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
103744    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
103745  }
103746#endif
103747#ifndef SQLITE_OMIT_FOREIGN_KEY
103748  /* Disallow the transfer optimization if the destination table constains
103749  ** any foreign key constraints.  This is more restrictive than necessary.
103750  ** But the main beneficiary of the transfer optimization is the VACUUM
103751  ** command, and the VACUUM command disables foreign key constraints.  So
103752  ** the extra complication to make this rule less restrictive is probably
103753  ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
103754  */
103755  if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
103756    return 0;
103757  }
103758#endif
103759  if( (db->flags & SQLITE_CountRows)!=0 ){
103760    return 0;  /* xfer opt does not play well with PRAGMA count_changes */
103761  }
103762
103763  /* If we get this far, it means that the xfer optimization is at
103764  ** least a possibility, though it might only work if the destination
103765  ** table (tab1) is initially empty.
103766  */
103767#ifdef SQLITE_TEST
103768  sqlite3_xferopt_count++;
103769#endif
103770  iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
103771  v = sqlite3GetVdbe(pParse);
103772  sqlite3CodeVerifySchema(pParse, iDbSrc);
103773  iSrc = pParse->nTab++;
103774  iDest = pParse->nTab++;
103775  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
103776  regData = sqlite3GetTempReg(pParse);
103777  regRowid = sqlite3GetTempReg(pParse);
103778  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
103779  assert( HasRowid(pDest) || destHasUniqueIdx );
103780  if( (db->flags & SQLITE_Vacuum)==0 && (
103781      (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
103782   || destHasUniqueIdx                              /* (2) */
103783   || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
103784  )){
103785    /* In some circumstances, we are able to run the xfer optimization
103786    ** only if the destination table is initially empty. Unless the
103787    ** SQLITE_Vacuum flag is set, this block generates code to make
103788    ** that determination. If SQLITE_Vacuum is set, then the destination
103789    ** table is always empty.
103790    **
103791    ** Conditions under which the destination must be empty:
103792    **
103793    ** (1) There is no INTEGER PRIMARY KEY but there are indices.
103794    **     (If the destination is not initially empty, the rowid fields
103795    **     of index entries might need to change.)
103796    **
103797    ** (2) The destination has a unique index.  (The xfer optimization
103798    **     is unable to test uniqueness.)
103799    **
103800    ** (3) onError is something other than OE_Abort and OE_Rollback.
103801    */
103802    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
103803    emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
103804    sqlite3VdbeJumpHere(v, addr1);
103805  }
103806  if( HasRowid(pSrc) ){
103807    sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
103808    emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
103809    if( pDest->iPKey>=0 ){
103810      addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
103811      addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
103812      VdbeCoverage(v);
103813      sqlite3RowidConstraint(pParse, onError, pDest);
103814      sqlite3VdbeJumpHere(v, addr2);
103815      autoIncStep(pParse, regAutoinc, regRowid);
103816    }else if( pDest->pIndex==0 ){
103817      addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
103818    }else{
103819      addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
103820      assert( (pDest->tabFlags & TF_Autoincrement)==0 );
103821    }
103822    sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
103823    sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
103824    sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
103825    sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
103826    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
103827    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
103828    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
103829  }else{
103830    sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
103831    sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
103832  }
103833  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
103834    u8 idxInsFlags = 0;
103835    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
103836      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
103837    }
103838    assert( pSrcIdx );
103839    sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
103840    sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
103841    VdbeComment((v, "%s", pSrcIdx->zName));
103842    sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
103843    sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
103844    sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
103845    VdbeComment((v, "%s", pDestIdx->zName));
103846    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
103847    sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
103848    if( db->flags & SQLITE_Vacuum ){
103849      /* This INSERT command is part of a VACUUM operation, which guarantees
103850      ** that the destination table is empty. If all indexed columns use
103851      ** collation sequence BINARY, then it can also be assumed that the
103852      ** index will be populated by inserting keys in strictly sorted
103853      ** order. In this case, instead of seeking within the b-tree as part
103854      ** of every OP_IdxInsert opcode, an OP_Last is added before the
103855      ** OP_IdxInsert to seek to the point within the b-tree where each key
103856      ** should be inserted. This is faster.
103857      **
103858      ** If any of the indexed columns use a collation sequence other than
103859      ** BINARY, this optimization is disabled. This is because the user
103860      ** might change the definition of a collation sequence and then run
103861      ** a VACUUM command. In that case keys may not be written in strictly
103862      ** sorted order.  */
103863      for(i=0; i<pSrcIdx->nColumn; i++){
103864        char *zColl = pSrcIdx->azColl[i];
103865        assert( zColl!=0 );
103866        if( sqlite3_stricmp("BINARY", zColl) ) break;
103867      }
103868      if( i==pSrcIdx->nColumn ){
103869        idxInsFlags = OPFLAG_USESEEKRESULT;
103870        sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
103871      }
103872    }
103873    if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
103874      idxInsFlags |= OPFLAG_NCHANGE;
103875    }
103876    sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
103877    sqlite3VdbeChangeP5(v, idxInsFlags);
103878    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
103879    sqlite3VdbeJumpHere(v, addr1);
103880    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
103881    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
103882  }
103883  if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
103884  sqlite3ReleaseTempReg(pParse, regRowid);
103885  sqlite3ReleaseTempReg(pParse, regData);
103886  if( emptyDestTest ){
103887    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
103888    sqlite3VdbeJumpHere(v, emptyDestTest);
103889    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
103890    return 0;
103891  }else{
103892    return 1;
103893  }
103894}
103895#endif /* SQLITE_OMIT_XFER_OPT */
103896
103897/************** End of insert.c **********************************************/
103898/************** Begin file legacy.c ******************************************/
103899/*
103900** 2001 September 15
103901**
103902** The author disclaims copyright to this source code.  In place of
103903** a legal notice, here is a blessing:
103904**
103905**    May you do good and not evil.
103906**    May you find forgiveness for yourself and forgive others.
103907**    May you share freely, never taking more than you give.
103908**
103909*************************************************************************
103910** Main file for the SQLite library.  The routines in this file
103911** implement the programmer interface to the library.  Routines in
103912** other files are for internal use by SQLite and should not be
103913** accessed by users of the library.
103914*/
103915
103916/* #include "sqliteInt.h" */
103917
103918/*
103919** Execute SQL code.  Return one of the SQLITE_ success/failure
103920** codes.  Also write an error message into memory obtained from
103921** malloc() and make *pzErrMsg point to that message.
103922**
103923** If the SQL is a query, then for each row in the query result
103924** the xCallback() function is called.  pArg becomes the first
103925** argument to xCallback().  If xCallback=NULL then no callback
103926** is invoked, even for queries.
103927*/
103928SQLITE_API int SQLITE_STDCALL sqlite3_exec(
103929  sqlite3 *db,                /* The database on which the SQL executes */
103930  const char *zSql,           /* The SQL to be executed */
103931  sqlite3_callback xCallback, /* Invoke this callback routine */
103932  void *pArg,                 /* First argument to xCallback() */
103933  char **pzErrMsg             /* Write error messages here */
103934){
103935  int rc = SQLITE_OK;         /* Return code */
103936  const char *zLeftover;      /* Tail of unprocessed SQL */
103937  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
103938  char **azCols = 0;          /* Names of result columns */
103939  int callbackIsInit;         /* True if callback data is initialized */
103940
103941  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
103942  if( zSql==0 ) zSql = "";
103943
103944  sqlite3_mutex_enter(db->mutex);
103945  sqlite3Error(db, SQLITE_OK);
103946  while( rc==SQLITE_OK && zSql[0] ){
103947    int nCol;
103948    char **azVals = 0;
103949
103950    pStmt = 0;
103951    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
103952    assert( rc==SQLITE_OK || pStmt==0 );
103953    if( rc!=SQLITE_OK ){
103954      continue;
103955    }
103956    if( !pStmt ){
103957      /* this happens for a comment or white-space */
103958      zSql = zLeftover;
103959      continue;
103960    }
103961
103962    callbackIsInit = 0;
103963    nCol = sqlite3_column_count(pStmt);
103964
103965    while( 1 ){
103966      int i;
103967      rc = sqlite3_step(pStmt);
103968
103969      /* Invoke the callback function if required */
103970      if( xCallback && (SQLITE_ROW==rc ||
103971          (SQLITE_DONE==rc && !callbackIsInit
103972                           && db->flags&SQLITE_NullCallback)) ){
103973        if( !callbackIsInit ){
103974          azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
103975          if( azCols==0 ){
103976            goto exec_out;
103977          }
103978          for(i=0; i<nCol; i++){
103979            azCols[i] = (char *)sqlite3_column_name(pStmt, i);
103980            /* sqlite3VdbeSetColName() installs column names as UTF8
103981            ** strings so there is no way for sqlite3_column_name() to fail. */
103982            assert( azCols[i]!=0 );
103983          }
103984          callbackIsInit = 1;
103985        }
103986        if( rc==SQLITE_ROW ){
103987          azVals = &azCols[nCol];
103988          for(i=0; i<nCol; i++){
103989            azVals[i] = (char *)sqlite3_column_text(pStmt, i);
103990            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
103991              db->mallocFailed = 1;
103992              goto exec_out;
103993            }
103994          }
103995        }
103996        if( xCallback(pArg, nCol, azVals, azCols) ){
103997          /* EVIDENCE-OF: R-38229-40159 If the callback function to
103998          ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
103999          ** return SQLITE_ABORT. */
104000          rc = SQLITE_ABORT;
104001          sqlite3VdbeFinalize((Vdbe *)pStmt);
104002          pStmt = 0;
104003          sqlite3Error(db, SQLITE_ABORT);
104004          goto exec_out;
104005        }
104006      }
104007
104008      if( rc!=SQLITE_ROW ){
104009        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
104010        pStmt = 0;
104011        zSql = zLeftover;
104012        while( sqlite3Isspace(zSql[0]) ) zSql++;
104013        break;
104014      }
104015    }
104016
104017    sqlite3DbFree(db, azCols);
104018    azCols = 0;
104019  }
104020
104021exec_out:
104022  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
104023  sqlite3DbFree(db, azCols);
104024
104025  rc = sqlite3ApiExit(db, rc);
104026  if( rc!=SQLITE_OK && pzErrMsg ){
104027    int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
104028    *pzErrMsg = sqlite3Malloc(nErrMsg);
104029    if( *pzErrMsg ){
104030      memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
104031    }else{
104032      rc = SQLITE_NOMEM;
104033      sqlite3Error(db, SQLITE_NOMEM);
104034    }
104035  }else if( pzErrMsg ){
104036    *pzErrMsg = 0;
104037  }
104038
104039  assert( (rc&db->errMask)==rc );
104040  sqlite3_mutex_leave(db->mutex);
104041  return rc;
104042}
104043
104044/************** End of legacy.c **********************************************/
104045/************** Begin file loadext.c *****************************************/
104046/*
104047** 2006 June 7
104048**
104049** The author disclaims copyright to this source code.  In place of
104050** a legal notice, here is a blessing:
104051**
104052**    May you do good and not evil.
104053**    May you find forgiveness for yourself and forgive others.
104054**    May you share freely, never taking more than you give.
104055**
104056*************************************************************************
104057** This file contains code used to dynamically load extensions into
104058** the SQLite library.
104059*/
104060
104061#ifndef SQLITE_CORE
104062  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
104063#endif
104064/************** Include sqlite3ext.h in the middle of loadext.c **************/
104065/************** Begin file sqlite3ext.h **************************************/
104066/*
104067** 2006 June 7
104068**
104069** The author disclaims copyright to this source code.  In place of
104070** a legal notice, here is a blessing:
104071**
104072**    May you do good and not evil.
104073**    May you find forgiveness for yourself and forgive others.
104074**    May you share freely, never taking more than you give.
104075**
104076*************************************************************************
104077** This header file defines the SQLite interface for use by
104078** shared libraries that want to be imported as extensions into
104079** an SQLite instance.  Shared libraries that intend to be loaded
104080** as extensions by SQLite should #include this file instead of
104081** sqlite3.h.
104082*/
104083#ifndef _SQLITE3EXT_H_
104084#define _SQLITE3EXT_H_
104085/* #include "sqlite3.h" */
104086
104087typedef struct sqlite3_api_routines sqlite3_api_routines;
104088
104089/*
104090** The following structure holds pointers to all of the SQLite API
104091** routines.
104092**
104093** WARNING:  In order to maintain backwards compatibility, add new
104094** interfaces to the end of this structure only.  If you insert new
104095** interfaces in the middle of this structure, then older different
104096** versions of SQLite will not be able to load each other's shared
104097** libraries!
104098*/
104099struct sqlite3_api_routines {
104100  void * (*aggregate_context)(sqlite3_context*,int nBytes);
104101  int  (*aggregate_count)(sqlite3_context*);
104102  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
104103  int  (*bind_double)(sqlite3_stmt*,int,double);
104104  int  (*bind_int)(sqlite3_stmt*,int,int);
104105  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
104106  int  (*bind_null)(sqlite3_stmt*,int);
104107  int  (*bind_parameter_count)(sqlite3_stmt*);
104108  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
104109  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
104110  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
104111  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
104112  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
104113  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
104114  int  (*busy_timeout)(sqlite3*,int ms);
104115  int  (*changes)(sqlite3*);
104116  int  (*close)(sqlite3*);
104117  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
104118                           int eTextRep,const char*));
104119  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
104120                             int eTextRep,const void*));
104121  const void * (*column_blob)(sqlite3_stmt*,int iCol);
104122  int  (*column_bytes)(sqlite3_stmt*,int iCol);
104123  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
104124  int  (*column_count)(sqlite3_stmt*pStmt);
104125  const char * (*column_database_name)(sqlite3_stmt*,int);
104126  const void * (*column_database_name16)(sqlite3_stmt*,int);
104127  const char * (*column_decltype)(sqlite3_stmt*,int i);
104128  const void * (*column_decltype16)(sqlite3_stmt*,int);
104129  double  (*column_double)(sqlite3_stmt*,int iCol);
104130  int  (*column_int)(sqlite3_stmt*,int iCol);
104131  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
104132  const char * (*column_name)(sqlite3_stmt*,int);
104133  const void * (*column_name16)(sqlite3_stmt*,int);
104134  const char * (*column_origin_name)(sqlite3_stmt*,int);
104135  const void * (*column_origin_name16)(sqlite3_stmt*,int);
104136  const char * (*column_table_name)(sqlite3_stmt*,int);
104137  const void * (*column_table_name16)(sqlite3_stmt*,int);
104138  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
104139  const void * (*column_text16)(sqlite3_stmt*,int iCol);
104140  int  (*column_type)(sqlite3_stmt*,int iCol);
104141  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
104142  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
104143  int  (*complete)(const char*sql);
104144  int  (*complete16)(const void*sql);
104145  int  (*create_collation)(sqlite3*,const char*,int,void*,
104146                           int(*)(void*,int,const void*,int,const void*));
104147  int  (*create_collation16)(sqlite3*,const void*,int,void*,
104148                             int(*)(void*,int,const void*,int,const void*));
104149  int  (*create_function)(sqlite3*,const char*,int,int,void*,
104150                          void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
104151                          void (*xStep)(sqlite3_context*,int,sqlite3_value**),
104152                          void (*xFinal)(sqlite3_context*));
104153  int  (*create_function16)(sqlite3*,const void*,int,int,void*,
104154                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
104155                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
104156                            void (*xFinal)(sqlite3_context*));
104157  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
104158  int  (*data_count)(sqlite3_stmt*pStmt);
104159  sqlite3 * (*db_handle)(sqlite3_stmt*);
104160  int (*declare_vtab)(sqlite3*,const char*);
104161  int  (*enable_shared_cache)(int);
104162  int  (*errcode)(sqlite3*db);
104163  const char * (*errmsg)(sqlite3*);
104164  const void * (*errmsg16)(sqlite3*);
104165  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
104166  int  (*expired)(sqlite3_stmt*);
104167  int  (*finalize)(sqlite3_stmt*pStmt);
104168  void  (*free)(void*);
104169  void  (*free_table)(char**result);
104170  int  (*get_autocommit)(sqlite3*);
104171  void * (*get_auxdata)(sqlite3_context*,int);
104172  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
104173  int  (*global_recover)(void);
104174  void  (*interruptx)(sqlite3*);
104175  sqlite_int64  (*last_insert_rowid)(sqlite3*);
104176  const char * (*libversion)(void);
104177  int  (*libversion_number)(void);
104178  void *(*malloc)(int);
104179  char * (*mprintf)(const char*,...);
104180  int  (*open)(const char*,sqlite3**);
104181  int  (*open16)(const void*,sqlite3**);
104182  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
104183  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
104184  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
104185  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
104186  void *(*realloc)(void*,int);
104187  int  (*reset)(sqlite3_stmt*pStmt);
104188  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
104189  void  (*result_double)(sqlite3_context*,double);
104190  void  (*result_error)(sqlite3_context*,const char*,int);
104191  void  (*result_error16)(sqlite3_context*,const void*,int);
104192  void  (*result_int)(sqlite3_context*,int);
104193  void  (*result_int64)(sqlite3_context*,sqlite_int64);
104194  void  (*result_null)(sqlite3_context*);
104195  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
104196  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
104197  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
104198  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
104199  void  (*result_value)(sqlite3_context*,sqlite3_value*);
104200  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
104201  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
104202                         const char*,const char*),void*);
104203  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
104204  char * (*snprintf)(int,char*,const char*,...);
104205  int  (*step)(sqlite3_stmt*);
104206  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
104207                                char const**,char const**,int*,int*,int*);
104208  void  (*thread_cleanup)(void);
104209  int  (*total_changes)(sqlite3*);
104210  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
104211  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
104212  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
104213                                         sqlite_int64),void*);
104214  void * (*user_data)(sqlite3_context*);
104215  const void * (*value_blob)(sqlite3_value*);
104216  int  (*value_bytes)(sqlite3_value*);
104217  int  (*value_bytes16)(sqlite3_value*);
104218  double  (*value_double)(sqlite3_value*);
104219  int  (*value_int)(sqlite3_value*);
104220  sqlite_int64  (*value_int64)(sqlite3_value*);
104221  int  (*value_numeric_type)(sqlite3_value*);
104222  const unsigned char * (*value_text)(sqlite3_value*);
104223  const void * (*value_text16)(sqlite3_value*);
104224  const void * (*value_text16be)(sqlite3_value*);
104225  const void * (*value_text16le)(sqlite3_value*);
104226  int  (*value_type)(sqlite3_value*);
104227  char *(*vmprintf)(const char*,va_list);
104228  /* Added ??? */
104229  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
104230  /* Added by 3.3.13 */
104231  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
104232  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
104233  int (*clear_bindings)(sqlite3_stmt*);
104234  /* Added by 3.4.1 */
104235  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
104236                          void (*xDestroy)(void *));
104237  /* Added by 3.5.0 */
104238  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
104239  int (*blob_bytes)(sqlite3_blob*);
104240  int (*blob_close)(sqlite3_blob*);
104241  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
104242                   int,sqlite3_blob**);
104243  int (*blob_read)(sqlite3_blob*,void*,int,int);
104244  int (*blob_write)(sqlite3_blob*,const void*,int,int);
104245  int (*create_collation_v2)(sqlite3*,const char*,int,void*,
104246                             int(*)(void*,int,const void*,int,const void*),
104247                             void(*)(void*));
104248  int (*file_control)(sqlite3*,const char*,int,void*);
104249  sqlite3_int64 (*memory_highwater)(int);
104250  sqlite3_int64 (*memory_used)(void);
104251  sqlite3_mutex *(*mutex_alloc)(int);
104252  void (*mutex_enter)(sqlite3_mutex*);
104253  void (*mutex_free)(sqlite3_mutex*);
104254  void (*mutex_leave)(sqlite3_mutex*);
104255  int (*mutex_try)(sqlite3_mutex*);
104256  int (*open_v2)(const char*,sqlite3**,int,const char*);
104257  int (*release_memory)(int);
104258  void (*result_error_nomem)(sqlite3_context*);
104259  void (*result_error_toobig)(sqlite3_context*);
104260  int (*sleep)(int);
104261  void (*soft_heap_limit)(int);
104262  sqlite3_vfs *(*vfs_find)(const char*);
104263  int (*vfs_register)(sqlite3_vfs*,int);
104264  int (*vfs_unregister)(sqlite3_vfs*);
104265  int (*xthreadsafe)(void);
104266  void (*result_zeroblob)(sqlite3_context*,int);
104267  void (*result_error_code)(sqlite3_context*,int);
104268  int (*test_control)(int, ...);
104269  void (*randomness)(int,void*);
104270  sqlite3 *(*context_db_handle)(sqlite3_context*);
104271  int (*extended_result_codes)(sqlite3*,int);
104272  int (*limit)(sqlite3*,int,int);
104273  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
104274  const char *(*sql)(sqlite3_stmt*);
104275  int (*status)(int,int*,int*,int);
104276  int (*backup_finish)(sqlite3_backup*);
104277  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
104278  int (*backup_pagecount)(sqlite3_backup*);
104279  int (*backup_remaining)(sqlite3_backup*);
104280  int (*backup_step)(sqlite3_backup*,int);
104281  const char *(*compileoption_get)(int);
104282  int (*compileoption_used)(const char*);
104283  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
104284                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
104285                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
104286                            void (*xFinal)(sqlite3_context*),
104287                            void(*xDestroy)(void*));
104288  int (*db_config)(sqlite3*,int,...);
104289  sqlite3_mutex *(*db_mutex)(sqlite3*);
104290  int (*db_status)(sqlite3*,int,int*,int*,int);
104291  int (*extended_errcode)(sqlite3*);
104292  void (*log)(int,const char*,...);
104293  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
104294  const char *(*sourceid)(void);
104295  int (*stmt_status)(sqlite3_stmt*,int,int);
104296  int (*strnicmp)(const char*,const char*,int);
104297  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
104298  int (*wal_autocheckpoint)(sqlite3*,int);
104299  int (*wal_checkpoint)(sqlite3*,const char*);
104300  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
104301  int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
104302  int (*vtab_config)(sqlite3*,int op,...);
104303  int (*vtab_on_conflict)(sqlite3*);
104304  /* Version 3.7.16 and later */
104305  int (*close_v2)(sqlite3*);
104306  const char *(*db_filename)(sqlite3*,const char*);
104307  int (*db_readonly)(sqlite3*,const char*);
104308  int (*db_release_memory)(sqlite3*);
104309  const char *(*errstr)(int);
104310  int (*stmt_busy)(sqlite3_stmt*);
104311  int (*stmt_readonly)(sqlite3_stmt*);
104312  int (*stricmp)(const char*,const char*);
104313  int (*uri_boolean)(const char*,const char*,int);
104314  sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
104315  const char *(*uri_parameter)(const char*,const char*);
104316  char *(*vsnprintf)(int,char*,const char*,va_list);
104317  int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
104318  /* Version 3.8.7 and later */
104319  int (*auto_extension)(void(*)(void));
104320  int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
104321                     void(*)(void*));
104322  int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
104323                      void(*)(void*),unsigned char);
104324  int (*cancel_auto_extension)(void(*)(void));
104325  int (*load_extension)(sqlite3*,const char*,const char*,char**);
104326  void *(*malloc64)(sqlite3_uint64);
104327  sqlite3_uint64 (*msize)(void*);
104328  void *(*realloc64)(void*,sqlite3_uint64);
104329  void (*reset_auto_extension)(void);
104330  void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
104331                        void(*)(void*));
104332  void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
104333                         void(*)(void*), unsigned char);
104334  int (*strglob)(const char*,const char*);
104335  /* Version 3.8.11 and later */
104336  sqlite3_value *(*value_dup)(const sqlite3_value*);
104337  void (*value_free)(sqlite3_value*);
104338  int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
104339  int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
104340  /* Version 3.9.0 and later */
104341  unsigned int (*value_subtype)(sqlite3_value*);
104342  void (*result_subtype)(sqlite3_context*,unsigned int);
104343};
104344
104345/*
104346** The following macros redefine the API routines so that they are
104347** redirected through the global sqlite3_api structure.
104348**
104349** This header file is also used by the loadext.c source file
104350** (part of the main SQLite library - not an extension) so that
104351** it can get access to the sqlite3_api_routines structure
104352** definition.  But the main library does not want to redefine
104353** the API.  So the redefinition macros are only valid if the
104354** SQLITE_CORE macros is undefined.
104355*/
104356#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
104357#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
104358#ifndef SQLITE_OMIT_DEPRECATED
104359#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
104360#endif
104361#define sqlite3_bind_blob              sqlite3_api->bind_blob
104362#define sqlite3_bind_double            sqlite3_api->bind_double
104363#define sqlite3_bind_int               sqlite3_api->bind_int
104364#define sqlite3_bind_int64             sqlite3_api->bind_int64
104365#define sqlite3_bind_null              sqlite3_api->bind_null
104366#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
104367#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
104368#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
104369#define sqlite3_bind_text              sqlite3_api->bind_text
104370#define sqlite3_bind_text16            sqlite3_api->bind_text16
104371#define sqlite3_bind_value             sqlite3_api->bind_value
104372#define sqlite3_busy_handler           sqlite3_api->busy_handler
104373#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
104374#define sqlite3_changes                sqlite3_api->changes
104375#define sqlite3_close                  sqlite3_api->close
104376#define sqlite3_collation_needed       sqlite3_api->collation_needed
104377#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
104378#define sqlite3_column_blob            sqlite3_api->column_blob
104379#define sqlite3_column_bytes           sqlite3_api->column_bytes
104380#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
104381#define sqlite3_column_count           sqlite3_api->column_count
104382#define sqlite3_column_database_name   sqlite3_api->column_database_name
104383#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
104384#define sqlite3_column_decltype        sqlite3_api->column_decltype
104385#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
104386#define sqlite3_column_double          sqlite3_api->column_double
104387#define sqlite3_column_int             sqlite3_api->column_int
104388#define sqlite3_column_int64           sqlite3_api->column_int64
104389#define sqlite3_column_name            sqlite3_api->column_name
104390#define sqlite3_column_name16          sqlite3_api->column_name16
104391#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
104392#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
104393#define sqlite3_column_table_name      sqlite3_api->column_table_name
104394#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
104395#define sqlite3_column_text            sqlite3_api->column_text
104396#define sqlite3_column_text16          sqlite3_api->column_text16
104397#define sqlite3_column_type            sqlite3_api->column_type
104398#define sqlite3_column_value           sqlite3_api->column_value
104399#define sqlite3_commit_hook            sqlite3_api->commit_hook
104400#define sqlite3_complete               sqlite3_api->complete
104401#define sqlite3_complete16             sqlite3_api->complete16
104402#define sqlite3_create_collation       sqlite3_api->create_collation
104403#define sqlite3_create_collation16     sqlite3_api->create_collation16
104404#define sqlite3_create_function        sqlite3_api->create_function
104405#define sqlite3_create_function16      sqlite3_api->create_function16
104406#define sqlite3_create_module          sqlite3_api->create_module
104407#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
104408#define sqlite3_data_count             sqlite3_api->data_count
104409#define sqlite3_db_handle              sqlite3_api->db_handle
104410#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
104411#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
104412#define sqlite3_errcode                sqlite3_api->errcode
104413#define sqlite3_errmsg                 sqlite3_api->errmsg
104414#define sqlite3_errmsg16               sqlite3_api->errmsg16
104415#define sqlite3_exec                   sqlite3_api->exec
104416#ifndef SQLITE_OMIT_DEPRECATED
104417#define sqlite3_expired                sqlite3_api->expired
104418#endif
104419#define sqlite3_finalize               sqlite3_api->finalize
104420#define sqlite3_free                   sqlite3_api->free
104421#define sqlite3_free_table             sqlite3_api->free_table
104422#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
104423#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
104424#define sqlite3_get_table              sqlite3_api->get_table
104425#ifndef SQLITE_OMIT_DEPRECATED
104426#define sqlite3_global_recover         sqlite3_api->global_recover
104427#endif
104428#define sqlite3_interrupt              sqlite3_api->interruptx
104429#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
104430#define sqlite3_libversion             sqlite3_api->libversion
104431#define sqlite3_libversion_number      sqlite3_api->libversion_number
104432#define sqlite3_malloc                 sqlite3_api->malloc
104433#define sqlite3_mprintf                sqlite3_api->mprintf
104434#define sqlite3_open                   sqlite3_api->open
104435#define sqlite3_open16                 sqlite3_api->open16
104436#define sqlite3_prepare                sqlite3_api->prepare
104437#define sqlite3_prepare16              sqlite3_api->prepare16
104438#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
104439#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
104440#define sqlite3_profile                sqlite3_api->profile
104441#define sqlite3_progress_handler       sqlite3_api->progress_handler
104442#define sqlite3_realloc                sqlite3_api->realloc
104443#define sqlite3_reset                  sqlite3_api->reset
104444#define sqlite3_result_blob            sqlite3_api->result_blob
104445#define sqlite3_result_double          sqlite3_api->result_double
104446#define sqlite3_result_error           sqlite3_api->result_error
104447#define sqlite3_result_error16         sqlite3_api->result_error16
104448#define sqlite3_result_int             sqlite3_api->result_int
104449#define sqlite3_result_int64           sqlite3_api->result_int64
104450#define sqlite3_result_null            sqlite3_api->result_null
104451#define sqlite3_result_text            sqlite3_api->result_text
104452#define sqlite3_result_text16          sqlite3_api->result_text16
104453#define sqlite3_result_text16be        sqlite3_api->result_text16be
104454#define sqlite3_result_text16le        sqlite3_api->result_text16le
104455#define sqlite3_result_value           sqlite3_api->result_value
104456#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
104457#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
104458#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
104459#define sqlite3_snprintf               sqlite3_api->snprintf
104460#define sqlite3_step                   sqlite3_api->step
104461#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
104462#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
104463#define sqlite3_total_changes          sqlite3_api->total_changes
104464#define sqlite3_trace                  sqlite3_api->trace
104465#ifndef SQLITE_OMIT_DEPRECATED
104466#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
104467#endif
104468#define sqlite3_update_hook            sqlite3_api->update_hook
104469#define sqlite3_user_data              sqlite3_api->user_data
104470#define sqlite3_value_blob             sqlite3_api->value_blob
104471#define sqlite3_value_bytes            sqlite3_api->value_bytes
104472#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
104473#define sqlite3_value_double           sqlite3_api->value_double
104474#define sqlite3_value_int              sqlite3_api->value_int
104475#define sqlite3_value_int64            sqlite3_api->value_int64
104476#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
104477#define sqlite3_value_text             sqlite3_api->value_text
104478#define sqlite3_value_text16           sqlite3_api->value_text16
104479#define sqlite3_value_text16be         sqlite3_api->value_text16be
104480#define sqlite3_value_text16le         sqlite3_api->value_text16le
104481#define sqlite3_value_type             sqlite3_api->value_type
104482#define sqlite3_vmprintf               sqlite3_api->vmprintf
104483#define sqlite3_vsnprintf              sqlite3_api->vsnprintf
104484#define sqlite3_overload_function      sqlite3_api->overload_function
104485#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
104486#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
104487#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
104488#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
104489#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
104490#define sqlite3_blob_close             sqlite3_api->blob_close
104491#define sqlite3_blob_open              sqlite3_api->blob_open
104492#define sqlite3_blob_read              sqlite3_api->blob_read
104493#define sqlite3_blob_write             sqlite3_api->blob_write
104494#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
104495#define sqlite3_file_control           sqlite3_api->file_control
104496#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
104497#define sqlite3_memory_used            sqlite3_api->memory_used
104498#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
104499#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
104500#define sqlite3_mutex_free             sqlite3_api->mutex_free
104501#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
104502#define sqlite3_mutex_try              sqlite3_api->mutex_try
104503#define sqlite3_open_v2                sqlite3_api->open_v2
104504#define sqlite3_release_memory         sqlite3_api->release_memory
104505#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
104506#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
104507#define sqlite3_sleep                  sqlite3_api->sleep
104508#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
104509#define sqlite3_vfs_find               sqlite3_api->vfs_find
104510#define sqlite3_vfs_register           sqlite3_api->vfs_register
104511#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
104512#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
104513#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
104514#define sqlite3_result_error_code      sqlite3_api->result_error_code
104515#define sqlite3_test_control           sqlite3_api->test_control
104516#define sqlite3_randomness             sqlite3_api->randomness
104517#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
104518#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
104519#define sqlite3_limit                  sqlite3_api->limit
104520#define sqlite3_next_stmt              sqlite3_api->next_stmt
104521#define sqlite3_sql                    sqlite3_api->sql
104522#define sqlite3_status                 sqlite3_api->status
104523#define sqlite3_backup_finish          sqlite3_api->backup_finish
104524#define sqlite3_backup_init            sqlite3_api->backup_init
104525#define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
104526#define sqlite3_backup_remaining       sqlite3_api->backup_remaining
104527#define sqlite3_backup_step            sqlite3_api->backup_step
104528#define sqlite3_compileoption_get      sqlite3_api->compileoption_get
104529#define sqlite3_compileoption_used     sqlite3_api->compileoption_used
104530#define sqlite3_create_function_v2     sqlite3_api->create_function_v2
104531#define sqlite3_db_config              sqlite3_api->db_config
104532#define sqlite3_db_mutex               sqlite3_api->db_mutex
104533#define sqlite3_db_status              sqlite3_api->db_status
104534#define sqlite3_extended_errcode       sqlite3_api->extended_errcode
104535#define sqlite3_log                    sqlite3_api->log
104536#define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
104537#define sqlite3_sourceid               sqlite3_api->sourceid
104538#define sqlite3_stmt_status            sqlite3_api->stmt_status
104539#define sqlite3_strnicmp               sqlite3_api->strnicmp
104540#define sqlite3_unlock_notify          sqlite3_api->unlock_notify
104541#define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
104542#define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
104543#define sqlite3_wal_hook               sqlite3_api->wal_hook
104544#define sqlite3_blob_reopen            sqlite3_api->blob_reopen
104545#define sqlite3_vtab_config            sqlite3_api->vtab_config
104546#define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
104547/* Version 3.7.16 and later */
104548#define sqlite3_close_v2               sqlite3_api->close_v2
104549#define sqlite3_db_filename            sqlite3_api->db_filename
104550#define sqlite3_db_readonly            sqlite3_api->db_readonly
104551#define sqlite3_db_release_memory      sqlite3_api->db_release_memory
104552#define sqlite3_errstr                 sqlite3_api->errstr
104553#define sqlite3_stmt_busy              sqlite3_api->stmt_busy
104554#define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
104555#define sqlite3_stricmp                sqlite3_api->stricmp
104556#define sqlite3_uri_boolean            sqlite3_api->uri_boolean
104557#define sqlite3_uri_int64              sqlite3_api->uri_int64
104558#define sqlite3_uri_parameter          sqlite3_api->uri_parameter
104559#define sqlite3_uri_vsnprintf          sqlite3_api->vsnprintf
104560#define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
104561/* Version 3.8.7 and later */
104562#define sqlite3_auto_extension         sqlite3_api->auto_extension
104563#define sqlite3_bind_blob64            sqlite3_api->bind_blob64
104564#define sqlite3_bind_text64            sqlite3_api->bind_text64
104565#define sqlite3_cancel_auto_extension  sqlite3_api->cancel_auto_extension
104566#define sqlite3_load_extension         sqlite3_api->load_extension
104567#define sqlite3_malloc64               sqlite3_api->malloc64
104568#define sqlite3_msize                  sqlite3_api->msize
104569#define sqlite3_realloc64              sqlite3_api->realloc64
104570#define sqlite3_reset_auto_extension   sqlite3_api->reset_auto_extension
104571#define sqlite3_result_blob64          sqlite3_api->result_blob64
104572#define sqlite3_result_text64          sqlite3_api->result_text64
104573#define sqlite3_strglob                sqlite3_api->strglob
104574/* Version 3.8.11 and later */
104575#define sqlite3_value_dup              sqlite3_api->value_dup
104576#define sqlite3_value_free             sqlite3_api->value_free
104577#define sqlite3_result_zeroblob64      sqlite3_api->result_zeroblob64
104578#define sqlite3_bind_zeroblob64        sqlite3_api->bind_zeroblob64
104579/* Version 3.9.0 and later */
104580#define sqlite3_value_subtype          sqlite3_api->value_subtype
104581#define sqlite3_result_subtype         sqlite3_api->result_subtype
104582#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
104583
104584#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
104585  /* This case when the file really is being compiled as a loadable
104586  ** extension */
104587# define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
104588# define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
104589# define SQLITE_EXTENSION_INIT3     \
104590    extern const sqlite3_api_routines *sqlite3_api;
104591#else
104592  /* This case when the file is being statically linked into the
104593  ** application */
104594# define SQLITE_EXTENSION_INIT1     /*no-op*/
104595# define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
104596# define SQLITE_EXTENSION_INIT3     /*no-op*/
104597#endif
104598
104599#endif /* _SQLITE3EXT_H_ */
104600
104601/************** End of sqlite3ext.h ******************************************/
104602/************** Continuing where we left off in loadext.c ********************/
104603/* #include "sqliteInt.h" */
104604/* #include <string.h> */
104605
104606#ifndef SQLITE_OMIT_LOAD_EXTENSION
104607
104608/*
104609** Some API routines are omitted when various features are
104610** excluded from a build of SQLite.  Substitute a NULL pointer
104611** for any missing APIs.
104612*/
104613#ifndef SQLITE_ENABLE_COLUMN_METADATA
104614# define sqlite3_column_database_name   0
104615# define sqlite3_column_database_name16 0
104616# define sqlite3_column_table_name      0
104617# define sqlite3_column_table_name16    0
104618# define sqlite3_column_origin_name     0
104619# define sqlite3_column_origin_name16   0
104620#endif
104621
104622#ifdef SQLITE_OMIT_AUTHORIZATION
104623# define sqlite3_set_authorizer         0
104624#endif
104625
104626#ifdef SQLITE_OMIT_UTF16
104627# define sqlite3_bind_text16            0
104628# define sqlite3_collation_needed16     0
104629# define sqlite3_column_decltype16      0
104630# define sqlite3_column_name16          0
104631# define sqlite3_column_text16          0
104632# define sqlite3_complete16             0
104633# define sqlite3_create_collation16     0
104634# define sqlite3_create_function16      0
104635# define sqlite3_errmsg16               0
104636# define sqlite3_open16                 0
104637# define sqlite3_prepare16              0
104638# define sqlite3_prepare16_v2           0
104639# define sqlite3_result_error16         0
104640# define sqlite3_result_text16          0
104641# define sqlite3_result_text16be        0
104642# define sqlite3_result_text16le        0
104643# define sqlite3_value_text16           0
104644# define sqlite3_value_text16be         0
104645# define sqlite3_value_text16le         0
104646# define sqlite3_column_database_name16 0
104647# define sqlite3_column_table_name16    0
104648# define sqlite3_column_origin_name16   0
104649#endif
104650
104651#ifdef SQLITE_OMIT_COMPLETE
104652# define sqlite3_complete 0
104653# define sqlite3_complete16 0
104654#endif
104655
104656#ifdef SQLITE_OMIT_DECLTYPE
104657# define sqlite3_column_decltype16      0
104658# define sqlite3_column_decltype        0
104659#endif
104660
104661#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
104662# define sqlite3_progress_handler 0
104663#endif
104664
104665#ifdef SQLITE_OMIT_VIRTUALTABLE
104666# define sqlite3_create_module 0
104667# define sqlite3_create_module_v2 0
104668# define sqlite3_declare_vtab 0
104669# define sqlite3_vtab_config 0
104670# define sqlite3_vtab_on_conflict 0
104671#endif
104672
104673#ifdef SQLITE_OMIT_SHARED_CACHE
104674# define sqlite3_enable_shared_cache 0
104675#endif
104676
104677#ifdef SQLITE_OMIT_TRACE
104678# define sqlite3_profile       0
104679# define sqlite3_trace         0
104680#endif
104681
104682#ifdef SQLITE_OMIT_GET_TABLE
104683# define sqlite3_free_table    0
104684# define sqlite3_get_table     0
104685#endif
104686
104687#ifdef SQLITE_OMIT_INCRBLOB
104688#define sqlite3_bind_zeroblob  0
104689#define sqlite3_blob_bytes     0
104690#define sqlite3_blob_close     0
104691#define sqlite3_blob_open      0
104692#define sqlite3_blob_read      0
104693#define sqlite3_blob_write     0
104694#define sqlite3_blob_reopen    0
104695#endif
104696
104697/*
104698** The following structure contains pointers to all SQLite API routines.
104699** A pointer to this structure is passed into extensions when they are
104700** loaded so that the extension can make calls back into the SQLite
104701** library.
104702**
104703** When adding new APIs, add them to the bottom of this structure
104704** in order to preserve backwards compatibility.
104705**
104706** Extensions that use newer APIs should first call the
104707** sqlite3_libversion_number() to make sure that the API they
104708** intend to use is supported by the library.  Extensions should
104709** also check to make sure that the pointer to the function is
104710** not NULL before calling it.
104711*/
104712static const sqlite3_api_routines sqlite3Apis = {
104713  sqlite3_aggregate_context,
104714#ifndef SQLITE_OMIT_DEPRECATED
104715  sqlite3_aggregate_count,
104716#else
104717  0,
104718#endif
104719  sqlite3_bind_blob,
104720  sqlite3_bind_double,
104721  sqlite3_bind_int,
104722  sqlite3_bind_int64,
104723  sqlite3_bind_null,
104724  sqlite3_bind_parameter_count,
104725  sqlite3_bind_parameter_index,
104726  sqlite3_bind_parameter_name,
104727  sqlite3_bind_text,
104728  sqlite3_bind_text16,
104729  sqlite3_bind_value,
104730  sqlite3_busy_handler,
104731  sqlite3_busy_timeout,
104732  sqlite3_changes,
104733  sqlite3_close,
104734  sqlite3_collation_needed,
104735  sqlite3_collation_needed16,
104736  sqlite3_column_blob,
104737  sqlite3_column_bytes,
104738  sqlite3_column_bytes16,
104739  sqlite3_column_count,
104740  sqlite3_column_database_name,
104741  sqlite3_column_database_name16,
104742  sqlite3_column_decltype,
104743  sqlite3_column_decltype16,
104744  sqlite3_column_double,
104745  sqlite3_column_int,
104746  sqlite3_column_int64,
104747  sqlite3_column_name,
104748  sqlite3_column_name16,
104749  sqlite3_column_origin_name,
104750  sqlite3_column_origin_name16,
104751  sqlite3_column_table_name,
104752  sqlite3_column_table_name16,
104753  sqlite3_column_text,
104754  sqlite3_column_text16,
104755  sqlite3_column_type,
104756  sqlite3_column_value,
104757  sqlite3_commit_hook,
104758  sqlite3_complete,
104759  sqlite3_complete16,
104760  sqlite3_create_collation,
104761  sqlite3_create_collation16,
104762  sqlite3_create_function,
104763  sqlite3_create_function16,
104764  sqlite3_create_module,
104765  sqlite3_data_count,
104766  sqlite3_db_handle,
104767  sqlite3_declare_vtab,
104768  sqlite3_enable_shared_cache,
104769  sqlite3_errcode,
104770  sqlite3_errmsg,
104771  sqlite3_errmsg16,
104772  sqlite3_exec,
104773#ifndef SQLITE_OMIT_DEPRECATED
104774  sqlite3_expired,
104775#else
104776  0,
104777#endif
104778  sqlite3_finalize,
104779  sqlite3_free,
104780  sqlite3_free_table,
104781  sqlite3_get_autocommit,
104782  sqlite3_get_auxdata,
104783  sqlite3_get_table,
104784  0,     /* Was sqlite3_global_recover(), but that function is deprecated */
104785  sqlite3_interrupt,
104786  sqlite3_last_insert_rowid,
104787  sqlite3_libversion,
104788  sqlite3_libversion_number,
104789  sqlite3_malloc,
104790  sqlite3_mprintf,
104791  sqlite3_open,
104792  sqlite3_open16,
104793  sqlite3_prepare,
104794  sqlite3_prepare16,
104795  sqlite3_profile,
104796  sqlite3_progress_handler,
104797  sqlite3_realloc,
104798  sqlite3_reset,
104799  sqlite3_result_blob,
104800  sqlite3_result_double,
104801  sqlite3_result_error,
104802  sqlite3_result_error16,
104803  sqlite3_result_int,
104804  sqlite3_result_int64,
104805  sqlite3_result_null,
104806  sqlite3_result_text,
104807  sqlite3_result_text16,
104808  sqlite3_result_text16be,
104809  sqlite3_result_text16le,
104810  sqlite3_result_value,
104811  sqlite3_rollback_hook,
104812  sqlite3_set_authorizer,
104813  sqlite3_set_auxdata,
104814  sqlite3_snprintf,
104815  sqlite3_step,
104816  sqlite3_table_column_metadata,
104817#ifndef SQLITE_OMIT_DEPRECATED
104818  sqlite3_thread_cleanup,
104819#else
104820  0,
104821#endif
104822  sqlite3_total_changes,
104823  sqlite3_trace,
104824#ifndef SQLITE_OMIT_DEPRECATED
104825  sqlite3_transfer_bindings,
104826#else
104827  0,
104828#endif
104829  sqlite3_update_hook,
104830  sqlite3_user_data,
104831  sqlite3_value_blob,
104832  sqlite3_value_bytes,
104833  sqlite3_value_bytes16,
104834  sqlite3_value_double,
104835  sqlite3_value_int,
104836  sqlite3_value_int64,
104837  sqlite3_value_numeric_type,
104838  sqlite3_value_text,
104839  sqlite3_value_text16,
104840  sqlite3_value_text16be,
104841  sqlite3_value_text16le,
104842  sqlite3_value_type,
104843  sqlite3_vmprintf,
104844  /*
104845  ** The original API set ends here.  All extensions can call any
104846  ** of the APIs above provided that the pointer is not NULL.  But
104847  ** before calling APIs that follow, extension should check the
104848  ** sqlite3_libversion_number() to make sure they are dealing with
104849  ** a library that is new enough to support that API.
104850  *************************************************************************
104851  */
104852  sqlite3_overload_function,
104853
104854  /*
104855  ** Added after 3.3.13
104856  */
104857  sqlite3_prepare_v2,
104858  sqlite3_prepare16_v2,
104859  sqlite3_clear_bindings,
104860
104861  /*
104862  ** Added for 3.4.1
104863  */
104864  sqlite3_create_module_v2,
104865
104866  /*
104867  ** Added for 3.5.0
104868  */
104869  sqlite3_bind_zeroblob,
104870  sqlite3_blob_bytes,
104871  sqlite3_blob_close,
104872  sqlite3_blob_open,
104873  sqlite3_blob_read,
104874  sqlite3_blob_write,
104875  sqlite3_create_collation_v2,
104876  sqlite3_file_control,
104877  sqlite3_memory_highwater,
104878  sqlite3_memory_used,
104879#ifdef SQLITE_MUTEX_OMIT
104880  0,
104881  0,
104882  0,
104883  0,
104884  0,
104885#else
104886  sqlite3_mutex_alloc,
104887  sqlite3_mutex_enter,
104888  sqlite3_mutex_free,
104889  sqlite3_mutex_leave,
104890  sqlite3_mutex_try,
104891#endif
104892  sqlite3_open_v2,
104893  sqlite3_release_memory,
104894  sqlite3_result_error_nomem,
104895  sqlite3_result_error_toobig,
104896  sqlite3_sleep,
104897  sqlite3_soft_heap_limit,
104898  sqlite3_vfs_find,
104899  sqlite3_vfs_register,
104900  sqlite3_vfs_unregister,
104901
104902  /*
104903  ** Added for 3.5.8
104904  */
104905  sqlite3_threadsafe,
104906  sqlite3_result_zeroblob,
104907  sqlite3_result_error_code,
104908  sqlite3_test_control,
104909  sqlite3_randomness,
104910  sqlite3_context_db_handle,
104911
104912  /*
104913  ** Added for 3.6.0
104914  */
104915  sqlite3_extended_result_codes,
104916  sqlite3_limit,
104917  sqlite3_next_stmt,
104918  sqlite3_sql,
104919  sqlite3_status,
104920
104921  /*
104922  ** Added for 3.7.4
104923  */
104924  sqlite3_backup_finish,
104925  sqlite3_backup_init,
104926  sqlite3_backup_pagecount,
104927  sqlite3_backup_remaining,
104928  sqlite3_backup_step,
104929#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
104930  sqlite3_compileoption_get,
104931  sqlite3_compileoption_used,
104932#else
104933  0,
104934  0,
104935#endif
104936  sqlite3_create_function_v2,
104937  sqlite3_db_config,
104938  sqlite3_db_mutex,
104939  sqlite3_db_status,
104940  sqlite3_extended_errcode,
104941  sqlite3_log,
104942  sqlite3_soft_heap_limit64,
104943  sqlite3_sourceid,
104944  sqlite3_stmt_status,
104945  sqlite3_strnicmp,
104946#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
104947  sqlite3_unlock_notify,
104948#else
104949  0,
104950#endif
104951#ifndef SQLITE_OMIT_WAL
104952  sqlite3_wal_autocheckpoint,
104953  sqlite3_wal_checkpoint,
104954  sqlite3_wal_hook,
104955#else
104956  0,
104957  0,
104958  0,
104959#endif
104960  sqlite3_blob_reopen,
104961  sqlite3_vtab_config,
104962  sqlite3_vtab_on_conflict,
104963  sqlite3_close_v2,
104964  sqlite3_db_filename,
104965  sqlite3_db_readonly,
104966  sqlite3_db_release_memory,
104967  sqlite3_errstr,
104968  sqlite3_stmt_busy,
104969  sqlite3_stmt_readonly,
104970  sqlite3_stricmp,
104971  sqlite3_uri_boolean,
104972  sqlite3_uri_int64,
104973  sqlite3_uri_parameter,
104974  sqlite3_vsnprintf,
104975  sqlite3_wal_checkpoint_v2,
104976  /* Version 3.8.7 and later */
104977  sqlite3_auto_extension,
104978  sqlite3_bind_blob64,
104979  sqlite3_bind_text64,
104980  sqlite3_cancel_auto_extension,
104981  sqlite3_load_extension,
104982  sqlite3_malloc64,
104983  sqlite3_msize,
104984  sqlite3_realloc64,
104985  sqlite3_reset_auto_extension,
104986  sqlite3_result_blob64,
104987  sqlite3_result_text64,
104988  sqlite3_strglob,
104989  /* Version 3.8.11 and later */
104990  (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
104991  sqlite3_value_free,
104992  sqlite3_result_zeroblob64,
104993  sqlite3_bind_zeroblob64,
104994  /* Version 3.9.0 and later */
104995  sqlite3_value_subtype,
104996  sqlite3_result_subtype
104997};
104998
104999/*
105000** Attempt to load an SQLite extension library contained in the file
105001** zFile.  The entry point is zProc.  zProc may be 0 in which case a
105002** default entry point name (sqlite3_extension_init) is used.  Use
105003** of the default name is recommended.
105004**
105005** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
105006**
105007** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
105008** error message text.  The calling function should free this memory
105009** by calling sqlite3DbFree(db, ).
105010*/
105011static int sqlite3LoadExtension(
105012  sqlite3 *db,          /* Load the extension into this database connection */
105013  const char *zFile,    /* Name of the shared library containing extension */
105014  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
105015  char **pzErrMsg       /* Put error message here if not 0 */
105016){
105017  sqlite3_vfs *pVfs = db->pVfs;
105018  void *handle;
105019  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
105020  char *zErrmsg = 0;
105021  const char *zEntry;
105022  char *zAltEntry = 0;
105023  void **aHandle;
105024  u64 nMsg = 300 + sqlite3Strlen30(zFile);
105025  int ii;
105026
105027  /* Shared library endings to try if zFile cannot be loaded as written */
105028  static const char *azEndings[] = {
105029#if SQLITE_OS_WIN
105030     "dll"
105031#elif defined(__APPLE__)
105032     "dylib"
105033#else
105034     "so"
105035#endif
105036  };
105037
105038
105039  if( pzErrMsg ) *pzErrMsg = 0;
105040
105041  /* Ticket #1863.  To avoid a creating security problems for older
105042  ** applications that relink against newer versions of SQLite, the
105043  ** ability to run load_extension is turned off by default.  One
105044  ** must call sqlite3_enable_load_extension() to turn on extension
105045  ** loading.  Otherwise you get the following error.
105046  */
105047  if( (db->flags & SQLITE_LoadExtension)==0 ){
105048    if( pzErrMsg ){
105049      *pzErrMsg = sqlite3_mprintf("not authorized");
105050    }
105051    return SQLITE_ERROR;
105052  }
105053
105054  zEntry = zProc ? zProc : "sqlite3_extension_init";
105055
105056  handle = sqlite3OsDlOpen(pVfs, zFile);
105057#if SQLITE_OS_UNIX || SQLITE_OS_WIN
105058  for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
105059    char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
105060    if( zAltFile==0 ) return SQLITE_NOMEM;
105061    handle = sqlite3OsDlOpen(pVfs, zAltFile);
105062    sqlite3_free(zAltFile);
105063  }
105064#endif
105065  if( handle==0 ){
105066    if( pzErrMsg ){
105067      *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
105068      if( zErrmsg ){
105069        sqlite3_snprintf(nMsg, zErrmsg,
105070            "unable to open shared library [%s]", zFile);
105071        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
105072      }
105073    }
105074    return SQLITE_ERROR;
105075  }
105076  xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
105077                   sqlite3OsDlSym(pVfs, handle, zEntry);
105078
105079  /* If no entry point was specified and the default legacy
105080  ** entry point name "sqlite3_extension_init" was not found, then
105081  ** construct an entry point name "sqlite3_X_init" where the X is
105082  ** replaced by the lowercase value of every ASCII alphabetic
105083  ** character in the filename after the last "/" upto the first ".",
105084  ** and eliding the first three characters if they are "lib".
105085  ** Examples:
105086  **
105087  **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init
105088  **    C:/lib/mathfuncs.dll              ==>  sqlite3_mathfuncs_init
105089  */
105090  if( xInit==0 && zProc==0 ){
105091    int iFile, iEntry, c;
105092    int ncFile = sqlite3Strlen30(zFile);
105093    zAltEntry = sqlite3_malloc64(ncFile+30);
105094    if( zAltEntry==0 ){
105095      sqlite3OsDlClose(pVfs, handle);
105096      return SQLITE_NOMEM;
105097    }
105098    memcpy(zAltEntry, "sqlite3_", 8);
105099    for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
105100    iFile++;
105101    if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
105102    for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
105103      if( sqlite3Isalpha(c) ){
105104        zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
105105      }
105106    }
105107    memcpy(zAltEntry+iEntry, "_init", 6);
105108    zEntry = zAltEntry;
105109    xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
105110                     sqlite3OsDlSym(pVfs, handle, zEntry);
105111  }
105112  if( xInit==0 ){
105113    if( pzErrMsg ){
105114      nMsg += sqlite3Strlen30(zEntry);
105115      *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
105116      if( zErrmsg ){
105117        sqlite3_snprintf(nMsg, zErrmsg,
105118            "no entry point [%s] in shared library [%s]", zEntry, zFile);
105119        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
105120      }
105121    }
105122    sqlite3OsDlClose(pVfs, handle);
105123    sqlite3_free(zAltEntry);
105124    return SQLITE_ERROR;
105125  }
105126  sqlite3_free(zAltEntry);
105127  if( xInit(db, &zErrmsg, &sqlite3Apis) ){
105128    if( pzErrMsg ){
105129      *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
105130    }
105131    sqlite3_free(zErrmsg);
105132    sqlite3OsDlClose(pVfs, handle);
105133    return SQLITE_ERROR;
105134  }
105135
105136  /* Append the new shared library handle to the db->aExtension array. */
105137  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
105138  if( aHandle==0 ){
105139    return SQLITE_NOMEM;
105140  }
105141  if( db->nExtension>0 ){
105142    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
105143  }
105144  sqlite3DbFree(db, db->aExtension);
105145  db->aExtension = aHandle;
105146
105147  db->aExtension[db->nExtension++] = handle;
105148  return SQLITE_OK;
105149}
105150SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
105151  sqlite3 *db,          /* Load the extension into this database connection */
105152  const char *zFile,    /* Name of the shared library containing extension */
105153  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
105154  char **pzErrMsg       /* Put error message here if not 0 */
105155){
105156  int rc;
105157  sqlite3_mutex_enter(db->mutex);
105158  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
105159  rc = sqlite3ApiExit(db, rc);
105160  sqlite3_mutex_leave(db->mutex);
105161  return rc;
105162}
105163
105164/*
105165** Call this routine when the database connection is closing in order
105166** to clean up loaded extensions
105167*/
105168SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
105169  int i;
105170  assert( sqlite3_mutex_held(db->mutex) );
105171  for(i=0; i<db->nExtension; i++){
105172    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
105173  }
105174  sqlite3DbFree(db, db->aExtension);
105175}
105176
105177/*
105178** Enable or disable extension loading.  Extension loading is disabled by
105179** default so as not to open security holes in older applications.
105180*/
105181SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff){
105182  sqlite3_mutex_enter(db->mutex);
105183  if( onoff ){
105184    db->flags |= SQLITE_LoadExtension;
105185  }else{
105186    db->flags &= ~SQLITE_LoadExtension;
105187  }
105188  sqlite3_mutex_leave(db->mutex);
105189  return SQLITE_OK;
105190}
105191
105192#endif /* SQLITE_OMIT_LOAD_EXTENSION */
105193
105194/*
105195** The auto-extension code added regardless of whether or not extension
105196** loading is supported.  We need a dummy sqlite3Apis pointer for that
105197** code if regular extension loading is not available.  This is that
105198** dummy pointer.
105199*/
105200#ifdef SQLITE_OMIT_LOAD_EXTENSION
105201static const sqlite3_api_routines sqlite3Apis;
105202#endif
105203
105204
105205/*
105206** The following object holds the list of automatically loaded
105207** extensions.
105208**
105209** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
105210** mutex must be held while accessing this list.
105211*/
105212typedef struct sqlite3AutoExtList sqlite3AutoExtList;
105213static SQLITE_WSD struct sqlite3AutoExtList {
105214  u32 nExt;              /* Number of entries in aExt[] */
105215  void (**aExt)(void);   /* Pointers to the extension init functions */
105216} sqlite3Autoext = { 0, 0 };
105217
105218/* The "wsdAutoext" macro will resolve to the autoextension
105219** state vector.  If writable static data is unsupported on the target,
105220** we have to locate the state vector at run-time.  In the more common
105221** case where writable static data is supported, wsdStat can refer directly
105222** to the "sqlite3Autoext" state vector declared above.
105223*/
105224#ifdef SQLITE_OMIT_WSD
105225# define wsdAutoextInit \
105226  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
105227# define wsdAutoext x[0]
105228#else
105229# define wsdAutoextInit
105230# define wsdAutoext sqlite3Autoext
105231#endif
105232
105233
105234/*
105235** Register a statically linked extension that is automatically
105236** loaded by every new database connection.
105237*/
105238SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void (*xInit)(void)){
105239  int rc = SQLITE_OK;
105240#ifndef SQLITE_OMIT_AUTOINIT
105241  rc = sqlite3_initialize();
105242  if( rc ){
105243    return rc;
105244  }else
105245#endif
105246  {
105247    u32 i;
105248#if SQLITE_THREADSAFE
105249    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
105250#endif
105251    wsdAutoextInit;
105252    sqlite3_mutex_enter(mutex);
105253    for(i=0; i<wsdAutoext.nExt; i++){
105254      if( wsdAutoext.aExt[i]==xInit ) break;
105255    }
105256    if( i==wsdAutoext.nExt ){
105257      u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
105258      void (**aNew)(void);
105259      aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
105260      if( aNew==0 ){
105261        rc = SQLITE_NOMEM;
105262      }else{
105263        wsdAutoext.aExt = aNew;
105264        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
105265        wsdAutoext.nExt++;
105266      }
105267    }
105268    sqlite3_mutex_leave(mutex);
105269    assert( (rc&0xff)==rc );
105270    return rc;
105271  }
105272}
105273
105274/*
105275** Cancel a prior call to sqlite3_auto_extension.  Remove xInit from the
105276** set of routines that is invoked for each new database connection, if it
105277** is currently on the list.  If xInit is not on the list, then this
105278** routine is a no-op.
105279**
105280** Return 1 if xInit was found on the list and removed.  Return 0 if xInit
105281** was not on the list.
105282*/
105283SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void (*xInit)(void)){
105284#if SQLITE_THREADSAFE
105285  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
105286#endif
105287  int i;
105288  int n = 0;
105289  wsdAutoextInit;
105290  sqlite3_mutex_enter(mutex);
105291  for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
105292    if( wsdAutoext.aExt[i]==xInit ){
105293      wsdAutoext.nExt--;
105294      wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
105295      n++;
105296      break;
105297    }
105298  }
105299  sqlite3_mutex_leave(mutex);
105300  return n;
105301}
105302
105303/*
105304** Reset the automatic extension loading mechanism.
105305*/
105306SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void){
105307#ifndef SQLITE_OMIT_AUTOINIT
105308  if( sqlite3_initialize()==SQLITE_OK )
105309#endif
105310  {
105311#if SQLITE_THREADSAFE
105312    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
105313#endif
105314    wsdAutoextInit;
105315    sqlite3_mutex_enter(mutex);
105316    sqlite3_free(wsdAutoext.aExt);
105317    wsdAutoext.aExt = 0;
105318    wsdAutoext.nExt = 0;
105319    sqlite3_mutex_leave(mutex);
105320  }
105321}
105322
105323/*
105324** Load all automatic extensions.
105325**
105326** If anything goes wrong, set an error in the database connection.
105327*/
105328SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
105329  u32 i;
105330  int go = 1;
105331  int rc;
105332  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
105333
105334  wsdAutoextInit;
105335  if( wsdAutoext.nExt==0 ){
105336    /* Common case: early out without every having to acquire a mutex */
105337    return;
105338  }
105339  for(i=0; go; i++){
105340    char *zErrmsg;
105341#if SQLITE_THREADSAFE
105342    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
105343#endif
105344    sqlite3_mutex_enter(mutex);
105345    if( i>=wsdAutoext.nExt ){
105346      xInit = 0;
105347      go = 0;
105348    }else{
105349      xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
105350              wsdAutoext.aExt[i];
105351    }
105352    sqlite3_mutex_leave(mutex);
105353    zErrmsg = 0;
105354    if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
105355      sqlite3ErrorWithMsg(db, rc,
105356            "automatic extension loading failed: %s", zErrmsg);
105357      go = 0;
105358    }
105359    sqlite3_free(zErrmsg);
105360  }
105361}
105362
105363/************** End of loadext.c *********************************************/
105364/************** Begin file pragma.c ******************************************/
105365/*
105366** 2003 April 6
105367**
105368** The author disclaims copyright to this source code.  In place of
105369** a legal notice, here is a blessing:
105370**
105371**    May you do good and not evil.
105372**    May you find forgiveness for yourself and forgive others.
105373**    May you share freely, never taking more than you give.
105374**
105375*************************************************************************
105376** This file contains code used to implement the PRAGMA command.
105377*/
105378/* #include "sqliteInt.h" */
105379
105380#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
105381#  if defined(__APPLE__)
105382#    define SQLITE_ENABLE_LOCKING_STYLE 1
105383#  else
105384#    define SQLITE_ENABLE_LOCKING_STYLE 0
105385#  endif
105386#endif
105387
105388/***************************************************************************
105389** The "pragma.h" include file is an automatically generated file that
105390** that includes the PragType_XXXX macro definitions and the aPragmaName[]
105391** object.  This ensures that the aPragmaName[] table is arranged in
105392** lexicographical order to facility a binary search of the pragma name.
105393** Do not edit pragma.h directly.  Edit and rerun the script in at
105394** ../tool/mkpragmatab.tcl. */
105395/************** Include pragma.h in the middle of pragma.c *******************/
105396/************** Begin file pragma.h ******************************************/
105397/* DO NOT EDIT!
105398** This file is automatically generated by the script at
105399** ../tool/mkpragmatab.tcl.  To update the set of pragmas, edit
105400** that script and rerun it.
105401*/
105402#define PragTyp_HEADER_VALUE                   0
105403#define PragTyp_AUTO_VACUUM                    1
105404#define PragTyp_FLAG                           2
105405#define PragTyp_BUSY_TIMEOUT                   3
105406#define PragTyp_CACHE_SIZE                     4
105407#define PragTyp_CASE_SENSITIVE_LIKE            5
105408#define PragTyp_COLLATION_LIST                 6
105409#define PragTyp_COMPILE_OPTIONS                7
105410#define PragTyp_DATA_STORE_DIRECTORY           8
105411#define PragTyp_DATABASE_LIST                  9
105412#define PragTyp_DEFAULT_CACHE_SIZE            10
105413#define PragTyp_ENCODING                      11
105414#define PragTyp_FOREIGN_KEY_CHECK             12
105415#define PragTyp_FOREIGN_KEY_LIST              13
105416#define PragTyp_INCREMENTAL_VACUUM            14
105417#define PragTyp_INDEX_INFO                    15
105418#define PragTyp_INDEX_LIST                    16
105419#define PragTyp_INTEGRITY_CHECK               17
105420#define PragTyp_JOURNAL_MODE                  18
105421#define PragTyp_JOURNAL_SIZE_LIMIT            19
105422#define PragTyp_LOCK_PROXY_FILE               20
105423#define PragTyp_LOCKING_MODE                  21
105424#define PragTyp_PAGE_COUNT                    22
105425#define PragTyp_MMAP_SIZE                     23
105426#define PragTyp_PAGE_SIZE                     24
105427#define PragTyp_SECURE_DELETE                 25
105428#define PragTyp_SHRINK_MEMORY                 26
105429#define PragTyp_SOFT_HEAP_LIMIT               27
105430#define PragTyp_STATS                         28
105431#define PragTyp_SYNCHRONOUS                   29
105432#define PragTyp_TABLE_INFO                    30
105433#define PragTyp_TEMP_STORE                    31
105434#define PragTyp_TEMP_STORE_DIRECTORY          32
105435#define PragTyp_THREADS                       33
105436#define PragTyp_WAL_AUTOCHECKPOINT            34
105437#define PragTyp_WAL_CHECKPOINT                35
105438#define PragTyp_ACTIVATE_EXTENSIONS           36
105439#define PragTyp_HEXKEY                        37
105440#define PragTyp_KEY                           38
105441#define PragTyp_REKEY                         39
105442#define PragTyp_LOCK_STATUS                   40
105443#define PragTyp_PARSER_TRACE                  41
105444#define PragFlag_NeedSchema           0x01
105445#define PragFlag_ReadOnly             0x02
105446static const struct sPragmaNames {
105447  const char *const zName;  /* Name of pragma */
105448  u8 ePragTyp;              /* PragTyp_XXX value */
105449  u8 mPragFlag;             /* Zero or more PragFlag_XXX values */
105450  u32 iArg;                 /* Extra argument */
105451} aPragmaNames[] = {
105452#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
105453  { /* zName:     */ "activate_extensions",
105454    /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,
105455    /* ePragFlag: */ 0,
105456    /* iArg:      */ 0 },
105457#endif
105458#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
105459  { /* zName:     */ "application_id",
105460    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
105461    /* ePragFlag: */ 0,
105462    /* iArg:      */ BTREE_APPLICATION_ID },
105463#endif
105464#if !defined(SQLITE_OMIT_AUTOVACUUM)
105465  { /* zName:     */ "auto_vacuum",
105466    /* ePragTyp:  */ PragTyp_AUTO_VACUUM,
105467    /* ePragFlag: */ PragFlag_NeedSchema,
105468    /* iArg:      */ 0 },
105469#endif
105470#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105471#if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
105472  { /* zName:     */ "automatic_index",
105473    /* ePragTyp:  */ PragTyp_FLAG,
105474    /* ePragFlag: */ 0,
105475    /* iArg:      */ SQLITE_AutoIndex },
105476#endif
105477#endif
105478  { /* zName:     */ "busy_timeout",
105479    /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
105480    /* ePragFlag: */ 0,
105481    /* iArg:      */ 0 },
105482#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
105483  { /* zName:     */ "cache_size",
105484    /* ePragTyp:  */ PragTyp_CACHE_SIZE,
105485    /* ePragFlag: */ 0,
105486    /* iArg:      */ 0 },
105487#endif
105488#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105489  { /* zName:     */ "cache_spill",
105490    /* ePragTyp:  */ PragTyp_FLAG,
105491    /* ePragFlag: */ 0,
105492    /* iArg:      */ SQLITE_CacheSpill },
105493#endif
105494  { /* zName:     */ "case_sensitive_like",
105495    /* ePragTyp:  */ PragTyp_CASE_SENSITIVE_LIKE,
105496    /* ePragFlag: */ 0,
105497    /* iArg:      */ 0 },
105498  { /* zName:     */ "cell_size_check",
105499    /* ePragTyp:  */ PragTyp_FLAG,
105500    /* ePragFlag: */ 0,
105501    /* iArg:      */ SQLITE_CellSizeCk },
105502#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105503  { /* zName:     */ "checkpoint_fullfsync",
105504    /* ePragTyp:  */ PragTyp_FLAG,
105505    /* ePragFlag: */ 0,
105506    /* iArg:      */ SQLITE_CkptFullFSync },
105507#endif
105508#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
105509  { /* zName:     */ "collation_list",
105510    /* ePragTyp:  */ PragTyp_COLLATION_LIST,
105511    /* ePragFlag: */ 0,
105512    /* iArg:      */ 0 },
105513#endif
105514#if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
105515  { /* zName:     */ "compile_options",
105516    /* ePragTyp:  */ PragTyp_COMPILE_OPTIONS,
105517    /* ePragFlag: */ 0,
105518    /* iArg:      */ 0 },
105519#endif
105520#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105521  { /* zName:     */ "count_changes",
105522    /* ePragTyp:  */ PragTyp_FLAG,
105523    /* ePragFlag: */ 0,
105524    /* iArg:      */ SQLITE_CountRows },
105525#endif
105526#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
105527  { /* zName:     */ "data_store_directory",
105528    /* ePragTyp:  */ PragTyp_DATA_STORE_DIRECTORY,
105529    /* ePragFlag: */ 0,
105530    /* iArg:      */ 0 },
105531#endif
105532#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
105533  { /* zName:     */ "data_version",
105534    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
105535    /* ePragFlag: */ PragFlag_ReadOnly,
105536    /* iArg:      */ BTREE_DATA_VERSION },
105537#endif
105538#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
105539  { /* zName:     */ "database_list",
105540    /* ePragTyp:  */ PragTyp_DATABASE_LIST,
105541    /* ePragFlag: */ PragFlag_NeedSchema,
105542    /* iArg:      */ 0 },
105543#endif
105544#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
105545  { /* zName:     */ "default_cache_size",
105546    /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
105547    /* ePragFlag: */ PragFlag_NeedSchema,
105548    /* iArg:      */ 0 },
105549#endif
105550#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105551#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
105552  { /* zName:     */ "defer_foreign_keys",
105553    /* ePragTyp:  */ PragTyp_FLAG,
105554    /* ePragFlag: */ 0,
105555    /* iArg:      */ SQLITE_DeferFKs },
105556#endif
105557#endif
105558#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105559  { /* zName:     */ "empty_result_callbacks",
105560    /* ePragTyp:  */ PragTyp_FLAG,
105561    /* ePragFlag: */ 0,
105562    /* iArg:      */ SQLITE_NullCallback },
105563#endif
105564#if !defined(SQLITE_OMIT_UTF16)
105565  { /* zName:     */ "encoding",
105566    /* ePragTyp:  */ PragTyp_ENCODING,
105567    /* ePragFlag: */ 0,
105568    /* iArg:      */ 0 },
105569#endif
105570#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
105571  { /* zName:     */ "foreign_key_check",
105572    /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
105573    /* ePragFlag: */ PragFlag_NeedSchema,
105574    /* iArg:      */ 0 },
105575#endif
105576#if !defined(SQLITE_OMIT_FOREIGN_KEY)
105577  { /* zName:     */ "foreign_key_list",
105578    /* ePragTyp:  */ PragTyp_FOREIGN_KEY_LIST,
105579    /* ePragFlag: */ PragFlag_NeedSchema,
105580    /* iArg:      */ 0 },
105581#endif
105582#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105583#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
105584  { /* zName:     */ "foreign_keys",
105585    /* ePragTyp:  */ PragTyp_FLAG,
105586    /* ePragFlag: */ 0,
105587    /* iArg:      */ SQLITE_ForeignKeys },
105588#endif
105589#endif
105590#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
105591  { /* zName:     */ "freelist_count",
105592    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
105593    /* ePragFlag: */ PragFlag_ReadOnly,
105594    /* iArg:      */ BTREE_FREE_PAGE_COUNT },
105595#endif
105596#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105597  { /* zName:     */ "full_column_names",
105598    /* ePragTyp:  */ PragTyp_FLAG,
105599    /* ePragFlag: */ 0,
105600    /* iArg:      */ SQLITE_FullColNames },
105601  { /* zName:     */ "fullfsync",
105602    /* ePragTyp:  */ PragTyp_FLAG,
105603    /* ePragFlag: */ 0,
105604    /* iArg:      */ SQLITE_FullFSync },
105605#endif
105606#if defined(SQLITE_HAS_CODEC)
105607  { /* zName:     */ "hexkey",
105608    /* ePragTyp:  */ PragTyp_HEXKEY,
105609    /* ePragFlag: */ 0,
105610    /* iArg:      */ 0 },
105611  { /* zName:     */ "hexrekey",
105612    /* ePragTyp:  */ PragTyp_HEXKEY,
105613    /* ePragFlag: */ 0,
105614    /* iArg:      */ 0 },
105615#endif
105616#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105617#if !defined(SQLITE_OMIT_CHECK)
105618  { /* zName:     */ "ignore_check_constraints",
105619    /* ePragTyp:  */ PragTyp_FLAG,
105620    /* ePragFlag: */ 0,
105621    /* iArg:      */ SQLITE_IgnoreChecks },
105622#endif
105623#endif
105624#if !defined(SQLITE_OMIT_AUTOVACUUM)
105625  { /* zName:     */ "incremental_vacuum",
105626    /* ePragTyp:  */ PragTyp_INCREMENTAL_VACUUM,
105627    /* ePragFlag: */ PragFlag_NeedSchema,
105628    /* iArg:      */ 0 },
105629#endif
105630#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
105631  { /* zName:     */ "index_info",
105632    /* ePragTyp:  */ PragTyp_INDEX_INFO,
105633    /* ePragFlag: */ PragFlag_NeedSchema,
105634    /* iArg:      */ 0 },
105635  { /* zName:     */ "index_list",
105636    /* ePragTyp:  */ PragTyp_INDEX_LIST,
105637    /* ePragFlag: */ PragFlag_NeedSchema,
105638    /* iArg:      */ 0 },
105639  { /* zName:     */ "index_xinfo",
105640    /* ePragTyp:  */ PragTyp_INDEX_INFO,
105641    /* ePragFlag: */ PragFlag_NeedSchema,
105642    /* iArg:      */ 1 },
105643#endif
105644#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
105645  { /* zName:     */ "integrity_check",
105646    /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
105647    /* ePragFlag: */ PragFlag_NeedSchema,
105648    /* iArg:      */ 0 },
105649#endif
105650#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
105651  { /* zName:     */ "journal_mode",
105652    /* ePragTyp:  */ PragTyp_JOURNAL_MODE,
105653    /* ePragFlag: */ PragFlag_NeedSchema,
105654    /* iArg:      */ 0 },
105655  { /* zName:     */ "journal_size_limit",
105656    /* ePragTyp:  */ PragTyp_JOURNAL_SIZE_LIMIT,
105657    /* ePragFlag: */ 0,
105658    /* iArg:      */ 0 },
105659#endif
105660#if defined(SQLITE_HAS_CODEC)
105661  { /* zName:     */ "key",
105662    /* ePragTyp:  */ PragTyp_KEY,
105663    /* ePragFlag: */ 0,
105664    /* iArg:      */ 0 },
105665#endif
105666#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105667  { /* zName:     */ "legacy_file_format",
105668    /* ePragTyp:  */ PragTyp_FLAG,
105669    /* ePragFlag: */ 0,
105670    /* iArg:      */ SQLITE_LegacyFileFmt },
105671#endif
105672#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
105673  { /* zName:     */ "lock_proxy_file",
105674    /* ePragTyp:  */ PragTyp_LOCK_PROXY_FILE,
105675    /* ePragFlag: */ 0,
105676    /* iArg:      */ 0 },
105677#endif
105678#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
105679  { /* zName:     */ "lock_status",
105680    /* ePragTyp:  */ PragTyp_LOCK_STATUS,
105681    /* ePragFlag: */ 0,
105682    /* iArg:      */ 0 },
105683#endif
105684#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
105685  { /* zName:     */ "locking_mode",
105686    /* ePragTyp:  */ PragTyp_LOCKING_MODE,
105687    /* ePragFlag: */ 0,
105688    /* iArg:      */ 0 },
105689  { /* zName:     */ "max_page_count",
105690    /* ePragTyp:  */ PragTyp_PAGE_COUNT,
105691    /* ePragFlag: */ PragFlag_NeedSchema,
105692    /* iArg:      */ 0 },
105693  { /* zName:     */ "mmap_size",
105694    /* ePragTyp:  */ PragTyp_MMAP_SIZE,
105695    /* ePragFlag: */ 0,
105696    /* iArg:      */ 0 },
105697  { /* zName:     */ "page_count",
105698    /* ePragTyp:  */ PragTyp_PAGE_COUNT,
105699    /* ePragFlag: */ PragFlag_NeedSchema,
105700    /* iArg:      */ 0 },
105701  { /* zName:     */ "page_size",
105702    /* ePragTyp:  */ PragTyp_PAGE_SIZE,
105703    /* ePragFlag: */ 0,
105704    /* iArg:      */ 0 },
105705#endif
105706#if defined(SQLITE_DEBUG)
105707  { /* zName:     */ "parser_trace",
105708    /* ePragTyp:  */ PragTyp_PARSER_TRACE,
105709    /* ePragFlag: */ 0,
105710    /* iArg:      */ 0 },
105711#endif
105712#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105713  { /* zName:     */ "query_only",
105714    /* ePragTyp:  */ PragTyp_FLAG,
105715    /* ePragFlag: */ 0,
105716    /* iArg:      */ SQLITE_QueryOnly },
105717#endif
105718#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
105719  { /* zName:     */ "quick_check",
105720    /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
105721    /* ePragFlag: */ PragFlag_NeedSchema,
105722    /* iArg:      */ 0 },
105723#endif
105724#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105725  { /* zName:     */ "read_uncommitted",
105726    /* ePragTyp:  */ PragTyp_FLAG,
105727    /* ePragFlag: */ 0,
105728    /* iArg:      */ SQLITE_ReadUncommitted },
105729  { /* zName:     */ "recursive_triggers",
105730    /* ePragTyp:  */ PragTyp_FLAG,
105731    /* ePragFlag: */ 0,
105732    /* iArg:      */ SQLITE_RecTriggers },
105733#endif
105734#if defined(SQLITE_HAS_CODEC)
105735  { /* zName:     */ "rekey",
105736    /* ePragTyp:  */ PragTyp_REKEY,
105737    /* ePragFlag: */ 0,
105738    /* iArg:      */ 0 },
105739#endif
105740#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105741  { /* zName:     */ "reverse_unordered_selects",
105742    /* ePragTyp:  */ PragTyp_FLAG,
105743    /* ePragFlag: */ 0,
105744    /* iArg:      */ SQLITE_ReverseOrder },
105745#endif
105746#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
105747  { /* zName:     */ "schema_version",
105748    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
105749    /* ePragFlag: */ 0,
105750    /* iArg:      */ BTREE_SCHEMA_VERSION },
105751#endif
105752#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
105753  { /* zName:     */ "secure_delete",
105754    /* ePragTyp:  */ PragTyp_SECURE_DELETE,
105755    /* ePragFlag: */ 0,
105756    /* iArg:      */ 0 },
105757#endif
105758#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105759  { /* zName:     */ "short_column_names",
105760    /* ePragTyp:  */ PragTyp_FLAG,
105761    /* ePragFlag: */ 0,
105762    /* iArg:      */ SQLITE_ShortColNames },
105763#endif
105764  { /* zName:     */ "shrink_memory",
105765    /* ePragTyp:  */ PragTyp_SHRINK_MEMORY,
105766    /* ePragFlag: */ 0,
105767    /* iArg:      */ 0 },
105768  { /* zName:     */ "soft_heap_limit",
105769    /* ePragTyp:  */ PragTyp_SOFT_HEAP_LIMIT,
105770    /* ePragFlag: */ 0,
105771    /* iArg:      */ 0 },
105772#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105773#if defined(SQLITE_DEBUG)
105774  { /* zName:     */ "sql_trace",
105775    /* ePragTyp:  */ PragTyp_FLAG,
105776    /* ePragFlag: */ 0,
105777    /* iArg:      */ SQLITE_SqlTrace },
105778#endif
105779#endif
105780#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
105781  { /* zName:     */ "stats",
105782    /* ePragTyp:  */ PragTyp_STATS,
105783    /* ePragFlag: */ PragFlag_NeedSchema,
105784    /* iArg:      */ 0 },
105785#endif
105786#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
105787  { /* zName:     */ "synchronous",
105788    /* ePragTyp:  */ PragTyp_SYNCHRONOUS,
105789    /* ePragFlag: */ PragFlag_NeedSchema,
105790    /* iArg:      */ 0 },
105791#endif
105792#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
105793  { /* zName:     */ "table_info",
105794    /* ePragTyp:  */ PragTyp_TABLE_INFO,
105795    /* ePragFlag: */ PragFlag_NeedSchema,
105796    /* iArg:      */ 0 },
105797#endif
105798#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
105799  { /* zName:     */ "temp_store",
105800    /* ePragTyp:  */ PragTyp_TEMP_STORE,
105801    /* ePragFlag: */ 0,
105802    /* iArg:      */ 0 },
105803  { /* zName:     */ "temp_store_directory",
105804    /* ePragTyp:  */ PragTyp_TEMP_STORE_DIRECTORY,
105805    /* ePragFlag: */ 0,
105806    /* iArg:      */ 0 },
105807#endif
105808  { /* zName:     */ "threads",
105809    /* ePragTyp:  */ PragTyp_THREADS,
105810    /* ePragFlag: */ 0,
105811    /* iArg:      */ 0 },
105812#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
105813  { /* zName:     */ "user_version",
105814    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
105815    /* ePragFlag: */ 0,
105816    /* iArg:      */ BTREE_USER_VERSION },
105817#endif
105818#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105819#if defined(SQLITE_DEBUG)
105820  { /* zName:     */ "vdbe_addoptrace",
105821    /* ePragTyp:  */ PragTyp_FLAG,
105822    /* ePragFlag: */ 0,
105823    /* iArg:      */ SQLITE_VdbeAddopTrace },
105824  { /* zName:     */ "vdbe_debug",
105825    /* ePragTyp:  */ PragTyp_FLAG,
105826    /* ePragFlag: */ 0,
105827    /* iArg:      */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
105828  { /* zName:     */ "vdbe_eqp",
105829    /* ePragTyp:  */ PragTyp_FLAG,
105830    /* ePragFlag: */ 0,
105831    /* iArg:      */ SQLITE_VdbeEQP },
105832  { /* zName:     */ "vdbe_listing",
105833    /* ePragTyp:  */ PragTyp_FLAG,
105834    /* ePragFlag: */ 0,
105835    /* iArg:      */ SQLITE_VdbeListing },
105836  { /* zName:     */ "vdbe_trace",
105837    /* ePragTyp:  */ PragTyp_FLAG,
105838    /* ePragFlag: */ 0,
105839    /* iArg:      */ SQLITE_VdbeTrace },
105840#endif
105841#endif
105842#if !defined(SQLITE_OMIT_WAL)
105843  { /* zName:     */ "wal_autocheckpoint",
105844    /* ePragTyp:  */ PragTyp_WAL_AUTOCHECKPOINT,
105845    /* ePragFlag: */ 0,
105846    /* iArg:      */ 0 },
105847  { /* zName:     */ "wal_checkpoint",
105848    /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
105849    /* ePragFlag: */ PragFlag_NeedSchema,
105850    /* iArg:      */ 0 },
105851#endif
105852#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
105853  { /* zName:     */ "writable_schema",
105854    /* ePragTyp:  */ PragTyp_FLAG,
105855    /* ePragFlag: */ 0,
105856    /* iArg:      */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
105857#endif
105858};
105859/* Number of pragmas: 60 on by default, 73 total. */
105860
105861/************** End of pragma.h **********************************************/
105862/************** Continuing where we left off in pragma.c *********************/
105863
105864/*
105865** Interpret the given string as a safety level.  Return 0 for OFF,
105866** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
105867** unrecognized string argument.  The FULL option is disallowed
105868** if the omitFull parameter it 1.
105869**
105870** Note that the values returned are one less that the values that
105871** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
105872** to support legacy SQL code.  The safety level used to be boolean
105873** and older scripts may have used numbers 0 for OFF and 1 for ON.
105874*/
105875static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
105876                             /* 123456789 123456789 */
105877  static const char zText[] = "onoffalseyestruefull";
105878  static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
105879  static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
105880  static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
105881  int i, n;
105882  if( sqlite3Isdigit(*z) ){
105883    return (u8)sqlite3Atoi(z);
105884  }
105885  n = sqlite3Strlen30(z);
105886  for(i=0; i<ArraySize(iLength)-omitFull; i++){
105887    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
105888      return iValue[i];
105889    }
105890  }
105891  return dflt;
105892}
105893
105894/*
105895** Interpret the given string as a boolean value.
105896*/
105897SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
105898  return getSafetyLevel(z,1,dflt)!=0;
105899}
105900
105901/* The sqlite3GetBoolean() function is used by other modules but the
105902** remainder of this file is specific to PRAGMA processing.  So omit
105903** the rest of the file if PRAGMAs are omitted from the build.
105904*/
105905#if !defined(SQLITE_OMIT_PRAGMA)
105906
105907/*
105908** Interpret the given string as a locking mode value.
105909*/
105910static int getLockingMode(const char *z){
105911  if( z ){
105912    if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
105913    if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
105914  }
105915  return PAGER_LOCKINGMODE_QUERY;
105916}
105917
105918#ifndef SQLITE_OMIT_AUTOVACUUM
105919/*
105920** Interpret the given string as an auto-vacuum mode value.
105921**
105922** The following strings, "none", "full" and "incremental" are
105923** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
105924*/
105925static int getAutoVacuum(const char *z){
105926  int i;
105927  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
105928  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
105929  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
105930  i = sqlite3Atoi(z);
105931  return (u8)((i>=0&&i<=2)?i:0);
105932}
105933#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
105934
105935#ifndef SQLITE_OMIT_PAGER_PRAGMAS
105936/*
105937** Interpret the given string as a temp db location. Return 1 for file
105938** backed temporary databases, 2 for the Red-Black tree in memory database
105939** and 0 to use the compile-time default.
105940*/
105941static int getTempStore(const char *z){
105942  if( z[0]>='0' && z[0]<='2' ){
105943    return z[0] - '0';
105944  }else if( sqlite3StrICmp(z, "file")==0 ){
105945    return 1;
105946  }else if( sqlite3StrICmp(z, "memory")==0 ){
105947    return 2;
105948  }else{
105949    return 0;
105950  }
105951}
105952#endif /* SQLITE_PAGER_PRAGMAS */
105953
105954#ifndef SQLITE_OMIT_PAGER_PRAGMAS
105955/*
105956** Invalidate temp storage, either when the temp storage is changed
105957** from default, or when 'file' and the temp_store_directory has changed
105958*/
105959static int invalidateTempStorage(Parse *pParse){
105960  sqlite3 *db = pParse->db;
105961  if( db->aDb[1].pBt!=0 ){
105962    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
105963      sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
105964        "from within a transaction");
105965      return SQLITE_ERROR;
105966    }
105967    sqlite3BtreeClose(db->aDb[1].pBt);
105968    db->aDb[1].pBt = 0;
105969    sqlite3ResetAllSchemasOfConnection(db);
105970  }
105971  return SQLITE_OK;
105972}
105973#endif /* SQLITE_PAGER_PRAGMAS */
105974
105975#ifndef SQLITE_OMIT_PAGER_PRAGMAS
105976/*
105977** If the TEMP database is open, close it and mark the database schema
105978** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
105979** or DEFAULT_TEMP_STORE pragmas.
105980*/
105981static int changeTempStorage(Parse *pParse, const char *zStorageType){
105982  int ts = getTempStore(zStorageType);
105983  sqlite3 *db = pParse->db;
105984  if( db->temp_store==ts ) return SQLITE_OK;
105985  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
105986    return SQLITE_ERROR;
105987  }
105988  db->temp_store = (u8)ts;
105989  return SQLITE_OK;
105990}
105991#endif /* SQLITE_PAGER_PRAGMAS */
105992
105993/*
105994** Set the names of the first N columns to the values in azCol[]
105995*/
105996static void setAllColumnNames(
105997  Vdbe *v,               /* The query under construction */
105998  int N,                 /* Number of columns */
105999  const char **azCol     /* Names of columns */
106000){
106001  int i;
106002  sqlite3VdbeSetNumCols(v, N);
106003  for(i=0; i<N; i++){
106004    sqlite3VdbeSetColName(v, i, COLNAME_NAME, azCol[i], SQLITE_STATIC);
106005  }
106006}
106007static void setOneColumnName(Vdbe *v, const char *z){
106008  setAllColumnNames(v, 1, &z);
106009}
106010
106011/*
106012** Generate code to return a single integer value.
106013*/
106014static void returnSingleInt(Vdbe *v, const char *zLabel, i64 value){
106015  sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
106016  setOneColumnName(v, zLabel);
106017  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
106018}
106019
106020/*
106021** Generate code to return a single text value.
106022*/
106023static void returnSingleText(
106024  Vdbe *v,                /* Prepared statement under construction */
106025  const char *zLabel,     /* Name of the result column */
106026  const char *zValue      /* Value to be returned */
106027){
106028  if( zValue ){
106029    sqlite3VdbeLoadString(v, 1, (const char*)zValue);
106030    setOneColumnName(v, zLabel);
106031    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
106032  }
106033}
106034
106035
106036/*
106037** Set the safety_level and pager flags for pager iDb.  Or if iDb<0
106038** set these values for all pagers.
106039*/
106040#ifndef SQLITE_OMIT_PAGER_PRAGMAS
106041static void setAllPagerFlags(sqlite3 *db){
106042  if( db->autoCommit ){
106043    Db *pDb = db->aDb;
106044    int n = db->nDb;
106045    assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
106046    assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
106047    assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
106048    assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
106049             ==  PAGER_FLAGS_MASK );
106050    assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
106051    while( (n--) > 0 ){
106052      if( pDb->pBt ){
106053        sqlite3BtreeSetPagerFlags(pDb->pBt,
106054                 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
106055      }
106056      pDb++;
106057    }
106058  }
106059}
106060#else
106061# define setAllPagerFlags(X)  /* no-op */
106062#endif
106063
106064
106065/*
106066** Return a human-readable name for a constraint resolution action.
106067*/
106068#ifndef SQLITE_OMIT_FOREIGN_KEY
106069static const char *actionName(u8 action){
106070  const char *zName;
106071  switch( action ){
106072    case OE_SetNull:  zName = "SET NULL";        break;
106073    case OE_SetDflt:  zName = "SET DEFAULT";     break;
106074    case OE_Cascade:  zName = "CASCADE";         break;
106075    case OE_Restrict: zName = "RESTRICT";        break;
106076    default:          zName = "NO ACTION";
106077                      assert( action==OE_None ); break;
106078  }
106079  return zName;
106080}
106081#endif
106082
106083
106084/*
106085** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
106086** defined in pager.h. This function returns the associated lowercase
106087** journal-mode name.
106088*/
106089SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
106090  static char * const azModeName[] = {
106091    "delete", "persist", "off", "truncate", "memory"
106092#ifndef SQLITE_OMIT_WAL
106093     , "wal"
106094#endif
106095  };
106096  assert( PAGER_JOURNALMODE_DELETE==0 );
106097  assert( PAGER_JOURNALMODE_PERSIST==1 );
106098  assert( PAGER_JOURNALMODE_OFF==2 );
106099  assert( PAGER_JOURNALMODE_TRUNCATE==3 );
106100  assert( PAGER_JOURNALMODE_MEMORY==4 );
106101  assert( PAGER_JOURNALMODE_WAL==5 );
106102  assert( eMode>=0 && eMode<=ArraySize(azModeName) );
106103
106104  if( eMode==ArraySize(azModeName) ) return 0;
106105  return azModeName[eMode];
106106}
106107
106108/*
106109** Process a pragma statement.
106110**
106111** Pragmas are of this form:
106112**
106113**      PRAGMA [database.]id [= value]
106114**
106115** The identifier might also be a string.  The value is a string, and
106116** identifier, or a number.  If minusFlag is true, then the value is
106117** a number that was preceded by a minus sign.
106118**
106119** If the left side is "database.id" then pId1 is the database name
106120** and pId2 is the id.  If the left side is just "id" then pId1 is the
106121** id and pId2 is any empty string.
106122*/
106123SQLITE_PRIVATE void sqlite3Pragma(
106124  Parse *pParse,
106125  Token *pId1,        /* First part of [database.]id field */
106126  Token *pId2,        /* Second part of [database.]id field, or NULL */
106127  Token *pValue,      /* Token for <value>, or NULL */
106128  int minusFlag       /* True if a '-' sign preceded <value> */
106129){
106130  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
106131  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
106132  const char *zDb = 0;   /* The database name */
106133  Token *pId;            /* Pointer to <id> token */
106134  char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
106135  int iDb;               /* Database index for <database> */
106136  int lwr, upr, mid = 0;       /* Binary search bounds */
106137  int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
106138  sqlite3 *db = pParse->db;    /* The database connection */
106139  Db *pDb;                     /* The specific database being pragmaed */
106140  Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
106141  const struct sPragmaNames *pPragma;
106142
106143  if( v==0 ) return;
106144  sqlite3VdbeRunOnlyOnce(v);
106145  pParse->nMem = 2;
106146
106147  /* Interpret the [database.] part of the pragma statement. iDb is the
106148  ** index of the database this pragma is being applied to in db.aDb[]. */
106149  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
106150  if( iDb<0 ) return;
106151  pDb = &db->aDb[iDb];
106152
106153  /* If the temp database has been explicitly named as part of the
106154  ** pragma, make sure it is open.
106155  */
106156  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
106157    return;
106158  }
106159
106160  zLeft = sqlite3NameFromToken(db, pId);
106161  if( !zLeft ) return;
106162  if( minusFlag ){
106163    zRight = sqlite3MPrintf(db, "-%T", pValue);
106164  }else{
106165    zRight = sqlite3NameFromToken(db, pValue);
106166  }
106167
106168  assert( pId2 );
106169  zDb = pId2->n>0 ? pDb->zName : 0;
106170  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
106171    goto pragma_out;
106172  }
106173
106174  /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
106175  ** connection.  If it returns SQLITE_OK, then assume that the VFS
106176  ** handled the pragma and generate a no-op prepared statement.
106177  **
106178  ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
106179  ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
106180  ** object corresponding to the database file to which the pragma
106181  ** statement refers.
106182  **
106183  ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
106184  ** file control is an array of pointers to strings (char**) in which the
106185  ** second element of the array is the name of the pragma and the third
106186  ** element is the argument to the pragma or NULL if the pragma has no
106187  ** argument.
106188  */
106189  aFcntl[0] = 0;
106190  aFcntl[1] = zLeft;
106191  aFcntl[2] = zRight;
106192  aFcntl[3] = 0;
106193  db->busyHandler.nBusy = 0;
106194  rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
106195  if( rc==SQLITE_OK ){
106196    returnSingleText(v, "result", aFcntl[0]);
106197    sqlite3_free(aFcntl[0]);
106198    goto pragma_out;
106199  }
106200  if( rc!=SQLITE_NOTFOUND ){
106201    if( aFcntl[0] ){
106202      sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
106203      sqlite3_free(aFcntl[0]);
106204    }
106205    pParse->nErr++;
106206    pParse->rc = rc;
106207    goto pragma_out;
106208  }
106209
106210  /* Locate the pragma in the lookup table */
106211  lwr = 0;
106212  upr = ArraySize(aPragmaNames)-1;
106213  while( lwr<=upr ){
106214    mid = (lwr+upr)/2;
106215    rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
106216    if( rc==0 ) break;
106217    if( rc<0 ){
106218      upr = mid - 1;
106219    }else{
106220      lwr = mid + 1;
106221    }
106222  }
106223  if( lwr>upr ) goto pragma_out;
106224  pPragma = &aPragmaNames[mid];
106225
106226  /* Make sure the database schema is loaded if the pragma requires that */
106227  if( (pPragma->mPragFlag & PragFlag_NeedSchema)!=0 ){
106228    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
106229  }
106230
106231  /* Jump to the appropriate pragma handler */
106232  switch( pPragma->ePragTyp ){
106233
106234#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
106235  /*
106236  **  PRAGMA [database.]default_cache_size
106237  **  PRAGMA [database.]default_cache_size=N
106238  **
106239  ** The first form reports the current persistent setting for the
106240  ** page cache size.  The value returned is the maximum number of
106241  ** pages in the page cache.  The second form sets both the current
106242  ** page cache size value and the persistent page cache size value
106243  ** stored in the database file.
106244  **
106245  ** Older versions of SQLite would set the default cache size to a
106246  ** negative number to indicate synchronous=OFF.  These days, synchronous
106247  ** is always on by default regardless of the sign of the default cache
106248  ** size.  But continue to take the absolute value of the default cache
106249  ** size of historical compatibility.
106250  */
106251  case PragTyp_DEFAULT_CACHE_SIZE: {
106252    static const int iLn = VDBE_OFFSET_LINENO(2);
106253    static const VdbeOpList getCacheSize[] = {
106254      { OP_Transaction, 0, 0,        0},                         /* 0 */
106255      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
106256      { OP_IfPos,       1, 8,        0},
106257      { OP_Integer,     0, 2,        0},
106258      { OP_Subtract,    1, 2,        1},
106259      { OP_IfPos,       1, 8,        0},
106260      { OP_Integer,     0, 1,        0},                         /* 6 */
106261      { OP_Noop,        0, 0,        0},
106262      { OP_ResultRow,   1, 1,        0},
106263    };
106264    int addr;
106265    sqlite3VdbeUsesBtree(v, iDb);
106266    if( !zRight ){
106267      setOneColumnName(v, "cache_size");
106268      pParse->nMem += 2;
106269      addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize,iLn);
106270      sqlite3VdbeChangeP1(v, addr, iDb);
106271      sqlite3VdbeChangeP1(v, addr+1, iDb);
106272      sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
106273    }else{
106274      int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
106275      sqlite3BeginWriteOperation(pParse, 0, iDb);
106276      sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
106277      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
106278      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
106279      pDb->pSchema->cache_size = size;
106280      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
106281    }
106282    break;
106283  }
106284#endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
106285
106286#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
106287  /*
106288  **  PRAGMA [database.]page_size
106289  **  PRAGMA [database.]page_size=N
106290  **
106291  ** The first form reports the current setting for the
106292  ** database page size in bytes.  The second form sets the
106293  ** database page size value.  The value can only be set if
106294  ** the database has not yet been created.
106295  */
106296  case PragTyp_PAGE_SIZE: {
106297    Btree *pBt = pDb->pBt;
106298    assert( pBt!=0 );
106299    if( !zRight ){
106300      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
106301      returnSingleInt(v, "page_size", size);
106302    }else{
106303      /* Malloc may fail when setting the page-size, as there is an internal
106304      ** buffer that the pager module resizes using sqlite3_realloc().
106305      */
106306      db->nextPagesize = sqlite3Atoi(zRight);
106307      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
106308        db->mallocFailed = 1;
106309      }
106310    }
106311    break;
106312  }
106313
106314  /*
106315  **  PRAGMA [database.]secure_delete
106316  **  PRAGMA [database.]secure_delete=ON/OFF
106317  **
106318  ** The first form reports the current setting for the
106319  ** secure_delete flag.  The second form changes the secure_delete
106320  ** flag setting and reports thenew value.
106321  */
106322  case PragTyp_SECURE_DELETE: {
106323    Btree *pBt = pDb->pBt;
106324    int b = -1;
106325    assert( pBt!=0 );
106326    if( zRight ){
106327      b = sqlite3GetBoolean(zRight, 0);
106328    }
106329    if( pId2->n==0 && b>=0 ){
106330      int ii;
106331      for(ii=0; ii<db->nDb; ii++){
106332        sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
106333      }
106334    }
106335    b = sqlite3BtreeSecureDelete(pBt, b);
106336    returnSingleInt(v, "secure_delete", b);
106337    break;
106338  }
106339
106340  /*
106341  **  PRAGMA [database.]max_page_count
106342  **  PRAGMA [database.]max_page_count=N
106343  **
106344  ** The first form reports the current setting for the
106345  ** maximum number of pages in the database file.  The
106346  ** second form attempts to change this setting.  Both
106347  ** forms return the current setting.
106348  **
106349  ** The absolute value of N is used.  This is undocumented and might
106350  ** change.  The only purpose is to provide an easy way to test
106351  ** the sqlite3AbsInt32() function.
106352  **
106353  **  PRAGMA [database.]page_count
106354  **
106355  ** Return the number of pages in the specified database.
106356  */
106357  case PragTyp_PAGE_COUNT: {
106358    int iReg;
106359    sqlite3CodeVerifySchema(pParse, iDb);
106360    iReg = ++pParse->nMem;
106361    if( sqlite3Tolower(zLeft[0])=='p' ){
106362      sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
106363    }else{
106364      sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
106365                        sqlite3AbsInt32(sqlite3Atoi(zRight)));
106366    }
106367    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
106368    sqlite3VdbeSetNumCols(v, 1);
106369    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
106370    break;
106371  }
106372
106373  /*
106374  **  PRAGMA [database.]locking_mode
106375  **  PRAGMA [database.]locking_mode = (normal|exclusive)
106376  */
106377  case PragTyp_LOCKING_MODE: {
106378    const char *zRet = "normal";
106379    int eMode = getLockingMode(zRight);
106380
106381    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
106382      /* Simple "PRAGMA locking_mode;" statement. This is a query for
106383      ** the current default locking mode (which may be different to
106384      ** the locking-mode of the main database).
106385      */
106386      eMode = db->dfltLockMode;
106387    }else{
106388      Pager *pPager;
106389      if( pId2->n==0 ){
106390        /* This indicates that no database name was specified as part
106391        ** of the PRAGMA command. In this case the locking-mode must be
106392        ** set on all attached databases, as well as the main db file.
106393        **
106394        ** Also, the sqlite3.dfltLockMode variable is set so that
106395        ** any subsequently attached databases also use the specified
106396        ** locking mode.
106397        */
106398        int ii;
106399        assert(pDb==&db->aDb[0]);
106400        for(ii=2; ii<db->nDb; ii++){
106401          pPager = sqlite3BtreePager(db->aDb[ii].pBt);
106402          sqlite3PagerLockingMode(pPager, eMode);
106403        }
106404        db->dfltLockMode = (u8)eMode;
106405      }
106406      pPager = sqlite3BtreePager(pDb->pBt);
106407      eMode = sqlite3PagerLockingMode(pPager, eMode);
106408    }
106409
106410    assert( eMode==PAGER_LOCKINGMODE_NORMAL
106411            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
106412    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
106413      zRet = "exclusive";
106414    }
106415    returnSingleText(v, "locking_mode", zRet);
106416    break;
106417  }
106418
106419  /*
106420  **  PRAGMA [database.]journal_mode
106421  **  PRAGMA [database.]journal_mode =
106422  **                      (delete|persist|off|truncate|memory|wal|off)
106423  */
106424  case PragTyp_JOURNAL_MODE: {
106425    int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
106426    int ii;           /* Loop counter */
106427
106428    setOneColumnName(v, "journal_mode");
106429    if( zRight==0 ){
106430      /* If there is no "=MODE" part of the pragma, do a query for the
106431      ** current mode */
106432      eMode = PAGER_JOURNALMODE_QUERY;
106433    }else{
106434      const char *zMode;
106435      int n = sqlite3Strlen30(zRight);
106436      for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
106437        if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
106438      }
106439      if( !zMode ){
106440        /* If the "=MODE" part does not match any known journal mode,
106441        ** then do a query */
106442        eMode = PAGER_JOURNALMODE_QUERY;
106443      }
106444    }
106445    if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
106446      /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
106447      iDb = 0;
106448      pId2->n = 1;
106449    }
106450    for(ii=db->nDb-1; ii>=0; ii--){
106451      if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
106452        sqlite3VdbeUsesBtree(v, ii);
106453        sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
106454      }
106455    }
106456    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
106457    break;
106458  }
106459
106460  /*
106461  **  PRAGMA [database.]journal_size_limit
106462  **  PRAGMA [database.]journal_size_limit=N
106463  **
106464  ** Get or set the size limit on rollback journal files.
106465  */
106466  case PragTyp_JOURNAL_SIZE_LIMIT: {
106467    Pager *pPager = sqlite3BtreePager(pDb->pBt);
106468    i64 iLimit = -2;
106469    if( zRight ){
106470      sqlite3DecOrHexToI64(zRight, &iLimit);
106471      if( iLimit<-1 ) iLimit = -1;
106472    }
106473    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
106474    returnSingleInt(v, "journal_size_limit", iLimit);
106475    break;
106476  }
106477
106478#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
106479
106480  /*
106481  **  PRAGMA [database.]auto_vacuum
106482  **  PRAGMA [database.]auto_vacuum=N
106483  **
106484  ** Get or set the value of the database 'auto-vacuum' parameter.
106485  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
106486  */
106487#ifndef SQLITE_OMIT_AUTOVACUUM
106488  case PragTyp_AUTO_VACUUM: {
106489    Btree *pBt = pDb->pBt;
106490    assert( pBt!=0 );
106491    if( !zRight ){
106492      returnSingleInt(v, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
106493    }else{
106494      int eAuto = getAutoVacuum(zRight);
106495      assert( eAuto>=0 && eAuto<=2 );
106496      db->nextAutovac = (u8)eAuto;
106497      /* Call SetAutoVacuum() to set initialize the internal auto and
106498      ** incr-vacuum flags. This is required in case this connection
106499      ** creates the database file. It is important that it is created
106500      ** as an auto-vacuum capable db.
106501      */
106502      rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
106503      if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
106504        /* When setting the auto_vacuum mode to either "full" or
106505        ** "incremental", write the value of meta[6] in the database
106506        ** file. Before writing to meta[6], check that meta[3] indicates
106507        ** that this really is an auto-vacuum capable database.
106508        */
106509        static const int iLn = VDBE_OFFSET_LINENO(2);
106510        static const VdbeOpList setMeta6[] = {
106511          { OP_Transaction,    0,         1,                 0},    /* 0 */
106512          { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
106513          { OP_If,             1,         0,                 0},    /* 2 */
106514          { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
106515          { OP_Integer,        0,         1,                 0},    /* 4 */
106516          { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
106517        };
106518        int iAddr;
106519        iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
106520        sqlite3VdbeChangeP1(v, iAddr, iDb);
106521        sqlite3VdbeChangeP1(v, iAddr+1, iDb);
106522        sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
106523        sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
106524        sqlite3VdbeChangeP1(v, iAddr+5, iDb);
106525        sqlite3VdbeUsesBtree(v, iDb);
106526      }
106527    }
106528    break;
106529  }
106530#endif
106531
106532  /*
106533  **  PRAGMA [database.]incremental_vacuum(N)
106534  **
106535  ** Do N steps of incremental vacuuming on a database.
106536  */
106537#ifndef SQLITE_OMIT_AUTOVACUUM
106538  case PragTyp_INCREMENTAL_VACUUM: {
106539    int iLimit, addr;
106540    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
106541      iLimit = 0x7fffffff;
106542    }
106543    sqlite3BeginWriteOperation(pParse, 0, iDb);
106544    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
106545    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
106546    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
106547    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
106548    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
106549    sqlite3VdbeJumpHere(v, addr);
106550    break;
106551  }
106552#endif
106553
106554#ifndef SQLITE_OMIT_PAGER_PRAGMAS
106555  /*
106556  **  PRAGMA [database.]cache_size
106557  **  PRAGMA [database.]cache_size=N
106558  **
106559  ** The first form reports the current local setting for the
106560  ** page cache size. The second form sets the local
106561  ** page cache size value.  If N is positive then that is the
106562  ** number of pages in the cache.  If N is negative, then the
106563  ** number of pages is adjusted so that the cache uses -N kibibytes
106564  ** of memory.
106565  */
106566  case PragTyp_CACHE_SIZE: {
106567    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
106568    if( !zRight ){
106569      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
106570      returnSingleInt(v, "cache_size", pDb->pSchema->cache_size);
106571    }else{
106572      int size = sqlite3Atoi(zRight);
106573      pDb->pSchema->cache_size = size;
106574      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
106575      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
106576    }
106577    break;
106578  }
106579
106580  /*
106581  **  PRAGMA [database.]mmap_size(N)
106582  **
106583  ** Used to set mapping size limit. The mapping size limit is
106584  ** used to limit the aggregate size of all memory mapped regions of the
106585  ** database file. If this parameter is set to zero, then memory mapping
106586  ** is not used at all.  If N is negative, then the default memory map
106587  ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
106588  ** The parameter N is measured in bytes.
106589  **
106590  ** This value is advisory.  The underlying VFS is free to memory map
106591  ** as little or as much as it wants.  Except, if N is set to 0 then the
106592  ** upper layers will never invoke the xFetch interfaces to the VFS.
106593  */
106594  case PragTyp_MMAP_SIZE: {
106595    sqlite3_int64 sz;
106596#if SQLITE_MAX_MMAP_SIZE>0
106597    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
106598    if( zRight ){
106599      int ii;
106600      sqlite3DecOrHexToI64(zRight, &sz);
106601      if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
106602      if( pId2->n==0 ) db->szMmap = sz;
106603      for(ii=db->nDb-1; ii>=0; ii--){
106604        if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
106605          sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
106606        }
106607      }
106608    }
106609    sz = -1;
106610    rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
106611#else
106612    sz = 0;
106613    rc = SQLITE_OK;
106614#endif
106615    if( rc==SQLITE_OK ){
106616      returnSingleInt(v, "mmap_size", sz);
106617    }else if( rc!=SQLITE_NOTFOUND ){
106618      pParse->nErr++;
106619      pParse->rc = rc;
106620    }
106621    break;
106622  }
106623
106624  /*
106625  **   PRAGMA temp_store
106626  **   PRAGMA temp_store = "default"|"memory"|"file"
106627  **
106628  ** Return or set the local value of the temp_store flag.  Changing
106629  ** the local value does not make changes to the disk file and the default
106630  ** value will be restored the next time the database is opened.
106631  **
106632  ** Note that it is possible for the library compile-time options to
106633  ** override this setting
106634  */
106635  case PragTyp_TEMP_STORE: {
106636    if( !zRight ){
106637      returnSingleInt(v, "temp_store", db->temp_store);
106638    }else{
106639      changeTempStorage(pParse, zRight);
106640    }
106641    break;
106642  }
106643
106644  /*
106645  **   PRAGMA temp_store_directory
106646  **   PRAGMA temp_store_directory = ""|"directory_name"
106647  **
106648  ** Return or set the local value of the temp_store_directory flag.  Changing
106649  ** the value sets a specific directory to be used for temporary files.
106650  ** Setting to a null string reverts to the default temporary directory search.
106651  ** If temporary directory is changed, then invalidateTempStorage.
106652  **
106653  */
106654  case PragTyp_TEMP_STORE_DIRECTORY: {
106655    if( !zRight ){
106656      returnSingleText(v, "temp_store_directory", sqlite3_temp_directory);
106657    }else{
106658#ifndef SQLITE_OMIT_WSD
106659      if( zRight[0] ){
106660        int res;
106661        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
106662        if( rc!=SQLITE_OK || res==0 ){
106663          sqlite3ErrorMsg(pParse, "not a writable directory");
106664          goto pragma_out;
106665        }
106666      }
106667      if( SQLITE_TEMP_STORE==0
106668       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
106669       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
106670      ){
106671        invalidateTempStorage(pParse);
106672      }
106673      sqlite3_free(sqlite3_temp_directory);
106674      if( zRight[0] ){
106675        sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
106676      }else{
106677        sqlite3_temp_directory = 0;
106678      }
106679#endif /* SQLITE_OMIT_WSD */
106680    }
106681    break;
106682  }
106683
106684#if SQLITE_OS_WIN
106685  /*
106686  **   PRAGMA data_store_directory
106687  **   PRAGMA data_store_directory = ""|"directory_name"
106688  **
106689  ** Return or set the local value of the data_store_directory flag.  Changing
106690  ** the value sets a specific directory to be used for database files that
106691  ** were specified with a relative pathname.  Setting to a null string reverts
106692  ** to the default database directory, which for database files specified with
106693  ** a relative path will probably be based on the current directory for the
106694  ** process.  Database file specified with an absolute path are not impacted
106695  ** by this setting, regardless of its value.
106696  **
106697  */
106698  case PragTyp_DATA_STORE_DIRECTORY: {
106699    if( !zRight ){
106700      returnSingleText(v, "data_store_directory", sqlite3_data_directory);
106701    }else{
106702#ifndef SQLITE_OMIT_WSD
106703      if( zRight[0] ){
106704        int res;
106705        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
106706        if( rc!=SQLITE_OK || res==0 ){
106707          sqlite3ErrorMsg(pParse, "not a writable directory");
106708          goto pragma_out;
106709        }
106710      }
106711      sqlite3_free(sqlite3_data_directory);
106712      if( zRight[0] ){
106713        sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
106714      }else{
106715        sqlite3_data_directory = 0;
106716      }
106717#endif /* SQLITE_OMIT_WSD */
106718    }
106719    break;
106720  }
106721#endif
106722
106723#if SQLITE_ENABLE_LOCKING_STYLE
106724  /*
106725  **   PRAGMA [database.]lock_proxy_file
106726  **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
106727  **
106728  ** Return or set the value of the lock_proxy_file flag.  Changing
106729  ** the value sets a specific file to be used for database access locks.
106730  **
106731  */
106732  case PragTyp_LOCK_PROXY_FILE: {
106733    if( !zRight ){
106734      Pager *pPager = sqlite3BtreePager(pDb->pBt);
106735      char *proxy_file_path = NULL;
106736      sqlite3_file *pFile = sqlite3PagerFile(pPager);
106737      sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
106738                           &proxy_file_path);
106739      returnSingleText(v, "lock_proxy_file", proxy_file_path);
106740    }else{
106741      Pager *pPager = sqlite3BtreePager(pDb->pBt);
106742      sqlite3_file *pFile = sqlite3PagerFile(pPager);
106743      int res;
106744      if( zRight[0] ){
106745        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
106746                                     zRight);
106747      } else {
106748        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
106749                                     NULL);
106750      }
106751      if( res!=SQLITE_OK ){
106752        sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
106753        goto pragma_out;
106754      }
106755    }
106756    break;
106757  }
106758#endif /* SQLITE_ENABLE_LOCKING_STYLE */
106759
106760  /*
106761  **   PRAGMA [database.]synchronous
106762  **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
106763  **
106764  ** Return or set the local value of the synchronous flag.  Changing
106765  ** the local value does not make changes to the disk file and the
106766  ** default value will be restored the next time the database is
106767  ** opened.
106768  */
106769  case PragTyp_SYNCHRONOUS: {
106770    if( !zRight ){
106771      returnSingleInt(v, "synchronous", pDb->safety_level-1);
106772    }else{
106773      if( !db->autoCommit ){
106774        sqlite3ErrorMsg(pParse,
106775            "Safety level may not be changed inside a transaction");
106776      }else{
106777        int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
106778        if( iLevel==0 ) iLevel = 1;
106779        pDb->safety_level = iLevel;
106780        setAllPagerFlags(db);
106781      }
106782    }
106783    break;
106784  }
106785#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
106786
106787#ifndef SQLITE_OMIT_FLAG_PRAGMAS
106788  case PragTyp_FLAG: {
106789    if( zRight==0 ){
106790      returnSingleInt(v, pPragma->zName, (db->flags & pPragma->iArg)!=0 );
106791    }else{
106792      int mask = pPragma->iArg;    /* Mask of bits to set or clear. */
106793      if( db->autoCommit==0 ){
106794        /* Foreign key support may not be enabled or disabled while not
106795        ** in auto-commit mode.  */
106796        mask &= ~(SQLITE_ForeignKeys);
106797      }
106798#if SQLITE_USER_AUTHENTICATION
106799      if( db->auth.authLevel==UAUTH_User ){
106800        /* Do not allow non-admin users to modify the schema arbitrarily */
106801        mask &= ~(SQLITE_WriteSchema);
106802      }
106803#endif
106804
106805      if( sqlite3GetBoolean(zRight, 0) ){
106806        db->flags |= mask;
106807      }else{
106808        db->flags &= ~mask;
106809        if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
106810      }
106811
106812      /* Many of the flag-pragmas modify the code generated by the SQL
106813      ** compiler (eg. count_changes). So add an opcode to expire all
106814      ** compiled SQL statements after modifying a pragma value.
106815      */
106816      sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
106817      setAllPagerFlags(db);
106818    }
106819    break;
106820  }
106821#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
106822
106823#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
106824  /*
106825  **   PRAGMA table_info(<table>)
106826  **
106827  ** Return a single row for each column of the named table. The columns of
106828  ** the returned data set are:
106829  **
106830  ** cid:        Column id (numbered from left to right, starting at 0)
106831  ** name:       Column name
106832  ** type:       Column declaration type.
106833  ** notnull:    True if 'NOT NULL' is part of column declaration
106834  ** dflt_value: The default value for the column, if any.
106835  */
106836  case PragTyp_TABLE_INFO: if( zRight ){
106837    Table *pTab;
106838    pTab = sqlite3FindTable(db, zRight, zDb);
106839    if( pTab ){
106840      static const char *azCol[] = {
106841         "cid", "name", "type", "notnull", "dflt_value", "pk"
106842      };
106843      int i, k;
106844      int nHidden = 0;
106845      Column *pCol;
106846      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
106847      pParse->nMem = 6;
106848      sqlite3CodeVerifySchema(pParse, iDb);
106849      setAllColumnNames(v, 6, azCol); assert( 6==ArraySize(azCol) );
106850      sqlite3ViewGetColumnNames(pParse, pTab);
106851      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
106852        if( IsHiddenColumn(pCol) ){
106853          nHidden++;
106854          continue;
106855        }
106856        if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
106857          k = 0;
106858        }else if( pPk==0 ){
106859          k = 1;
106860        }else{
106861          for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
106862        }
106863        sqlite3VdbeMultiLoad(v, 1, "issisi",
106864               i-nHidden,
106865               pCol->zName,
106866               pCol->zType ? pCol->zType : "",
106867               pCol->notNull ? 1 : 0,
106868               pCol->zDflt,
106869               k);
106870        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
106871      }
106872    }
106873  }
106874  break;
106875
106876  case PragTyp_STATS: {
106877    static const char *azCol[] = { "table", "index", "width", "height" };
106878    Index *pIdx;
106879    HashElem *i;
106880    v = sqlite3GetVdbe(pParse);
106881    pParse->nMem = 4;
106882    sqlite3CodeVerifySchema(pParse, iDb);
106883    setAllColumnNames(v, 4, azCol);  assert( 4==ArraySize(azCol) );
106884    for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
106885      Table *pTab = sqliteHashData(i);
106886      sqlite3VdbeMultiLoad(v, 1, "ssii",
106887           pTab->zName,
106888           0,
106889           (int)sqlite3LogEstToInt(pTab->szTabRow),
106890           (int)sqlite3LogEstToInt(pTab->nRowLogEst));
106891      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
106892      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
106893        sqlite3VdbeMultiLoad(v, 2, "sii",
106894           pIdx->zName,
106895           (int)sqlite3LogEstToInt(pIdx->szIdxRow),
106896           (int)sqlite3LogEstToInt(pIdx->aiRowLogEst[0]));
106897        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
106898      }
106899    }
106900  }
106901  break;
106902
106903  case PragTyp_INDEX_INFO: if( zRight ){
106904    Index *pIdx;
106905    Table *pTab;
106906    pIdx = sqlite3FindIndex(db, zRight, zDb);
106907    if( pIdx ){
106908      static const char *azCol[] = {
106909         "seqno", "cid", "name", "desc", "coll", "key"
106910      };
106911      int i;
106912      int mx;
106913      if( pPragma->iArg ){
106914        /* PRAGMA index_xinfo (newer version with more rows and columns) */
106915        mx = pIdx->nColumn;
106916        pParse->nMem = 6;
106917      }else{
106918        /* PRAGMA index_info (legacy version) */
106919        mx = pIdx->nKeyCol;
106920        pParse->nMem = 3;
106921      }
106922      pTab = pIdx->pTable;
106923      sqlite3CodeVerifySchema(pParse, iDb);
106924      assert( pParse->nMem<=ArraySize(azCol) );
106925      setAllColumnNames(v, pParse->nMem, azCol);
106926      for(i=0; i<mx; i++){
106927        i16 cnum = pIdx->aiColumn[i];
106928        sqlite3VdbeMultiLoad(v, 1, "iis", i, cnum,
106929                             cnum<0 ? 0 : pTab->aCol[cnum].zName);
106930        if( pPragma->iArg ){
106931          sqlite3VdbeMultiLoad(v, 4, "isi",
106932            pIdx->aSortOrder[i],
106933            pIdx->azColl[i],
106934            i<pIdx->nKeyCol);
106935        }
106936        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
106937      }
106938    }
106939  }
106940  break;
106941
106942  case PragTyp_INDEX_LIST: if( zRight ){
106943    Index *pIdx;
106944    Table *pTab;
106945    int i;
106946    pTab = sqlite3FindTable(db, zRight, zDb);
106947    if( pTab ){
106948      static const char *azCol[] = {
106949        "seq", "name", "unique", "origin", "partial"
106950      };
106951      v = sqlite3GetVdbe(pParse);
106952      pParse->nMem = 5;
106953      sqlite3CodeVerifySchema(pParse, iDb);
106954      setAllColumnNames(v, 5, azCol);  assert( 5==ArraySize(azCol) );
106955      for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
106956        const char *azOrigin[] = { "c", "u", "pk" };
106957        sqlite3VdbeMultiLoad(v, 1, "isisi",
106958           i,
106959           pIdx->zName,
106960           IsUniqueIndex(pIdx),
106961           azOrigin[pIdx->idxType],
106962           pIdx->pPartIdxWhere!=0);
106963        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
106964      }
106965    }
106966  }
106967  break;
106968
106969  case PragTyp_DATABASE_LIST: {
106970    static const char *azCol[] = { "seq", "name", "file" };
106971    int i;
106972    pParse->nMem = 3;
106973    setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) );
106974    for(i=0; i<db->nDb; i++){
106975      if( db->aDb[i].pBt==0 ) continue;
106976      assert( db->aDb[i].zName!=0 );
106977      sqlite3VdbeMultiLoad(v, 1, "iss",
106978         i,
106979         db->aDb[i].zName,
106980         sqlite3BtreeGetFilename(db->aDb[i].pBt));
106981      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
106982    }
106983  }
106984  break;
106985
106986  case PragTyp_COLLATION_LIST: {
106987    static const char *azCol[] = { "seq", "name" };
106988    int i = 0;
106989    HashElem *p;
106990    pParse->nMem = 2;
106991    setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
106992    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
106993      CollSeq *pColl = (CollSeq *)sqliteHashData(p);
106994      sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
106995      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
106996    }
106997  }
106998  break;
106999#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
107000
107001#ifndef SQLITE_OMIT_FOREIGN_KEY
107002  case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
107003    FKey *pFK;
107004    Table *pTab;
107005    pTab = sqlite3FindTable(db, zRight, zDb);
107006    if( pTab ){
107007      v = sqlite3GetVdbe(pParse);
107008      pFK = pTab->pFKey;
107009      if( pFK ){
107010        static const char *azCol[] = {
107011           "id", "seq", "table", "from", "to", "on_update", "on_delete",
107012           "match"
107013        };
107014        int i = 0;
107015        pParse->nMem = 8;
107016        sqlite3CodeVerifySchema(pParse, iDb);
107017        setAllColumnNames(v, 8, azCol); assert( 8==ArraySize(azCol) );
107018        while(pFK){
107019          int j;
107020          for(j=0; j<pFK->nCol; j++){
107021            sqlite3VdbeMultiLoad(v, 1, "iissssss",
107022                   i,
107023                   j,
107024                   pFK->zTo,
107025                   pTab->aCol[pFK->aCol[j].iFrom].zName,
107026                   pFK->aCol[j].zCol,
107027                   actionName(pFK->aAction[1]),  /* ON UPDATE */
107028                   actionName(pFK->aAction[0]),  /* ON DELETE */
107029                   "NONE");
107030            sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
107031          }
107032          ++i;
107033          pFK = pFK->pNextFrom;
107034        }
107035      }
107036    }
107037  }
107038  break;
107039#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
107040
107041#ifndef SQLITE_OMIT_FOREIGN_KEY
107042#ifndef SQLITE_OMIT_TRIGGER
107043  case PragTyp_FOREIGN_KEY_CHECK: {
107044    FKey *pFK;             /* A foreign key constraint */
107045    Table *pTab;           /* Child table contain "REFERENCES" keyword */
107046    Table *pParent;        /* Parent table that child points to */
107047    Index *pIdx;           /* Index in the parent table */
107048    int i;                 /* Loop counter:  Foreign key number for pTab */
107049    int j;                 /* Loop counter:  Field of the foreign key */
107050    HashElem *k;           /* Loop counter:  Next table in schema */
107051    int x;                 /* result variable */
107052    int regResult;         /* 3 registers to hold a result row */
107053    int regKey;            /* Register to hold key for checking the FK */
107054    int regRow;            /* Registers to hold a row from pTab */
107055    int addrTop;           /* Top of a loop checking foreign keys */
107056    int addrOk;            /* Jump here if the key is OK */
107057    int *aiCols;           /* child to parent column mapping */
107058    static const char *azCol[] = { "table", "rowid", "parent", "fkid" };
107059
107060    regResult = pParse->nMem+1;
107061    pParse->nMem += 4;
107062    regKey = ++pParse->nMem;
107063    regRow = ++pParse->nMem;
107064    v = sqlite3GetVdbe(pParse);
107065    setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) );
107066    sqlite3CodeVerifySchema(pParse, iDb);
107067    k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
107068    while( k ){
107069      if( zRight ){
107070        pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
107071        k = 0;
107072      }else{
107073        pTab = (Table*)sqliteHashData(k);
107074        k = sqliteHashNext(k);
107075      }
107076      if( pTab==0 || pTab->pFKey==0 ) continue;
107077      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
107078      if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
107079      sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
107080      sqlite3VdbeLoadString(v, regResult, pTab->zName);
107081      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
107082        pParent = sqlite3FindTable(db, pFK->zTo, zDb);
107083        if( pParent==0 ) continue;
107084        pIdx = 0;
107085        sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
107086        x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
107087        if( x==0 ){
107088          if( pIdx==0 ){
107089            sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
107090          }else{
107091            sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
107092            sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
107093          }
107094        }else{
107095          k = 0;
107096          break;
107097        }
107098      }
107099      assert( pParse->nErr>0 || pFK==0 );
107100      if( pFK ) break;
107101      if( pParse->nTab<i ) pParse->nTab = i;
107102      addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
107103      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
107104        pParent = sqlite3FindTable(db, pFK->zTo, zDb);
107105        pIdx = 0;
107106        aiCols = 0;
107107        if( pParent ){
107108          x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
107109          assert( x==0 );
107110        }
107111        addrOk = sqlite3VdbeMakeLabel(v);
107112        if( pParent && pIdx==0 ){
107113          int iKey = pFK->aCol[0].iFrom;
107114          assert( iKey>=0 && iKey<pTab->nCol );
107115          if( iKey!=pTab->iPKey ){
107116            sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
107117            sqlite3ColumnDefault(v, pTab, iKey, regRow);
107118            sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
107119            sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
107120               sqlite3VdbeCurrentAddr(v)+3); VdbeCoverage(v);
107121          }else{
107122            sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
107123          }
107124          sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); VdbeCoverage(v);
107125          sqlite3VdbeGoto(v, addrOk);
107126          sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
107127        }else{
107128          for(j=0; j<pFK->nCol; j++){
107129            sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
107130                            aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
107131            sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
107132          }
107133          if( pParent ){
107134            sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
107135                              sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
107136            sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
107137            VdbeCoverage(v);
107138          }
107139        }
107140        sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
107141        sqlite3VdbeMultiLoad(v, regResult+2, "si", pFK->zTo, i-1);
107142        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
107143        sqlite3VdbeResolveLabel(v, addrOk);
107144        sqlite3DbFree(db, aiCols);
107145      }
107146      sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
107147      sqlite3VdbeJumpHere(v, addrTop);
107148    }
107149  }
107150  break;
107151#endif /* !defined(SQLITE_OMIT_TRIGGER) */
107152#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
107153
107154#ifndef NDEBUG
107155  case PragTyp_PARSER_TRACE: {
107156    if( zRight ){
107157      if( sqlite3GetBoolean(zRight, 0) ){
107158        sqlite3ParserTrace(stderr, "parser: ");
107159      }else{
107160        sqlite3ParserTrace(0, 0);
107161      }
107162    }
107163  }
107164  break;
107165#endif
107166
107167  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
107168  ** used will be case sensitive or not depending on the RHS.
107169  */
107170  case PragTyp_CASE_SENSITIVE_LIKE: {
107171    if( zRight ){
107172      sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
107173    }
107174  }
107175  break;
107176
107177#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
107178# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
107179#endif
107180
107181#ifndef SQLITE_OMIT_INTEGRITY_CHECK
107182  /* Pragma "quick_check" is reduced version of
107183  ** integrity_check designed to detect most database corruption
107184  ** without most of the overhead of a full integrity-check.
107185  */
107186  case PragTyp_INTEGRITY_CHECK: {
107187    int i, j, addr, mxErr;
107188
107189    /* Code that appears at the end of the integrity check.  If no error
107190    ** messages have been generated, output OK.  Otherwise output the
107191    ** error message
107192    */
107193    static const int iLn = VDBE_OFFSET_LINENO(2);
107194    static const VdbeOpList endCode[] = {
107195      { OP_AddImm,      1, 0,        0},    /* 0 */
107196      { OP_If,          1, 0,        0},    /* 1 */
107197      { OP_String8,     0, 3,        0},    /* 2 */
107198      { OP_ResultRow,   3, 1,        0},
107199    };
107200
107201    int isQuick = (sqlite3Tolower(zLeft[0])=='q');
107202
107203    /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
107204    ** then iDb is set to the index of the database identified by <db>.
107205    ** In this case, the integrity of database iDb only is verified by
107206    ** the VDBE created below.
107207    **
107208    ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
107209    ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
107210    ** to -1 here, to indicate that the VDBE should verify the integrity
107211    ** of all attached databases.  */
107212    assert( iDb>=0 );
107213    assert( iDb==0 || pId2->z );
107214    if( pId2->z==0 ) iDb = -1;
107215
107216    /* Initialize the VDBE program */
107217    pParse->nMem = 6;
107218    setOneColumnName(v, "integrity_check");
107219
107220    /* Set the maximum error count */
107221    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
107222    if( zRight ){
107223      sqlite3GetInt32(zRight, &mxErr);
107224      if( mxErr<=0 ){
107225        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
107226      }
107227    }
107228    sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
107229
107230    /* Do an integrity check on each database file */
107231    for(i=0; i<db->nDb; i++){
107232      HashElem *x;
107233      Hash *pTbls;
107234      int cnt = 0;
107235
107236      if( OMIT_TEMPDB && i==1 ) continue;
107237      if( iDb>=0 && i!=iDb ) continue;
107238
107239      sqlite3CodeVerifySchema(pParse, i);
107240      addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
107241      VdbeCoverage(v);
107242      sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
107243      sqlite3VdbeJumpHere(v, addr);
107244
107245      /* Do an integrity check of the B-Tree
107246      **
107247      ** Begin by filling registers 2, 3, ... with the root pages numbers
107248      ** for all tables and indices in the database.
107249      */
107250      assert( sqlite3SchemaMutexHeld(db, i, 0) );
107251      pTbls = &db->aDb[i].pSchema->tblHash;
107252      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
107253        Table *pTab = sqliteHashData(x);
107254        Index *pIdx;
107255        if( HasRowid(pTab) ){
107256          sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
107257          VdbeComment((v, "%s", pTab->zName));
107258          cnt++;
107259        }
107260        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
107261          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
107262          VdbeComment((v, "%s", pIdx->zName));
107263          cnt++;
107264        }
107265      }
107266
107267      /* Make sure sufficient number of registers have been allocated */
107268      pParse->nMem = MAX( pParse->nMem, cnt+8 );
107269
107270      /* Do the b-tree integrity checks */
107271      sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
107272      sqlite3VdbeChangeP5(v, (u8)i);
107273      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
107274      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
107275         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
107276         P4_DYNAMIC);
107277      sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
107278      sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
107279      sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
107280      sqlite3VdbeJumpHere(v, addr);
107281
107282      /* Make sure all the indices are constructed correctly.
107283      */
107284      for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
107285        Table *pTab = sqliteHashData(x);
107286        Index *pIdx, *pPk;
107287        Index *pPrior = 0;
107288        int loopTop;
107289        int iDataCur, iIdxCur;
107290        int r1 = -1;
107291
107292        if( pTab->pIndex==0 ) continue;
107293        pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
107294        addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
107295        VdbeCoverage(v);
107296        sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
107297        sqlite3VdbeJumpHere(v, addr);
107298        sqlite3ExprCacheClear(pParse);
107299        sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead,
107300                                   1, 0, &iDataCur, &iIdxCur);
107301        sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
107302        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
107303          sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
107304        }
107305        pParse->nMem = MAX(pParse->nMem, 8+j);
107306        sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
107307        loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
107308        /* Verify that all NOT NULL columns really are NOT NULL */
107309        for(j=0; j<pTab->nCol; j++){
107310          char *zErr;
107311          int jmp2, jmp3;
107312          if( j==pTab->iPKey ) continue;
107313          if( pTab->aCol[j].notNull==0 ) continue;
107314          sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
107315          sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
107316          jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
107317          sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
107318          zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
107319                              pTab->aCol[j].zName);
107320          sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
107321          sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
107322          jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
107323          sqlite3VdbeAddOp0(v, OP_Halt);
107324          sqlite3VdbeJumpHere(v, jmp2);
107325          sqlite3VdbeJumpHere(v, jmp3);
107326        }
107327        /* Validate index entries for the current row */
107328        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
107329          int jmp2, jmp3, jmp4, jmp5;
107330          int ckUniq = sqlite3VdbeMakeLabel(v);
107331          if( pPk==pIdx ) continue;
107332          r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
107333                                       pPrior, r1);
107334          pPrior = pIdx;
107335          sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);  /* increment entry count */
107336          /* Verify that an index entry exists for the current table row */
107337          jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
107338                                      pIdx->nColumn); VdbeCoverage(v);
107339          sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
107340          sqlite3VdbeLoadString(v, 3, "row ");
107341          sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
107342          sqlite3VdbeLoadString(v, 4, " missing from index ");
107343          sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
107344          jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
107345          sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
107346          sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
107347          jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
107348          sqlite3VdbeAddOp0(v, OP_Halt);
107349          sqlite3VdbeJumpHere(v, jmp2);
107350          /* For UNIQUE indexes, verify that only one entry exists with the
107351          ** current key.  The entry is unique if (1) any column is NULL
107352          ** or (2) the next entry has a different key */
107353          if( IsUniqueIndex(pIdx) ){
107354            int uniqOk = sqlite3VdbeMakeLabel(v);
107355            int jmp6;
107356            int kk;
107357            for(kk=0; kk<pIdx->nKeyCol; kk++){
107358              int iCol = pIdx->aiColumn[kk];
107359              assert( iCol!=XN_ROWID && iCol<pTab->nCol );
107360              if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
107361              sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
107362              VdbeCoverage(v);
107363            }
107364            jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
107365            sqlite3VdbeGoto(v, uniqOk);
107366            sqlite3VdbeJumpHere(v, jmp6);
107367            sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
107368                                 pIdx->nKeyCol); VdbeCoverage(v);
107369            sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
107370            sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
107371            sqlite3VdbeGoto(v, jmp5);
107372            sqlite3VdbeResolveLabel(v, uniqOk);
107373          }
107374          sqlite3VdbeJumpHere(v, jmp4);
107375          sqlite3ResolvePartIdxLabel(pParse, jmp3);
107376        }
107377        sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
107378        sqlite3VdbeJumpHere(v, loopTop-1);
107379#ifndef SQLITE_OMIT_BTREECOUNT
107380        sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
107381        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
107382          if( pPk==pIdx ) continue;
107383          addr = sqlite3VdbeCurrentAddr(v);
107384          sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
107385          sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
107386          sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
107387          sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
107388          sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
107389          sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
107390          sqlite3VdbeLoadString(v, 3, pIdx->zName);
107391          sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
107392          sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
107393        }
107394#endif /* SQLITE_OMIT_BTREECOUNT */
107395      }
107396    }
107397    addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
107398    sqlite3VdbeChangeP2(v, addr, -mxErr);
107399    sqlite3VdbeJumpHere(v, addr+1);
107400    sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
107401  }
107402  break;
107403#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
107404
107405#ifndef SQLITE_OMIT_UTF16
107406  /*
107407  **   PRAGMA encoding
107408  **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
107409  **
107410  ** In its first form, this pragma returns the encoding of the main
107411  ** database. If the database is not initialized, it is initialized now.
107412  **
107413  ** The second form of this pragma is a no-op if the main database file
107414  ** has not already been initialized. In this case it sets the default
107415  ** encoding that will be used for the main database file if a new file
107416  ** is created. If an existing main database file is opened, then the
107417  ** default text encoding for the existing database is used.
107418  **
107419  ** In all cases new databases created using the ATTACH command are
107420  ** created to use the same default text encoding as the main database. If
107421  ** the main database has not been initialized and/or created when ATTACH
107422  ** is executed, this is done before the ATTACH operation.
107423  **
107424  ** In the second form this pragma sets the text encoding to be used in
107425  ** new database files created using this database handle. It is only
107426  ** useful if invoked immediately after the main database i
107427  */
107428  case PragTyp_ENCODING: {
107429    static const struct EncName {
107430      char *zName;
107431      u8 enc;
107432    } encnames[] = {
107433      { "UTF8",     SQLITE_UTF8        },
107434      { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
107435      { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
107436      { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
107437      { "UTF16le",  SQLITE_UTF16LE     },
107438      { "UTF16be",  SQLITE_UTF16BE     },
107439      { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
107440      { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
107441      { 0, 0 }
107442    };
107443    const struct EncName *pEnc;
107444    if( !zRight ){    /* "PRAGMA encoding" */
107445      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
107446      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
107447      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
107448      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
107449      returnSingleText(v, "encoding", encnames[ENC(pParse->db)].zName);
107450    }else{                        /* "PRAGMA encoding = XXX" */
107451      /* Only change the value of sqlite.enc if the database handle is not
107452      ** initialized. If the main database exists, the new sqlite.enc value
107453      ** will be overwritten when the schema is next loaded. If it does not
107454      ** already exists, it will be created to use the new encoding value.
107455      */
107456      if(
107457        !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
107458        DbHasProperty(db, 0, DB_Empty)
107459      ){
107460        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
107461          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
107462            SCHEMA_ENC(db) = ENC(db) =
107463                pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
107464            break;
107465          }
107466        }
107467        if( !pEnc->zName ){
107468          sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
107469        }
107470      }
107471    }
107472  }
107473  break;
107474#endif /* SQLITE_OMIT_UTF16 */
107475
107476#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
107477  /*
107478  **   PRAGMA [database.]schema_version
107479  **   PRAGMA [database.]schema_version = <integer>
107480  **
107481  **   PRAGMA [database.]user_version
107482  **   PRAGMA [database.]user_version = <integer>
107483  **
107484  **   PRAGMA [database.]freelist_count = <integer>
107485  **
107486  **   PRAGMA [database.]application_id
107487  **   PRAGMA [database.]application_id = <integer>
107488  **
107489  ** The pragma's schema_version and user_version are used to set or get
107490  ** the value of the schema-version and user-version, respectively. Both
107491  ** the schema-version and the user-version are 32-bit signed integers
107492  ** stored in the database header.
107493  **
107494  ** The schema-cookie is usually only manipulated internally by SQLite. It
107495  ** is incremented by SQLite whenever the database schema is modified (by
107496  ** creating or dropping a table or index). The schema version is used by
107497  ** SQLite each time a query is executed to ensure that the internal cache
107498  ** of the schema used when compiling the SQL query matches the schema of
107499  ** the database against which the compiled query is actually executed.
107500  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
107501  ** the schema-version is potentially dangerous and may lead to program
107502  ** crashes or database corruption. Use with caution!
107503  **
107504  ** The user-version is not used internally by SQLite. It may be used by
107505  ** applications for any purpose.
107506  */
107507  case PragTyp_HEADER_VALUE: {
107508    int iCookie = pPragma->iArg;  /* Which cookie to read or write */
107509    sqlite3VdbeUsesBtree(v, iDb);
107510    if( zRight && (pPragma->mPragFlag & PragFlag_ReadOnly)==0 ){
107511      /* Write the specified cookie value */
107512      static const VdbeOpList setCookie[] = {
107513        { OP_Transaction,    0,  1,  0},    /* 0 */
107514        { OP_Integer,        0,  1,  0},    /* 1 */
107515        { OP_SetCookie,      0,  0,  1},    /* 2 */
107516      };
107517      int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
107518      sqlite3VdbeChangeP1(v, addr, iDb);
107519      sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
107520      sqlite3VdbeChangeP1(v, addr+2, iDb);
107521      sqlite3VdbeChangeP2(v, addr+2, iCookie);
107522    }else{
107523      /* Read the specified cookie value */
107524      static const VdbeOpList readCookie[] = {
107525        { OP_Transaction,     0,  0,  0},    /* 0 */
107526        { OP_ReadCookie,      0,  1,  0},    /* 1 */
107527        { OP_ResultRow,       1,  1,  0}
107528      };
107529      int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie, 0);
107530      sqlite3VdbeChangeP1(v, addr, iDb);
107531      sqlite3VdbeChangeP1(v, addr+1, iDb);
107532      sqlite3VdbeChangeP3(v, addr+1, iCookie);
107533      sqlite3VdbeSetNumCols(v, 1);
107534      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
107535    }
107536  }
107537  break;
107538#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
107539
107540#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
107541  /*
107542  **   PRAGMA compile_options
107543  **
107544  ** Return the names of all compile-time options used in this build,
107545  ** one option per row.
107546  */
107547  case PragTyp_COMPILE_OPTIONS: {
107548    int i = 0;
107549    const char *zOpt;
107550    pParse->nMem = 1;
107551    setOneColumnName(v, "compile_option");
107552    while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
107553      sqlite3VdbeLoadString(v, 1, zOpt);
107554      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
107555    }
107556  }
107557  break;
107558#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
107559
107560#ifndef SQLITE_OMIT_WAL
107561  /*
107562  **   PRAGMA [database.]wal_checkpoint = passive|full|restart|truncate
107563  **
107564  ** Checkpoint the database.
107565  */
107566  case PragTyp_WAL_CHECKPOINT: {
107567    static const char *azCol[] = { "busy", "log", "checkpointed" };
107568    int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
107569    int eMode = SQLITE_CHECKPOINT_PASSIVE;
107570    if( zRight ){
107571      if( sqlite3StrICmp(zRight, "full")==0 ){
107572        eMode = SQLITE_CHECKPOINT_FULL;
107573      }else if( sqlite3StrICmp(zRight, "restart")==0 ){
107574        eMode = SQLITE_CHECKPOINT_RESTART;
107575      }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
107576        eMode = SQLITE_CHECKPOINT_TRUNCATE;
107577      }
107578    }
107579    setAllColumnNames(v, 3, azCol);  assert( 3==ArraySize(azCol) );
107580    pParse->nMem = 3;
107581    sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
107582    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
107583  }
107584  break;
107585
107586  /*
107587  **   PRAGMA wal_autocheckpoint
107588  **   PRAGMA wal_autocheckpoint = N
107589  **
107590  ** Configure a database connection to automatically checkpoint a database
107591  ** after accumulating N frames in the log. Or query for the current value
107592  ** of N.
107593  */
107594  case PragTyp_WAL_AUTOCHECKPOINT: {
107595    if( zRight ){
107596      sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
107597    }
107598    returnSingleInt(v, "wal_autocheckpoint",
107599       db->xWalCallback==sqlite3WalDefaultHook ?
107600           SQLITE_PTR_TO_INT(db->pWalArg) : 0);
107601  }
107602  break;
107603#endif
107604
107605  /*
107606  **  PRAGMA shrink_memory
107607  **
107608  ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
107609  ** connection on which it is invoked to free up as much memory as it
107610  ** can, by calling sqlite3_db_release_memory().
107611  */
107612  case PragTyp_SHRINK_MEMORY: {
107613    sqlite3_db_release_memory(db);
107614    break;
107615  }
107616
107617  /*
107618  **   PRAGMA busy_timeout
107619  **   PRAGMA busy_timeout = N
107620  **
107621  ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
107622  ** if one is set.  If no busy handler or a different busy handler is set
107623  ** then 0 is returned.  Setting the busy_timeout to 0 or negative
107624  ** disables the timeout.
107625  */
107626  /*case PragTyp_BUSY_TIMEOUT*/ default: {
107627    assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
107628    if( zRight ){
107629      sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
107630    }
107631    returnSingleInt(v, "timeout",  db->busyTimeout);
107632    break;
107633  }
107634
107635  /*
107636  **   PRAGMA soft_heap_limit
107637  **   PRAGMA soft_heap_limit = N
107638  **
107639  ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
107640  ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
107641  ** specified and is a non-negative integer.
107642  ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
107643  ** returns the same integer that would be returned by the
107644  ** sqlite3_soft_heap_limit64(-1) C-language function.
107645  */
107646  case PragTyp_SOFT_HEAP_LIMIT: {
107647    sqlite3_int64 N;
107648    if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
107649      sqlite3_soft_heap_limit64(N);
107650    }
107651    returnSingleInt(v, "soft_heap_limit",  sqlite3_soft_heap_limit64(-1));
107652    break;
107653  }
107654
107655  /*
107656  **   PRAGMA threads
107657  **   PRAGMA threads = N
107658  **
107659  ** Configure the maximum number of worker threads.  Return the new
107660  ** maximum, which might be less than requested.
107661  */
107662  case PragTyp_THREADS: {
107663    sqlite3_int64 N;
107664    if( zRight
107665     && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
107666     && N>=0
107667    ){
107668      sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
107669    }
107670    returnSingleInt(v, "threads",
107671                    sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
107672    break;
107673  }
107674
107675#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
107676  /*
107677  ** Report the current state of file logs for all databases
107678  */
107679  case PragTyp_LOCK_STATUS: {
107680    static const char *const azLockName[] = {
107681      "unlocked", "shared", "reserved", "pending", "exclusive"
107682    };
107683    static const char *azCol[] = { "database", "status" };
107684    int i;
107685    setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
107686    pParse->nMem = 2;
107687    for(i=0; i<db->nDb; i++){
107688      Btree *pBt;
107689      const char *zState = "unknown";
107690      int j;
107691      if( db->aDb[i].zName==0 ) continue;
107692      pBt = db->aDb[i].pBt;
107693      if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
107694        zState = "closed";
107695      }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
107696                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
107697         zState = azLockName[j];
107698      }
107699      sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zName, zState);
107700      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
107701    }
107702    break;
107703  }
107704#endif
107705
107706#ifdef SQLITE_HAS_CODEC
107707  case PragTyp_KEY: {
107708    if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
107709    break;
107710  }
107711  case PragTyp_REKEY: {
107712    if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
107713    break;
107714  }
107715  case PragTyp_HEXKEY: {
107716    if( zRight ){
107717      u8 iByte;
107718      int i;
107719      char zKey[40];
107720      for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
107721        iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
107722        if( (i&1)!=0 ) zKey[i/2] = iByte;
107723      }
107724      if( (zLeft[3] & 0xf)==0xb ){
107725        sqlite3_key_v2(db, zDb, zKey, i/2);
107726      }else{
107727        sqlite3_rekey_v2(db, zDb, zKey, i/2);
107728      }
107729    }
107730    break;
107731  }
107732#endif
107733#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
107734  case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
107735#ifdef SQLITE_HAS_CODEC
107736    if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
107737      sqlite3_activate_see(&zRight[4]);
107738    }
107739#endif
107740#ifdef SQLITE_ENABLE_CEROD
107741    if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
107742      sqlite3_activate_cerod(&zRight[6]);
107743    }
107744#endif
107745  }
107746  break;
107747#endif
107748
107749  } /* End of the PRAGMA switch */
107750
107751pragma_out:
107752  sqlite3DbFree(db, zLeft);
107753  sqlite3DbFree(db, zRight);
107754}
107755
107756#endif /* SQLITE_OMIT_PRAGMA */
107757
107758/************** End of pragma.c **********************************************/
107759/************** Begin file prepare.c *****************************************/
107760/*
107761** 2005 May 25
107762**
107763** The author disclaims copyright to this source code.  In place of
107764** a legal notice, here is a blessing:
107765**
107766**    May you do good and not evil.
107767**    May you find forgiveness for yourself and forgive others.
107768**    May you share freely, never taking more than you give.
107769**
107770*************************************************************************
107771** This file contains the implementation of the sqlite3_prepare()
107772** interface, and routines that contribute to loading the database schema
107773** from disk.
107774*/
107775/* #include "sqliteInt.h" */
107776
107777/*
107778** Fill the InitData structure with an error message that indicates
107779** that the database is corrupt.
107780*/
107781static void corruptSchema(
107782  InitData *pData,     /* Initialization context */
107783  const char *zObj,    /* Object being parsed at the point of error */
107784  const char *zExtra   /* Error information */
107785){
107786  sqlite3 *db = pData->db;
107787  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
107788    char *z;
107789    if( zObj==0 ) zObj = "?";
107790    z = sqlite3_mprintf("malformed database schema (%s)", zObj);
107791    if( z && zExtra ) z = sqlite3_mprintf("%z - %s", z, zExtra);
107792    sqlite3DbFree(db, *pData->pzErrMsg);
107793    *pData->pzErrMsg = z;
107794    if( z==0 ) db->mallocFailed = 1;
107795  }
107796  pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
107797}
107798
107799/*
107800** This is the callback routine for the code that initializes the
107801** database.  See sqlite3Init() below for additional information.
107802** This routine is also called from the OP_ParseSchema opcode of the VDBE.
107803**
107804** Each callback contains the following information:
107805**
107806**     argv[0] = name of thing being created
107807**     argv[1] = root page number for table or index. 0 for trigger or view.
107808**     argv[2] = SQL text for the CREATE statement.
107809**
107810*/
107811SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
107812  InitData *pData = (InitData*)pInit;
107813  sqlite3 *db = pData->db;
107814  int iDb = pData->iDb;
107815
107816  assert( argc==3 );
107817  UNUSED_PARAMETER2(NotUsed, argc);
107818  assert( sqlite3_mutex_held(db->mutex) );
107819  DbClearProperty(db, iDb, DB_Empty);
107820  if( db->mallocFailed ){
107821    corruptSchema(pData, argv[0], 0);
107822    return 1;
107823  }
107824
107825  assert( iDb>=0 && iDb<db->nDb );
107826  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
107827  if( argv[1]==0 ){
107828    corruptSchema(pData, argv[0], 0);
107829  }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
107830    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
107831    ** But because db->init.busy is set to 1, no VDBE code is generated
107832    ** or executed.  All the parser does is build the internal data
107833    ** structures that describe the table, index, or view.
107834    */
107835    int rc;
107836    sqlite3_stmt *pStmt;
107837    TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
107838
107839    assert( db->init.busy );
107840    db->init.iDb = iDb;
107841    db->init.newTnum = sqlite3Atoi(argv[1]);
107842    db->init.orphanTrigger = 0;
107843    TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
107844    rc = db->errCode;
107845    assert( (rc&0xFF)==(rcp&0xFF) );
107846    db->init.iDb = 0;
107847    if( SQLITE_OK!=rc ){
107848      if( db->init.orphanTrigger ){
107849        assert( iDb==1 );
107850      }else{
107851        pData->rc = rc;
107852        if( rc==SQLITE_NOMEM ){
107853          db->mallocFailed = 1;
107854        }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
107855          corruptSchema(pData, argv[0], sqlite3_errmsg(db));
107856        }
107857      }
107858    }
107859    sqlite3_finalize(pStmt);
107860  }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
107861    corruptSchema(pData, argv[0], 0);
107862  }else{
107863    /* If the SQL column is blank it means this is an index that
107864    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
107865    ** constraint for a CREATE TABLE.  The index should have already
107866    ** been created when we processed the CREATE TABLE.  All we have
107867    ** to do here is record the root page number for that index.
107868    */
107869    Index *pIndex;
107870    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
107871    if( pIndex==0 ){
107872      /* This can occur if there exists an index on a TEMP table which
107873      ** has the same name as another index on a permanent index.  Since
107874      ** the permanent table is hidden by the TEMP table, we can also
107875      ** safely ignore the index on the permanent table.
107876      */
107877      /* Do Nothing */;
107878    }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
107879      corruptSchema(pData, argv[0], "invalid rootpage");
107880    }
107881  }
107882  return 0;
107883}
107884
107885/*
107886** Attempt to read the database schema and initialize internal
107887** data structures for a single database file.  The index of the
107888** database file is given by iDb.  iDb==0 is used for the main
107889** database.  iDb==1 should never be used.  iDb>=2 is used for
107890** auxiliary databases.  Return one of the SQLITE_ error codes to
107891** indicate success or failure.
107892*/
107893static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
107894  int rc;
107895  int i;
107896#ifndef SQLITE_OMIT_DEPRECATED
107897  int size;
107898#endif
107899  Table *pTab;
107900  Db *pDb;
107901  char const *azArg[4];
107902  int meta[5];
107903  InitData initData;
107904  char const *zMasterSchema;
107905  char const *zMasterName;
107906  int openedTransaction = 0;
107907
107908  /*
107909  ** The master database table has a structure like this
107910  */
107911  static const char master_schema[] =
107912     "CREATE TABLE sqlite_master(\n"
107913     "  type text,\n"
107914     "  name text,\n"
107915     "  tbl_name text,\n"
107916     "  rootpage integer,\n"
107917     "  sql text\n"
107918     ")"
107919  ;
107920#ifndef SQLITE_OMIT_TEMPDB
107921  static const char temp_master_schema[] =
107922     "CREATE TEMP TABLE sqlite_temp_master(\n"
107923     "  type text,\n"
107924     "  name text,\n"
107925     "  tbl_name text,\n"
107926     "  rootpage integer,\n"
107927     "  sql text\n"
107928     ")"
107929  ;
107930#else
107931  #define temp_master_schema 0
107932#endif
107933
107934  assert( iDb>=0 && iDb<db->nDb );
107935  assert( db->aDb[iDb].pSchema );
107936  assert( sqlite3_mutex_held(db->mutex) );
107937  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
107938
107939  /* zMasterSchema and zInitScript are set to point at the master schema
107940  ** and initialisation script appropriate for the database being
107941  ** initialized. zMasterName is the name of the master table.
107942  */
107943  if( !OMIT_TEMPDB && iDb==1 ){
107944    zMasterSchema = temp_master_schema;
107945  }else{
107946    zMasterSchema = master_schema;
107947  }
107948  zMasterName = SCHEMA_TABLE(iDb);
107949
107950  /* Construct the schema tables.  */
107951  azArg[0] = zMasterName;
107952  azArg[1] = "1";
107953  azArg[2] = zMasterSchema;
107954  azArg[3] = 0;
107955  initData.db = db;
107956  initData.iDb = iDb;
107957  initData.rc = SQLITE_OK;
107958  initData.pzErrMsg = pzErrMsg;
107959  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
107960  if( initData.rc ){
107961    rc = initData.rc;
107962    goto error_out;
107963  }
107964  pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
107965  if( ALWAYS(pTab) ){
107966    pTab->tabFlags |= TF_Readonly;
107967  }
107968
107969  /* Create a cursor to hold the database open
107970  */
107971  pDb = &db->aDb[iDb];
107972  if( pDb->pBt==0 ){
107973    if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
107974      DbSetProperty(db, 1, DB_SchemaLoaded);
107975    }
107976    return SQLITE_OK;
107977  }
107978
107979  /* If there is not already a read-only (or read-write) transaction opened
107980  ** on the b-tree database, open one now. If a transaction is opened, it
107981  ** will be closed before this function returns.  */
107982  sqlite3BtreeEnter(pDb->pBt);
107983  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
107984    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
107985    if( rc!=SQLITE_OK ){
107986      sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
107987      goto initone_error_out;
107988    }
107989    openedTransaction = 1;
107990  }
107991
107992  /* Get the database meta information.
107993  **
107994  ** Meta values are as follows:
107995  **    meta[0]   Schema cookie.  Changes with each schema change.
107996  **    meta[1]   File format of schema layer.
107997  **    meta[2]   Size of the page cache.
107998  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
107999  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
108000  **    meta[5]   User version
108001  **    meta[6]   Incremental vacuum mode
108002  **    meta[7]   unused
108003  **    meta[8]   unused
108004  **    meta[9]   unused
108005  **
108006  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
108007  ** the possible values of meta[4].
108008  */
108009  for(i=0; i<ArraySize(meta); i++){
108010    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
108011  }
108012  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
108013
108014  /* If opening a non-empty database, check the text encoding. For the
108015  ** main database, set sqlite3.enc to the encoding of the main database.
108016  ** For an attached db, it is an error if the encoding is not the same
108017  ** as sqlite3.enc.
108018  */
108019  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
108020    if( iDb==0 ){
108021#ifndef SQLITE_OMIT_UTF16
108022      u8 encoding;
108023      /* If opening the main database, set ENC(db). */
108024      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
108025      if( encoding==0 ) encoding = SQLITE_UTF8;
108026      ENC(db) = encoding;
108027#else
108028      ENC(db) = SQLITE_UTF8;
108029#endif
108030    }else{
108031      /* If opening an attached database, the encoding much match ENC(db) */
108032      if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
108033        sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
108034            " text encoding as main database");
108035        rc = SQLITE_ERROR;
108036        goto initone_error_out;
108037      }
108038    }
108039  }else{
108040    DbSetProperty(db, iDb, DB_Empty);
108041  }
108042  pDb->pSchema->enc = ENC(db);
108043
108044  if( pDb->pSchema->cache_size==0 ){
108045#ifndef SQLITE_OMIT_DEPRECATED
108046    size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
108047    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
108048    pDb->pSchema->cache_size = size;
108049#else
108050    pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
108051#endif
108052    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
108053  }
108054
108055  /*
108056  ** file_format==1    Version 3.0.0.
108057  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
108058  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
108059  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
108060  */
108061  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
108062  if( pDb->pSchema->file_format==0 ){
108063    pDb->pSchema->file_format = 1;
108064  }
108065  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
108066    sqlite3SetString(pzErrMsg, db, "unsupported file format");
108067    rc = SQLITE_CORRUPT_BKPT; // Android Change from "rc = SQLITE_ERROR;"
108068    goto initone_error_out;
108069  }
108070
108071  /* Ticket #2804:  When we open a database in the newer file format,
108072  ** clear the legacy_file_format pragma flag so that a VACUUM will
108073  ** not downgrade the database and thus invalidate any descending
108074  ** indices that the user might have created.
108075  */
108076  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
108077    db->flags &= ~SQLITE_LegacyFileFmt;
108078  }
108079
108080  /* Read the schema information out of the schema tables
108081  */
108082  assert( db->init.busy );
108083  {
108084    char *zSql;
108085    zSql = sqlite3MPrintf(db,
108086        "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
108087        db->aDb[iDb].zName, zMasterName);
108088#ifndef SQLITE_OMIT_AUTHORIZATION
108089    {
108090      sqlite3_xauth xAuth;
108091      xAuth = db->xAuth;
108092      db->xAuth = 0;
108093#endif
108094      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
108095#ifndef SQLITE_OMIT_AUTHORIZATION
108096      db->xAuth = xAuth;
108097    }
108098#endif
108099    if( rc==SQLITE_OK ) rc = initData.rc;
108100    sqlite3DbFree(db, zSql);
108101#ifndef SQLITE_OMIT_ANALYZE
108102    if( rc==SQLITE_OK ){
108103      sqlite3AnalysisLoad(db, iDb);
108104    }
108105#endif
108106  }
108107  if( db->mallocFailed ){
108108    rc = SQLITE_NOMEM;
108109    sqlite3ResetAllSchemasOfConnection(db);
108110  }
108111  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
108112    /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
108113    ** the schema loaded, even if errors occurred. In this situation the
108114    ** current sqlite3_prepare() operation will fail, but the following one
108115    ** will attempt to compile the supplied statement against whatever subset
108116    ** of the schema was loaded before the error occurred. The primary
108117    ** purpose of this is to allow access to the sqlite_master table
108118    ** even when its contents have been corrupted.
108119    */
108120    DbSetProperty(db, iDb, DB_SchemaLoaded);
108121    rc = SQLITE_OK;
108122  }
108123
108124  /* Jump here for an error that occurs after successfully allocating
108125  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
108126  ** before that point, jump to error_out.
108127  */
108128initone_error_out:
108129  if( openedTransaction ){
108130    sqlite3BtreeCommit(pDb->pBt);
108131  }
108132  sqlite3BtreeLeave(pDb->pBt);
108133
108134error_out:
108135  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
108136    db->mallocFailed = 1;
108137  }
108138  return rc;
108139}
108140
108141/*
108142** Initialize all database files - the main database file, the file
108143** used to store temporary tables, and any additional database files
108144** created using ATTACH statements.  Return a success code.  If an
108145** error occurs, write an error message into *pzErrMsg.
108146**
108147** After a database is initialized, the DB_SchemaLoaded bit is set
108148** bit is set in the flags field of the Db structure. If the database
108149** file was of zero-length, then the DB_Empty flag is also set.
108150*/
108151SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
108152  int i, rc;
108153  int commit_internal = !(db->flags&SQLITE_InternChanges);
108154
108155  assert( sqlite3_mutex_held(db->mutex) );
108156  assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
108157  assert( db->init.busy==0 );
108158  rc = SQLITE_OK;
108159  db->init.busy = 1;
108160  ENC(db) = SCHEMA_ENC(db);
108161  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
108162    if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
108163    rc = sqlite3InitOne(db, i, pzErrMsg);
108164    if( rc ){
108165      sqlite3ResetOneSchema(db, i);
108166    }
108167  }
108168
108169  /* Once all the other databases have been initialized, load the schema
108170  ** for the TEMP database. This is loaded last, as the TEMP database
108171  ** schema may contain references to objects in other databases.
108172  */
108173#ifndef SQLITE_OMIT_TEMPDB
108174  assert( db->nDb>1 );
108175  if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
108176    rc = sqlite3InitOne(db, 1, pzErrMsg);
108177    if( rc ){
108178      sqlite3ResetOneSchema(db, 1);
108179    }
108180  }
108181#endif
108182
108183  db->init.busy = 0;
108184  if( rc==SQLITE_OK && commit_internal ){
108185    sqlite3CommitInternalChanges(db);
108186  }
108187
108188  return rc;
108189}
108190
108191/*
108192** This routine is a no-op if the database schema is already initialized.
108193** Otherwise, the schema is loaded. An error code is returned.
108194*/
108195SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
108196  int rc = SQLITE_OK;
108197  sqlite3 *db = pParse->db;
108198  assert( sqlite3_mutex_held(db->mutex) );
108199  if( !db->init.busy ){
108200    rc = sqlite3Init(db, &pParse->zErrMsg);
108201  }
108202  if( rc!=SQLITE_OK ){
108203    pParse->rc = rc;
108204    pParse->nErr++;
108205  }
108206  return rc;
108207}
108208
108209
108210/*
108211** Check schema cookies in all databases.  If any cookie is out
108212** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
108213** make no changes to pParse->rc.
108214*/
108215static void schemaIsValid(Parse *pParse){
108216  sqlite3 *db = pParse->db;
108217  int iDb;
108218  int rc;
108219  int cookie;
108220
108221  assert( pParse->checkSchema );
108222  assert( sqlite3_mutex_held(db->mutex) );
108223  for(iDb=0; iDb<db->nDb; iDb++){
108224    int openedTransaction = 0;         /* True if a transaction is opened */
108225    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
108226    if( pBt==0 ) continue;
108227
108228    /* If there is not already a read-only (or read-write) transaction opened
108229    ** on the b-tree database, open one now. If a transaction is opened, it
108230    ** will be closed immediately after reading the meta-value. */
108231    if( !sqlite3BtreeIsInReadTrans(pBt) ){
108232      rc = sqlite3BtreeBeginTrans(pBt, 0);
108233      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
108234        db->mallocFailed = 1;
108235      }
108236      if( rc!=SQLITE_OK ) return;
108237      openedTransaction = 1;
108238    }
108239
108240    /* Read the schema cookie from the database. If it does not match the
108241    ** value stored as part of the in-memory schema representation,
108242    ** set Parse.rc to SQLITE_SCHEMA. */
108243    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
108244    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
108245    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
108246      sqlite3ResetOneSchema(db, iDb);
108247      pParse->rc = SQLITE_SCHEMA;
108248    }
108249
108250    /* Close the transaction, if one was opened. */
108251    if( openedTransaction ){
108252      sqlite3BtreeCommit(pBt);
108253    }
108254  }
108255}
108256
108257/*
108258** Convert a schema pointer into the iDb index that indicates
108259** which database file in db->aDb[] the schema refers to.
108260**
108261** If the same database is attached more than once, the first
108262** attached database is returned.
108263*/
108264SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
108265  int i = -1000000;
108266
108267  /* If pSchema is NULL, then return -1000000. This happens when code in
108268  ** expr.c is trying to resolve a reference to a transient table (i.e. one
108269  ** created by a sub-select). In this case the return value of this
108270  ** function should never be used.
108271  **
108272  ** We return -1000000 instead of the more usual -1 simply because using
108273  ** -1000000 as the incorrect index into db->aDb[] is much
108274  ** more likely to cause a segfault than -1 (of course there are assert()
108275  ** statements too, but it never hurts to play the odds).
108276  */
108277  assert( sqlite3_mutex_held(db->mutex) );
108278  if( pSchema ){
108279    for(i=0; ALWAYS(i<db->nDb); i++){
108280      if( db->aDb[i].pSchema==pSchema ){
108281        break;
108282      }
108283    }
108284    assert( i>=0 && i<db->nDb );
108285  }
108286  return i;
108287}
108288
108289/*
108290** Free all memory allocations in the pParse object
108291*/
108292SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
108293  if( pParse ){
108294    sqlite3 *db = pParse->db;
108295    sqlite3DbFree(db, pParse->aLabel);
108296    sqlite3ExprListDelete(db, pParse->pConstExpr);
108297  }
108298}
108299
108300/*
108301** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
108302*/
108303static int sqlite3Prepare(
108304  sqlite3 *db,              /* Database handle. */
108305  const char *zSql,         /* UTF-8 encoded SQL statement. */
108306  int nBytes,               /* Length of zSql in bytes. */
108307  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
108308  Vdbe *pReprepare,         /* VM being reprepared */
108309  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
108310  const char **pzTail       /* OUT: End of parsed string */
108311){
108312  Parse *pParse;            /* Parsing context */
108313  char *zErrMsg = 0;        /* Error message */
108314  int rc = SQLITE_OK;       /* Result code */
108315  int i;                    /* Loop counter */
108316
108317  /* Allocate the parsing context */
108318  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
108319  if( pParse==0 ){
108320    rc = SQLITE_NOMEM;
108321    goto end_prepare;
108322  }
108323  pParse->pReprepare = pReprepare;
108324  assert( ppStmt && *ppStmt==0 );
108325  assert( !db->mallocFailed );
108326  assert( sqlite3_mutex_held(db->mutex) );
108327
108328  /* Check to verify that it is possible to get a read lock on all
108329  ** database schemas.  The inability to get a read lock indicates that
108330  ** some other database connection is holding a write-lock, which in
108331  ** turn means that the other connection has made uncommitted changes
108332  ** to the schema.
108333  **
108334  ** Were we to proceed and prepare the statement against the uncommitted
108335  ** schema changes and if those schema changes are subsequently rolled
108336  ** back and different changes are made in their place, then when this
108337  ** prepared statement goes to run the schema cookie would fail to detect
108338  ** the schema change.  Disaster would follow.
108339  **
108340  ** This thread is currently holding mutexes on all Btrees (because
108341  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
108342  ** is not possible for another thread to start a new schema change
108343  ** while this routine is running.  Hence, we do not need to hold
108344  ** locks on the schema, we just need to make sure nobody else is
108345  ** holding them.
108346  **
108347  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
108348  ** but it does *not* override schema lock detection, so this all still
108349  ** works even if READ_UNCOMMITTED is set.
108350  */
108351  for(i=0; i<db->nDb; i++) {
108352    Btree *pBt = db->aDb[i].pBt;
108353    if( pBt ){
108354      assert( sqlite3BtreeHoldsMutex(pBt) );
108355      rc = sqlite3BtreeSchemaLocked(pBt);
108356      if( rc ){
108357        const char *zDb = db->aDb[i].zName;
108358        sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
108359        testcase( db->flags & SQLITE_ReadUncommitted );
108360        goto end_prepare;
108361      }
108362    }
108363  }
108364
108365  sqlite3VtabUnlockList(db);
108366
108367  pParse->db = db;
108368  pParse->nQueryLoop = 0;  /* Logarithmic, so 0 really means 1 */
108369  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
108370    char *zSqlCopy;
108371    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
108372    testcase( nBytes==mxLen );
108373    testcase( nBytes==mxLen+1 );
108374    if( nBytes>mxLen ){
108375      sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
108376      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
108377      goto end_prepare;
108378    }
108379    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
108380    if( zSqlCopy ){
108381      sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
108382      sqlite3DbFree(db, zSqlCopy);
108383      pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
108384    }else{
108385      pParse->zTail = &zSql[nBytes];
108386    }
108387  }else{
108388    sqlite3RunParser(pParse, zSql, &zErrMsg);
108389  }
108390  assert( 0==pParse->nQueryLoop );
108391
108392  if( db->mallocFailed ){
108393    pParse->rc = SQLITE_NOMEM;
108394  }
108395  if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
108396  if( pParse->checkSchema ){
108397    schemaIsValid(pParse);
108398  }
108399  if( db->mallocFailed ){
108400    pParse->rc = SQLITE_NOMEM;
108401  }
108402  if( pzTail ){
108403    *pzTail = pParse->zTail;
108404  }
108405  rc = pParse->rc;
108406
108407#ifndef SQLITE_OMIT_EXPLAIN
108408  if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
108409    static const char * const azColName[] = {
108410       "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
108411       "selectid", "order", "from", "detail"
108412    };
108413    int iFirst, mx;
108414    if( pParse->explain==2 ){
108415      sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
108416      iFirst = 8;
108417      mx = 12;
108418    }else{
108419      sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
108420      iFirst = 0;
108421      mx = 8;
108422    }
108423    for(i=iFirst; i<mx; i++){
108424      sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
108425                            azColName[i], SQLITE_STATIC);
108426    }
108427  }
108428#endif
108429
108430  if( db->init.busy==0 ){
108431    Vdbe *pVdbe = pParse->pVdbe;
108432    sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
108433  }
108434  if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
108435    sqlite3VdbeFinalize(pParse->pVdbe);
108436    assert(!(*ppStmt));
108437  }else{
108438    *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
108439  }
108440
108441  if( zErrMsg ){
108442    sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
108443    sqlite3DbFree(db, zErrMsg);
108444  }else{
108445    sqlite3Error(db, rc);
108446  }
108447
108448  /* Delete any TriggerPrg structures allocated while parsing this statement. */
108449  while( pParse->pTriggerPrg ){
108450    TriggerPrg *pT = pParse->pTriggerPrg;
108451    pParse->pTriggerPrg = pT->pNext;
108452    sqlite3DbFree(db, pT);
108453  }
108454
108455end_prepare:
108456
108457  sqlite3ParserReset(pParse);
108458  sqlite3StackFree(db, pParse);
108459  rc = sqlite3ApiExit(db, rc);
108460  assert( (rc&db->errMask)==rc );
108461  return rc;
108462}
108463static int sqlite3LockAndPrepare(
108464  sqlite3 *db,              /* Database handle. */
108465  const char *zSql,         /* UTF-8 encoded SQL statement. */
108466  int nBytes,               /* Length of zSql in bytes. */
108467  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
108468  Vdbe *pOld,               /* VM being reprepared */
108469  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
108470  const char **pzTail       /* OUT: End of parsed string */
108471){
108472  int rc;
108473
108474#ifdef SQLITE_ENABLE_API_ARMOR
108475  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
108476#endif
108477  *ppStmt = 0;
108478  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
108479    return SQLITE_MISUSE_BKPT;
108480  }
108481  sqlite3_mutex_enter(db->mutex);
108482  sqlite3BtreeEnterAll(db);
108483  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
108484  if( rc==SQLITE_SCHEMA ){
108485    sqlite3_finalize(*ppStmt);
108486    rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
108487  }
108488  sqlite3BtreeLeaveAll(db);
108489  sqlite3_mutex_leave(db->mutex);
108490  assert( rc==SQLITE_OK || *ppStmt==0 );
108491  return rc;
108492}
108493
108494/*
108495** Rerun the compilation of a statement after a schema change.
108496**
108497** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
108498** if the statement cannot be recompiled because another connection has
108499** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
108500** occurs, return SQLITE_SCHEMA.
108501*/
108502SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
108503  int rc;
108504  sqlite3_stmt *pNew;
108505  const char *zSql;
108506  sqlite3 *db;
108507
108508  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
108509  zSql = sqlite3_sql((sqlite3_stmt *)p);
108510  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
108511  db = sqlite3VdbeDb(p);
108512  assert( sqlite3_mutex_held(db->mutex) );
108513  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
108514  if( rc ){
108515    if( rc==SQLITE_NOMEM ){
108516      db->mallocFailed = 1;
108517    }
108518    assert( pNew==0 );
108519    return rc;
108520  }else{
108521    assert( pNew!=0 );
108522  }
108523  sqlite3VdbeSwap((Vdbe*)pNew, p);
108524  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
108525  sqlite3VdbeResetStepResult((Vdbe*)pNew);
108526  sqlite3VdbeFinalize((Vdbe*)pNew);
108527  return SQLITE_OK;
108528}
108529
108530
108531/*
108532** Two versions of the official API.  Legacy and new use.  In the legacy
108533** version, the original SQL text is not saved in the prepared statement
108534** and so if a schema change occurs, SQLITE_SCHEMA is returned by
108535** sqlite3_step().  In the new version, the original SQL text is retained
108536** and the statement is automatically recompiled if an schema change
108537** occurs.
108538*/
108539SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
108540  sqlite3 *db,              /* Database handle. */
108541  const char *zSql,         /* UTF-8 encoded SQL statement. */
108542  int nBytes,               /* Length of zSql in bytes. */
108543  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
108544  const char **pzTail       /* OUT: End of parsed string */
108545){
108546  int rc;
108547  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
108548  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
108549  return rc;
108550}
108551SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
108552  sqlite3 *db,              /* Database handle. */
108553  const char *zSql,         /* UTF-8 encoded SQL statement. */
108554  int nBytes,               /* Length of zSql in bytes. */
108555  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
108556  const char **pzTail       /* OUT: End of parsed string */
108557){
108558  int rc;
108559  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
108560  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
108561  return rc;
108562}
108563
108564
108565#ifndef SQLITE_OMIT_UTF16
108566/*
108567** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
108568*/
108569static int sqlite3Prepare16(
108570  sqlite3 *db,              /* Database handle. */
108571  const void *zSql,         /* UTF-16 encoded SQL statement. */
108572  int nBytes,               /* Length of zSql in bytes. */
108573  int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
108574  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
108575  const void **pzTail       /* OUT: End of parsed string */
108576){
108577  /* This function currently works by first transforming the UTF-16
108578  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
108579  ** tricky bit is figuring out the pointer to return in *pzTail.
108580  */
108581  char *zSql8;
108582  const char *zTail8 = 0;
108583  int rc = SQLITE_OK;
108584
108585#ifdef SQLITE_ENABLE_API_ARMOR
108586  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
108587#endif
108588  *ppStmt = 0;
108589  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
108590    return SQLITE_MISUSE_BKPT;
108591  }
108592  if( nBytes>=0 ){
108593    int sz;
108594    const char *z = (const char*)zSql;
108595    for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
108596    nBytes = sz;
108597  }
108598  sqlite3_mutex_enter(db->mutex);
108599  zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
108600  if( zSql8 ){
108601    rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
108602  }
108603
108604  if( zTail8 && pzTail ){
108605    /* If sqlite3_prepare returns a tail pointer, we calculate the
108606    ** equivalent pointer into the UTF-16 string by counting the unicode
108607    ** characters between zSql8 and zTail8, and then returning a pointer
108608    ** the same number of characters into the UTF-16 string.
108609    */
108610    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
108611    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
108612  }
108613  sqlite3DbFree(db, zSql8);
108614  rc = sqlite3ApiExit(db, rc);
108615  sqlite3_mutex_leave(db->mutex);
108616  return rc;
108617}
108618
108619/*
108620** Two versions of the official API.  Legacy and new use.  In the legacy
108621** version, the original SQL text is not saved in the prepared statement
108622** and so if a schema change occurs, SQLITE_SCHEMA is returned by
108623** sqlite3_step().  In the new version, the original SQL text is retained
108624** and the statement is automatically recompiled if an schema change
108625** occurs.
108626*/
108627SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
108628  sqlite3 *db,              /* Database handle. */
108629  const void *zSql,         /* UTF-16 encoded SQL statement. */
108630  int nBytes,               /* Length of zSql in bytes. */
108631  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
108632  const void **pzTail       /* OUT: End of parsed string */
108633){
108634  int rc;
108635  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
108636  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
108637  return rc;
108638}
108639SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
108640  sqlite3 *db,              /* Database handle. */
108641  const void *zSql,         /* UTF-16 encoded SQL statement. */
108642  int nBytes,               /* Length of zSql in bytes. */
108643  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
108644  const void **pzTail       /* OUT: End of parsed string */
108645){
108646  int rc;
108647  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
108648  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
108649  return rc;
108650}
108651
108652#endif /* SQLITE_OMIT_UTF16 */
108653
108654/************** End of prepare.c *********************************************/
108655/************** Begin file select.c ******************************************/
108656/*
108657** 2001 September 15
108658**
108659** The author disclaims copyright to this source code.  In place of
108660** a legal notice, here is a blessing:
108661**
108662**    May you do good and not evil.
108663**    May you find forgiveness for yourself and forgive others.
108664**    May you share freely, never taking more than you give.
108665**
108666*************************************************************************
108667** This file contains C code routines that are called by the parser
108668** to handle SELECT statements in SQLite.
108669*/
108670/* #include "sqliteInt.h" */
108671
108672/*
108673** Trace output macros
108674*/
108675#if SELECTTRACE_ENABLED
108676/***/ int sqlite3SelectTrace = 0;
108677# define SELECTTRACE(K,P,S,X)  \
108678  if(sqlite3SelectTrace&(K))   \
108679    sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
108680        (S)->zSelName,(S)),\
108681    sqlite3DebugPrintf X
108682#else
108683# define SELECTTRACE(K,P,S,X)
108684#endif
108685
108686
108687/*
108688** An instance of the following object is used to record information about
108689** how to process the DISTINCT keyword, to simplify passing that information
108690** into the selectInnerLoop() routine.
108691*/
108692typedef struct DistinctCtx DistinctCtx;
108693struct DistinctCtx {
108694  u8 isTnct;      /* True if the DISTINCT keyword is present */
108695  u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
108696  int tabTnct;    /* Ephemeral table used for DISTINCT processing */
108697  int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
108698};
108699
108700/*
108701** An instance of the following object is used to record information about
108702** the ORDER BY (or GROUP BY) clause of query is being coded.
108703*/
108704typedef struct SortCtx SortCtx;
108705struct SortCtx {
108706  ExprList *pOrderBy;   /* The ORDER BY (or GROUP BY clause) */
108707  int nOBSat;           /* Number of ORDER BY terms satisfied by indices */
108708  int iECursor;         /* Cursor number for the sorter */
108709  int regReturn;        /* Register holding block-output return address */
108710  int labelBkOut;       /* Start label for the block-output subroutine */
108711  int addrSortIndex;    /* Address of the OP_SorterOpen or OP_OpenEphemeral */
108712  u8 sortFlags;         /* Zero or more SORTFLAG_* bits */
108713};
108714#define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */
108715
108716/*
108717** Delete all the content of a Select structure.  Deallocate the structure
108718** itself only if bFree is true.
108719*/
108720static void clearSelect(sqlite3 *db, Select *p, int bFree){
108721  while( p ){
108722    Select *pPrior = p->pPrior;
108723    sqlite3ExprListDelete(db, p->pEList);
108724    sqlite3SrcListDelete(db, p->pSrc);
108725    sqlite3ExprDelete(db, p->pWhere);
108726    sqlite3ExprListDelete(db, p->pGroupBy);
108727    sqlite3ExprDelete(db, p->pHaving);
108728    sqlite3ExprListDelete(db, p->pOrderBy);
108729    sqlite3ExprDelete(db, p->pLimit);
108730    sqlite3ExprDelete(db, p->pOffset);
108731    sqlite3WithDelete(db, p->pWith);
108732    if( bFree ) sqlite3DbFree(db, p);
108733    p = pPrior;
108734    bFree = 1;
108735  }
108736}
108737
108738/*
108739** Initialize a SelectDest structure.
108740*/
108741SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
108742  pDest->eDest = (u8)eDest;
108743  pDest->iSDParm = iParm;
108744  pDest->affSdst = 0;
108745  pDest->iSdst = 0;
108746  pDest->nSdst = 0;
108747}
108748
108749
108750/*
108751** Allocate a new Select structure and return a pointer to that
108752** structure.
108753*/
108754SQLITE_PRIVATE Select *sqlite3SelectNew(
108755  Parse *pParse,        /* Parsing context */
108756  ExprList *pEList,     /* which columns to include in the result */
108757  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
108758  Expr *pWhere,         /* the WHERE clause */
108759  ExprList *pGroupBy,   /* the GROUP BY clause */
108760  Expr *pHaving,        /* the HAVING clause */
108761  ExprList *pOrderBy,   /* the ORDER BY clause */
108762  u16 selFlags,         /* Flag parameters, such as SF_Distinct */
108763  Expr *pLimit,         /* LIMIT value.  NULL means not used */
108764  Expr *pOffset         /* OFFSET value.  NULL means no offset */
108765){
108766  Select *pNew;
108767  Select standin;
108768  sqlite3 *db = pParse->db;
108769  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
108770  if( pNew==0 ){
108771    assert( db->mallocFailed );
108772    pNew = &standin;
108773    memset(pNew, 0, sizeof(*pNew));
108774  }
108775  if( pEList==0 ){
108776    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
108777  }
108778  pNew->pEList = pEList;
108779  if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
108780  pNew->pSrc = pSrc;
108781  pNew->pWhere = pWhere;
108782  pNew->pGroupBy = pGroupBy;
108783  pNew->pHaving = pHaving;
108784  pNew->pOrderBy = pOrderBy;
108785  pNew->selFlags = selFlags;
108786  pNew->op = TK_SELECT;
108787  pNew->pLimit = pLimit;
108788  pNew->pOffset = pOffset;
108789  assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 );
108790  pNew->addrOpenEphm[0] = -1;
108791  pNew->addrOpenEphm[1] = -1;
108792  if( db->mallocFailed ) {
108793    clearSelect(db, pNew, pNew!=&standin);
108794    pNew = 0;
108795  }else{
108796    assert( pNew->pSrc!=0 || pParse->nErr>0 );
108797  }
108798  assert( pNew!=&standin );
108799  return pNew;
108800}
108801
108802#if SELECTTRACE_ENABLED
108803/*
108804** Set the name of a Select object
108805*/
108806SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
108807  if( p && zName ){
108808    sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
108809  }
108810}
108811#endif
108812
108813
108814/*
108815** Delete the given Select structure and all of its substructures.
108816*/
108817SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
108818  clearSelect(db, p, 1);
108819}
108820
108821/*
108822** Return a pointer to the right-most SELECT statement in a compound.
108823*/
108824static Select *findRightmost(Select *p){
108825  while( p->pNext ) p = p->pNext;
108826  return p;
108827}
108828
108829/*
108830** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
108831** type of join.  Return an integer constant that expresses that type
108832** in terms of the following bit values:
108833**
108834**     JT_INNER
108835**     JT_CROSS
108836**     JT_OUTER
108837**     JT_NATURAL
108838**     JT_LEFT
108839**     JT_RIGHT
108840**
108841** A full outer join is the combination of JT_LEFT and JT_RIGHT.
108842**
108843** If an illegal or unsupported join type is seen, then still return
108844** a join type, but put an error in the pParse structure.
108845*/
108846SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
108847  int jointype = 0;
108848  Token *apAll[3];
108849  Token *p;
108850                             /*   0123456789 123456789 123456789 123 */
108851  static const char zKeyText[] = "naturaleftouterightfullinnercross";
108852  static const struct {
108853    u8 i;        /* Beginning of keyword text in zKeyText[] */
108854    u8 nChar;    /* Length of the keyword in characters */
108855    u8 code;     /* Join type mask */
108856  } aKeyword[] = {
108857    /* natural */ { 0,  7, JT_NATURAL                },
108858    /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
108859    /* outer   */ { 10, 5, JT_OUTER                  },
108860    /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
108861    /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
108862    /* inner   */ { 23, 5, JT_INNER                  },
108863    /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
108864  };
108865  int i, j;
108866  apAll[0] = pA;
108867  apAll[1] = pB;
108868  apAll[2] = pC;
108869  for(i=0; i<3 && apAll[i]; i++){
108870    p = apAll[i];
108871    for(j=0; j<ArraySize(aKeyword); j++){
108872      if( p->n==aKeyword[j].nChar
108873          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
108874        jointype |= aKeyword[j].code;
108875        break;
108876      }
108877    }
108878    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
108879    if( j>=ArraySize(aKeyword) ){
108880      jointype |= JT_ERROR;
108881      break;
108882    }
108883  }
108884  if(
108885     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
108886     (jointype & JT_ERROR)!=0
108887  ){
108888    const char *zSp = " ";
108889    assert( pB!=0 );
108890    if( pC==0 ){ zSp++; }
108891    sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
108892       "%T %T%s%T", pA, pB, zSp, pC);
108893    jointype = JT_INNER;
108894  }else if( (jointype & JT_OUTER)!=0
108895         && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
108896    sqlite3ErrorMsg(pParse,
108897      "RIGHT and FULL OUTER JOINs are not currently supported");
108898    jointype = JT_INNER;
108899  }
108900  return jointype;
108901}
108902
108903/*
108904** Return the index of a column in a table.  Return -1 if the column
108905** is not contained in the table.
108906*/
108907static int columnIndex(Table *pTab, const char *zCol){
108908  int i;
108909  for(i=0; i<pTab->nCol; i++){
108910    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
108911  }
108912  return -1;
108913}
108914
108915/*
108916** Search the first N tables in pSrc, from left to right, looking for a
108917** table that has a column named zCol.
108918**
108919** When found, set *piTab and *piCol to the table index and column index
108920** of the matching column and return TRUE.
108921**
108922** If not found, return FALSE.
108923*/
108924static int tableAndColumnIndex(
108925  SrcList *pSrc,       /* Array of tables to search */
108926  int N,               /* Number of tables in pSrc->a[] to search */
108927  const char *zCol,    /* Name of the column we are looking for */
108928  int *piTab,          /* Write index of pSrc->a[] here */
108929  int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
108930){
108931  int i;               /* For looping over tables in pSrc */
108932  int iCol;            /* Index of column matching zCol */
108933
108934  assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
108935  for(i=0; i<N; i++){
108936    iCol = columnIndex(pSrc->a[i].pTab, zCol);
108937    if( iCol>=0 ){
108938      if( piTab ){
108939        *piTab = i;
108940        *piCol = iCol;
108941      }
108942      return 1;
108943    }
108944  }
108945  return 0;
108946}
108947
108948/*
108949** This function is used to add terms implied by JOIN syntax to the
108950** WHERE clause expression of a SELECT statement. The new term, which
108951** is ANDed with the existing WHERE clause, is of the form:
108952**
108953**    (tab1.col1 = tab2.col2)
108954**
108955** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
108956** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
108957** column iColRight of tab2.
108958*/
108959static void addWhereTerm(
108960  Parse *pParse,                  /* Parsing context */
108961  SrcList *pSrc,                  /* List of tables in FROM clause */
108962  int iLeft,                      /* Index of first table to join in pSrc */
108963  int iColLeft,                   /* Index of column in first table */
108964  int iRight,                     /* Index of second table in pSrc */
108965  int iColRight,                  /* Index of column in second table */
108966  int isOuterJoin,                /* True if this is an OUTER join */
108967  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
108968){
108969  sqlite3 *db = pParse->db;
108970  Expr *pE1;
108971  Expr *pE2;
108972  Expr *pEq;
108973
108974  assert( iLeft<iRight );
108975  assert( pSrc->nSrc>iRight );
108976  assert( pSrc->a[iLeft].pTab );
108977  assert( pSrc->a[iRight].pTab );
108978
108979  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
108980  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
108981
108982  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
108983  if( pEq && isOuterJoin ){
108984    ExprSetProperty(pEq, EP_FromJoin);
108985    assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
108986    ExprSetVVAProperty(pEq, EP_NoReduce);
108987    pEq->iRightJoinTable = (i16)pE2->iTable;
108988  }
108989  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
108990}
108991
108992/*
108993** Set the EP_FromJoin property on all terms of the given expression.
108994** And set the Expr.iRightJoinTable to iTable for every term in the
108995** expression.
108996**
108997** The EP_FromJoin property is used on terms of an expression to tell
108998** the LEFT OUTER JOIN processing logic that this term is part of the
108999** join restriction specified in the ON or USING clause and not a part
109000** of the more general WHERE clause.  These terms are moved over to the
109001** WHERE clause during join processing but we need to remember that they
109002** originated in the ON or USING clause.
109003**
109004** The Expr.iRightJoinTable tells the WHERE clause processing that the
109005** expression depends on table iRightJoinTable even if that table is not
109006** explicitly mentioned in the expression.  That information is needed
109007** for cases like this:
109008**
109009**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
109010**
109011** The where clause needs to defer the handling of the t1.x=5
109012** term until after the t2 loop of the join.  In that way, a
109013** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
109014** defer the handling of t1.x=5, it will be processed immediately
109015** after the t1 loop and rows with t1.x!=5 will never appear in
109016** the output, which is incorrect.
109017*/
109018static void setJoinExpr(Expr *p, int iTable){
109019  while( p ){
109020    ExprSetProperty(p, EP_FromJoin);
109021    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
109022    ExprSetVVAProperty(p, EP_NoReduce);
109023    p->iRightJoinTable = (i16)iTable;
109024    if( p->op==TK_FUNCTION && p->x.pList ){
109025      int i;
109026      for(i=0; i<p->x.pList->nExpr; i++){
109027        setJoinExpr(p->x.pList->a[i].pExpr, iTable);
109028      }
109029    }
109030    setJoinExpr(p->pLeft, iTable);
109031    p = p->pRight;
109032  }
109033}
109034
109035/*
109036** This routine processes the join information for a SELECT statement.
109037** ON and USING clauses are converted into extra terms of the WHERE clause.
109038** NATURAL joins also create extra WHERE clause terms.
109039**
109040** The terms of a FROM clause are contained in the Select.pSrc structure.
109041** The left most table is the first entry in Select.pSrc.  The right-most
109042** table is the last entry.  The join operator is held in the entry to
109043** the left.  Thus entry 0 contains the join operator for the join between
109044** entries 0 and 1.  Any ON or USING clauses associated with the join are
109045** also attached to the left entry.
109046**
109047** This routine returns the number of errors encountered.
109048*/
109049static int sqliteProcessJoin(Parse *pParse, Select *p){
109050  SrcList *pSrc;                  /* All tables in the FROM clause */
109051  int i, j;                       /* Loop counters */
109052  struct SrcList_item *pLeft;     /* Left table being joined */
109053  struct SrcList_item *pRight;    /* Right table being joined */
109054
109055  pSrc = p->pSrc;
109056  pLeft = &pSrc->a[0];
109057  pRight = &pLeft[1];
109058  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
109059    Table *pLeftTab = pLeft->pTab;
109060    Table *pRightTab = pRight->pTab;
109061    int isOuter;
109062
109063    if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
109064    isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
109065
109066    /* When the NATURAL keyword is present, add WHERE clause terms for
109067    ** every column that the two tables have in common.
109068    */
109069    if( pRight->fg.jointype & JT_NATURAL ){
109070      if( pRight->pOn || pRight->pUsing ){
109071        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
109072           "an ON or USING clause", 0);
109073        return 1;
109074      }
109075      for(j=0; j<pRightTab->nCol; j++){
109076        char *zName;   /* Name of column in the right table */
109077        int iLeft;     /* Matching left table */
109078        int iLeftCol;  /* Matching column in the left table */
109079
109080        zName = pRightTab->aCol[j].zName;
109081        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
109082          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
109083                       isOuter, &p->pWhere);
109084        }
109085      }
109086    }
109087
109088    /* Disallow both ON and USING clauses in the same join
109089    */
109090    if( pRight->pOn && pRight->pUsing ){
109091      sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
109092        "clauses in the same join");
109093      return 1;
109094    }
109095
109096    /* Add the ON clause to the end of the WHERE clause, connected by
109097    ** an AND operator.
109098    */
109099    if( pRight->pOn ){
109100      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
109101      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
109102      pRight->pOn = 0;
109103    }
109104
109105    /* Create extra terms on the WHERE clause for each column named
109106    ** in the USING clause.  Example: If the two tables to be joined are
109107    ** A and B and the USING clause names X, Y, and Z, then add this
109108    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
109109    ** Report an error if any column mentioned in the USING clause is
109110    ** not contained in both tables to be joined.
109111    */
109112    if( pRight->pUsing ){
109113      IdList *pList = pRight->pUsing;
109114      for(j=0; j<pList->nId; j++){
109115        char *zName;     /* Name of the term in the USING clause */
109116        int iLeft;       /* Table on the left with matching column name */
109117        int iLeftCol;    /* Column number of matching column on the left */
109118        int iRightCol;   /* Column number of matching column on the right */
109119
109120        zName = pList->a[j].zName;
109121        iRightCol = columnIndex(pRightTab, zName);
109122        if( iRightCol<0
109123         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
109124        ){
109125          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
109126            "not present in both tables", zName);
109127          return 1;
109128        }
109129        addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
109130                     isOuter, &p->pWhere);
109131      }
109132    }
109133  }
109134  return 0;
109135}
109136
109137/* Forward reference */
109138static KeyInfo *keyInfoFromExprList(
109139  Parse *pParse,       /* Parsing context */
109140  ExprList *pList,     /* Form the KeyInfo object from this ExprList */
109141  int iStart,          /* Begin with this column of pList */
109142  int nExtra           /* Add this many extra columns to the end */
109143);
109144
109145/*
109146** Generate code that will push the record in registers regData
109147** through regData+nData-1 onto the sorter.
109148*/
109149static void pushOntoSorter(
109150  Parse *pParse,         /* Parser context */
109151  SortCtx *pSort,        /* Information about the ORDER BY clause */
109152  Select *pSelect,       /* The whole SELECT statement */
109153  int regData,           /* First register holding data to be sorted */
109154  int regOrigData,       /* First register holding data before packing */
109155  int nData,             /* Number of elements in the data array */
109156  int nPrefixReg         /* No. of reg prior to regData available for use */
109157){
109158  Vdbe *v = pParse->pVdbe;                         /* Stmt under construction */
109159  int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
109160  int nExpr = pSort->pOrderBy->nExpr;              /* No. of ORDER BY terms */
109161  int nBase = nExpr + bSeq + nData;                /* Fields in sorter record */
109162  int regBase;                                     /* Regs for sorter record */
109163  int regRecord = ++pParse->nMem;                  /* Assembled sorter record */
109164  int nOBSat = pSort->nOBSat;                      /* ORDER BY terms to skip */
109165  int op;                            /* Opcode to add sorter record to sorter */
109166
109167  assert( bSeq==0 || bSeq==1 );
109168  assert( nData==1 || regData==regOrigData );
109169  if( nPrefixReg ){
109170    assert( nPrefixReg==nExpr+bSeq );
109171    regBase = regData - nExpr - bSeq;
109172  }else{
109173    regBase = pParse->nMem + 1;
109174    pParse->nMem += nBase;
109175  }
109176  sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
109177                          SQLITE_ECEL_DUP|SQLITE_ECEL_REF);
109178  if( bSeq ){
109179    sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
109180  }
109181  if( nPrefixReg==0 ){
109182    sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
109183  }
109184
109185  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
109186  if( nOBSat>0 ){
109187    int regPrevKey;   /* The first nOBSat columns of the previous row */
109188    int addrFirst;    /* Address of the OP_IfNot opcode */
109189    int addrJmp;      /* Address of the OP_Jump opcode */
109190    VdbeOp *pOp;      /* Opcode that opens the sorter */
109191    int nKey;         /* Number of sorting key columns, including OP_Sequence */
109192    KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
109193
109194    regPrevKey = pParse->nMem+1;
109195    pParse->nMem += pSort->nOBSat;
109196    nKey = nExpr - pSort->nOBSat + bSeq;
109197    if( bSeq ){
109198      addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
109199    }else{
109200      addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
109201    }
109202    VdbeCoverage(v);
109203    sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
109204    pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
109205    if( pParse->db->mallocFailed ) return;
109206    pOp->p2 = nKey + nData;
109207    pKI = pOp->p4.pKeyInfo;
109208    memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
109209    sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
109210    testcase( pKI->nXField>2 );
109211    pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
109212                                           pKI->nXField-1);
109213    addrJmp = sqlite3VdbeCurrentAddr(v);
109214    sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
109215    pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
109216    pSort->regReturn = ++pParse->nMem;
109217    sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
109218    sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
109219    sqlite3VdbeJumpHere(v, addrFirst);
109220    sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
109221    sqlite3VdbeJumpHere(v, addrJmp);
109222  }
109223  if( pSort->sortFlags & SORTFLAG_UseSorter ){
109224    op = OP_SorterInsert;
109225  }else{
109226    op = OP_IdxInsert;
109227  }
109228  sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
109229  if( pSelect->iLimit ){
109230    int addr;
109231    int iLimit;
109232    if( pSelect->iOffset ){
109233      iLimit = pSelect->iOffset+1;
109234    }else{
109235      iLimit = pSelect->iLimit;
109236    }
109237    addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, 1); VdbeCoverage(v);
109238    sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
109239    sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
109240    sqlite3VdbeJumpHere(v, addr);
109241  }
109242}
109243
109244/*
109245** Add code to implement the OFFSET
109246*/
109247static void codeOffset(
109248  Vdbe *v,          /* Generate code into this VM */
109249  int iOffset,      /* Register holding the offset counter */
109250  int iContinue     /* Jump here to skip the current record */
109251){
109252  if( iOffset>0 ){
109253    sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
109254    VdbeComment((v, "OFFSET"));
109255  }
109256}
109257
109258/*
109259** Add code that will check to make sure the N registers starting at iMem
109260** form a distinct entry.  iTab is a sorting index that holds previously
109261** seen combinations of the N values.  A new entry is made in iTab
109262** if the current N values are new.
109263**
109264** A jump to addrRepeat is made and the N+1 values are popped from the
109265** stack if the top N elements are not distinct.
109266*/
109267static void codeDistinct(
109268  Parse *pParse,     /* Parsing and code generating context */
109269  int iTab,          /* A sorting index used to test for distinctness */
109270  int addrRepeat,    /* Jump to here if not distinct */
109271  int N,             /* Number of elements */
109272  int iMem           /* First element */
109273){
109274  Vdbe *v;
109275  int r1;
109276
109277  v = pParse->pVdbe;
109278  r1 = sqlite3GetTempReg(pParse);
109279  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
109280  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
109281  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
109282  sqlite3ReleaseTempReg(pParse, r1);
109283}
109284
109285#ifndef SQLITE_OMIT_SUBQUERY
109286/*
109287** Generate an error message when a SELECT is used within a subexpression
109288** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
109289** column.  We do this in a subroutine because the error used to occur
109290** in multiple places.  (The error only occurs in one place now, but we
109291** retain the subroutine to minimize code disruption.)
109292*/
109293static int checkForMultiColumnSelectError(
109294  Parse *pParse,       /* Parse context. */
109295  SelectDest *pDest,   /* Destination of SELECT results */
109296  int nExpr            /* Number of result columns returned by SELECT */
109297){
109298  int eDest = pDest->eDest;
109299  if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
109300    sqlite3ErrorMsg(pParse, "only a single result allowed for "
109301       "a SELECT that is part of an expression");
109302    return 1;
109303  }else{
109304    return 0;
109305  }
109306}
109307#endif
109308
109309/*
109310** This routine generates the code for the inside of the inner loop
109311** of a SELECT.
109312**
109313** If srcTab is negative, then the pEList expressions
109314** are evaluated in order to get the data for this row.  If srcTab is
109315** zero or more, then data is pulled from srcTab and pEList is used only
109316** to get number columns and the datatype for each column.
109317*/
109318static void selectInnerLoop(
109319  Parse *pParse,          /* The parser context */
109320  Select *p,              /* The complete select statement being coded */
109321  ExprList *pEList,       /* List of values being extracted */
109322  int srcTab,             /* Pull data from this table */
109323  SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */
109324  DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
109325  SelectDest *pDest,      /* How to dispose of the results */
109326  int iContinue,          /* Jump here to continue with next row */
109327  int iBreak              /* Jump here to break out of the inner loop */
109328){
109329  Vdbe *v = pParse->pVdbe;
109330  int i;
109331  int hasDistinct;        /* True if the DISTINCT keyword is present */
109332  int regResult;              /* Start of memory holding result set */
109333  int eDest = pDest->eDest;   /* How to dispose of results */
109334  int iParm = pDest->iSDParm; /* First argument to disposal method */
109335  int nResultCol;             /* Number of result columns */
109336  int nPrefixReg = 0;         /* Number of extra registers before regResult */
109337
109338  assert( v );
109339  assert( pEList!=0 );
109340  hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
109341  if( pSort && pSort->pOrderBy==0 ) pSort = 0;
109342  if( pSort==0 && !hasDistinct ){
109343    assert( iContinue!=0 );
109344    codeOffset(v, p->iOffset, iContinue);
109345  }
109346
109347  /* Pull the requested columns.
109348  */
109349  nResultCol = pEList->nExpr;
109350
109351  if( pDest->iSdst==0 ){
109352    if( pSort ){
109353      nPrefixReg = pSort->pOrderBy->nExpr;
109354      if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
109355      pParse->nMem += nPrefixReg;
109356    }
109357    pDest->iSdst = pParse->nMem+1;
109358    pParse->nMem += nResultCol;
109359  }else if( pDest->iSdst+nResultCol > pParse->nMem ){
109360    /* This is an error condition that can result, for example, when a SELECT
109361    ** on the right-hand side of an INSERT contains more result columns than
109362    ** there are columns in the table on the left.  The error will be caught
109363    ** and reported later.  But we need to make sure enough memory is allocated
109364    ** to avoid other spurious errors in the meantime. */
109365    pParse->nMem += nResultCol;
109366  }
109367  pDest->nSdst = nResultCol;
109368  regResult = pDest->iSdst;
109369  if( srcTab>=0 ){
109370    for(i=0; i<nResultCol; i++){
109371      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
109372      VdbeComment((v, "%s", pEList->a[i].zName));
109373    }
109374  }else if( eDest!=SRT_Exists ){
109375    /* If the destination is an EXISTS(...) expression, the actual
109376    ** values returned by the SELECT are not required.
109377    */
109378    u8 ecelFlags;
109379    if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
109380      ecelFlags = SQLITE_ECEL_DUP;
109381    }else{
109382      ecelFlags = 0;
109383    }
109384    sqlite3ExprCodeExprList(pParse, pEList, regResult, 0, ecelFlags);
109385  }
109386
109387  /* If the DISTINCT keyword was present on the SELECT statement
109388  ** and this row has been seen before, then do not make this row
109389  ** part of the result.
109390  */
109391  if( hasDistinct ){
109392    switch( pDistinct->eTnctType ){
109393      case WHERE_DISTINCT_ORDERED: {
109394        VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
109395        int iJump;              /* Jump destination */
109396        int regPrev;            /* Previous row content */
109397
109398        /* Allocate space for the previous row */
109399        regPrev = pParse->nMem+1;
109400        pParse->nMem += nResultCol;
109401
109402        /* Change the OP_OpenEphemeral coded earlier to an OP_Null
109403        ** sets the MEM_Cleared bit on the first register of the
109404        ** previous value.  This will cause the OP_Ne below to always
109405        ** fail on the first iteration of the loop even if the first
109406        ** row is all NULLs.
109407        */
109408        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
109409        pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
109410        pOp->opcode = OP_Null;
109411        pOp->p1 = 1;
109412        pOp->p2 = regPrev;
109413
109414        iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
109415        for(i=0; i<nResultCol; i++){
109416          CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
109417          if( i<nResultCol-1 ){
109418            sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
109419            VdbeCoverage(v);
109420          }else{
109421            sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
109422            VdbeCoverage(v);
109423           }
109424          sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
109425          sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
109426        }
109427        assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
109428        sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
109429        break;
109430      }
109431
109432      case WHERE_DISTINCT_UNIQUE: {
109433        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
109434        break;
109435      }
109436
109437      default: {
109438        assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
109439        codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
109440                     regResult);
109441        break;
109442      }
109443    }
109444    if( pSort==0 ){
109445      codeOffset(v, p->iOffset, iContinue);
109446    }
109447  }
109448
109449  switch( eDest ){
109450    /* In this mode, write each query result to the key of the temporary
109451    ** table iParm.
109452    */
109453#ifndef SQLITE_OMIT_COMPOUND_SELECT
109454    case SRT_Union: {
109455      int r1;
109456      r1 = sqlite3GetTempReg(pParse);
109457      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
109458      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
109459      sqlite3ReleaseTempReg(pParse, r1);
109460      break;
109461    }
109462
109463    /* Construct a record from the query result, but instead of
109464    ** saving that record, use it as a key to delete elements from
109465    ** the temporary table iParm.
109466    */
109467    case SRT_Except: {
109468      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
109469      break;
109470    }
109471#endif /* SQLITE_OMIT_COMPOUND_SELECT */
109472
109473    /* Store the result as data using a unique key.
109474    */
109475    case SRT_Fifo:
109476    case SRT_DistFifo:
109477    case SRT_Table:
109478    case SRT_EphemTab: {
109479      int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
109480      testcase( eDest==SRT_Table );
109481      testcase( eDest==SRT_EphemTab );
109482      testcase( eDest==SRT_Fifo );
109483      testcase( eDest==SRT_DistFifo );
109484      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
109485#ifndef SQLITE_OMIT_CTE
109486      if( eDest==SRT_DistFifo ){
109487        /* If the destination is DistFifo, then cursor (iParm+1) is open
109488        ** on an ephemeral index. If the current row is already present
109489        ** in the index, do not write it to the output. If not, add the
109490        ** current row to the index and proceed with writing it to the
109491        ** output table as well.  */
109492        int addr = sqlite3VdbeCurrentAddr(v) + 4;
109493        sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
109494        VdbeCoverage(v);
109495        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
109496        assert( pSort==0 );
109497      }
109498#endif
109499      if( pSort ){
109500        pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
109501      }else{
109502        int r2 = sqlite3GetTempReg(pParse);
109503        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
109504        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
109505        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
109506        sqlite3ReleaseTempReg(pParse, r2);
109507      }
109508      sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
109509      break;
109510    }
109511
109512#ifndef SQLITE_OMIT_SUBQUERY
109513    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
109514    ** then there should be a single item on the stack.  Write this
109515    ** item into the set table with bogus data.
109516    */
109517    case SRT_Set: {
109518      assert( nResultCol==1 );
109519      pDest->affSdst =
109520                  sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
109521      if( pSort ){
109522        /* At first glance you would think we could optimize out the
109523        ** ORDER BY in this case since the order of entries in the set
109524        ** does not matter.  But there might be a LIMIT clause, in which
109525        ** case the order does matter */
109526        pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
109527      }else{
109528        int r1 = sqlite3GetTempReg(pParse);
109529        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
109530        sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
109531        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
109532        sqlite3ReleaseTempReg(pParse, r1);
109533      }
109534      break;
109535    }
109536
109537    /* If any row exist in the result set, record that fact and abort.
109538    */
109539    case SRT_Exists: {
109540      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
109541      /* The LIMIT clause will terminate the loop for us */
109542      break;
109543    }
109544
109545    /* If this is a scalar select that is part of an expression, then
109546    ** store the results in the appropriate memory cell and break out
109547    ** of the scan loop.
109548    */
109549    case SRT_Mem: {
109550      assert( nResultCol==1 );
109551      if( pSort ){
109552        pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
109553      }else{
109554        assert( regResult==iParm );
109555        /* The LIMIT clause will jump out of the loop for us */
109556      }
109557      break;
109558    }
109559#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
109560
109561    case SRT_Coroutine:       /* Send data to a co-routine */
109562    case SRT_Output: {        /* Return the results */
109563      testcase( eDest==SRT_Coroutine );
109564      testcase( eDest==SRT_Output );
109565      if( pSort ){
109566        pushOntoSorter(pParse, pSort, p, regResult, regResult, nResultCol,
109567                       nPrefixReg);
109568      }else if( eDest==SRT_Coroutine ){
109569        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
109570      }else{
109571        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
109572        sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
109573      }
109574      break;
109575    }
109576
109577#ifndef SQLITE_OMIT_CTE
109578    /* Write the results into a priority queue that is order according to
109579    ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
109580    ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
109581    ** pSO->nExpr columns, then make sure all keys are unique by adding a
109582    ** final OP_Sequence column.  The last column is the record as a blob.
109583    */
109584    case SRT_DistQueue:
109585    case SRT_Queue: {
109586      int nKey;
109587      int r1, r2, r3;
109588      int addrTest = 0;
109589      ExprList *pSO;
109590      pSO = pDest->pOrderBy;
109591      assert( pSO );
109592      nKey = pSO->nExpr;
109593      r1 = sqlite3GetTempReg(pParse);
109594      r2 = sqlite3GetTempRange(pParse, nKey+2);
109595      r3 = r2+nKey+1;
109596      if( eDest==SRT_DistQueue ){
109597        /* If the destination is DistQueue, then cursor (iParm+1) is open
109598        ** on a second ephemeral index that holds all values every previously
109599        ** added to the queue. */
109600        addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
109601                                        regResult, nResultCol);
109602        VdbeCoverage(v);
109603      }
109604      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
109605      if( eDest==SRT_DistQueue ){
109606        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
109607        sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
109608      }
109609      for(i=0; i<nKey; i++){
109610        sqlite3VdbeAddOp2(v, OP_SCopy,
109611                          regResult + pSO->a[i].u.x.iOrderByCol - 1,
109612                          r2+i);
109613      }
109614      sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
109615      sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
109616      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
109617      if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
109618      sqlite3ReleaseTempReg(pParse, r1);
109619      sqlite3ReleaseTempRange(pParse, r2, nKey+2);
109620      break;
109621    }
109622#endif /* SQLITE_OMIT_CTE */
109623
109624
109625
109626#if !defined(SQLITE_OMIT_TRIGGER)
109627    /* Discard the results.  This is used for SELECT statements inside
109628    ** the body of a TRIGGER.  The purpose of such selects is to call
109629    ** user-defined functions that have side effects.  We do not care
109630    ** about the actual results of the select.
109631    */
109632    default: {
109633      assert( eDest==SRT_Discard );
109634      break;
109635    }
109636#endif
109637  }
109638
109639  /* Jump to the end of the loop if the LIMIT is reached.  Except, if
109640  ** there is a sorter, in which case the sorter has already limited
109641  ** the output for us.
109642  */
109643  if( pSort==0 && p->iLimit ){
109644    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
109645  }
109646}
109647
109648/*
109649** Allocate a KeyInfo object sufficient for an index of N key columns and
109650** X extra columns.
109651*/
109652SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
109653  KeyInfo *p = sqlite3DbMallocZero(0,
109654                   sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
109655  if( p ){
109656    p->aSortOrder = (u8*)&p->aColl[N+X];
109657    p->nField = (u16)N;
109658    p->nXField = (u16)X;
109659    p->enc = ENC(db);
109660    p->db = db;
109661    p->nRef = 1;
109662  }else{
109663    db->mallocFailed = 1;
109664  }
109665  return p;
109666}
109667
109668/*
109669** Deallocate a KeyInfo object
109670*/
109671SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
109672  if( p ){
109673    assert( p->nRef>0 );
109674    p->nRef--;
109675    if( p->nRef==0 ) sqlite3DbFree(0, p);
109676  }
109677}
109678
109679/*
109680** Make a new pointer to a KeyInfo object
109681*/
109682SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
109683  if( p ){
109684    assert( p->nRef>0 );
109685    p->nRef++;
109686  }
109687  return p;
109688}
109689
109690#ifdef SQLITE_DEBUG
109691/*
109692** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
109693** can only be changed if this is just a single reference to the object.
109694**
109695** This routine is used only inside of assert() statements.
109696*/
109697SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
109698#endif /* SQLITE_DEBUG */
109699
109700/*
109701** Given an expression list, generate a KeyInfo structure that records
109702** the collating sequence for each expression in that expression list.
109703**
109704** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
109705** KeyInfo structure is appropriate for initializing a virtual index to
109706** implement that clause.  If the ExprList is the result set of a SELECT
109707** then the KeyInfo structure is appropriate for initializing a virtual
109708** index to implement a DISTINCT test.
109709**
109710** Space to hold the KeyInfo structure is obtained from malloc.  The calling
109711** function is responsible for seeing that this structure is eventually
109712** freed.
109713*/
109714static KeyInfo *keyInfoFromExprList(
109715  Parse *pParse,       /* Parsing context */
109716  ExprList *pList,     /* Form the KeyInfo object from this ExprList */
109717  int iStart,          /* Begin with this column of pList */
109718  int nExtra           /* Add this many extra columns to the end */
109719){
109720  int nExpr;
109721  KeyInfo *pInfo;
109722  struct ExprList_item *pItem;
109723  sqlite3 *db = pParse->db;
109724  int i;
109725
109726  nExpr = pList->nExpr;
109727  pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
109728  if( pInfo ){
109729    assert( sqlite3KeyInfoIsWriteable(pInfo) );
109730    for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
109731      CollSeq *pColl;
109732      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
109733      if( !pColl ) pColl = db->pDfltColl;
109734      pInfo->aColl[i-iStart] = pColl;
109735      pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
109736    }
109737  }
109738  return pInfo;
109739}
109740
109741/*
109742** Name of the connection operator, used for error messages.
109743*/
109744static const char *selectOpName(int id){
109745  char *z;
109746  switch( id ){
109747    case TK_ALL:       z = "UNION ALL";   break;
109748    case TK_INTERSECT: z = "INTERSECT";   break;
109749    case TK_EXCEPT:    z = "EXCEPT";      break;
109750    default:           z = "UNION";       break;
109751  }
109752  return z;
109753}
109754
109755#ifndef SQLITE_OMIT_EXPLAIN
109756/*
109757** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
109758** is a no-op. Otherwise, it adds a single row of output to the EQP result,
109759** where the caption is of the form:
109760**
109761**   "USE TEMP B-TREE FOR xxx"
109762**
109763** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
109764** is determined by the zUsage argument.
109765*/
109766static void explainTempTable(Parse *pParse, const char *zUsage){
109767  if( pParse->explain==2 ){
109768    Vdbe *v = pParse->pVdbe;
109769    char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
109770    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
109771  }
109772}
109773
109774/*
109775** Assign expression b to lvalue a. A second, no-op, version of this macro
109776** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
109777** in sqlite3Select() to assign values to structure member variables that
109778** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
109779** code with #ifndef directives.
109780*/
109781# define explainSetInteger(a, b) a = b
109782
109783#else
109784/* No-op versions of the explainXXX() functions and macros. */
109785# define explainTempTable(y,z)
109786# define explainSetInteger(y,z)
109787#endif
109788
109789#if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
109790/*
109791** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
109792** is a no-op. Otherwise, it adds a single row of output to the EQP result,
109793** where the caption is of one of the two forms:
109794**
109795**   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
109796**   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
109797**
109798** where iSub1 and iSub2 are the integers passed as the corresponding
109799** function parameters, and op is the text representation of the parameter
109800** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
109801** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
109802** false, or the second form if it is true.
109803*/
109804static void explainComposite(
109805  Parse *pParse,                  /* Parse context */
109806  int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
109807  int iSub1,                      /* Subquery id 1 */
109808  int iSub2,                      /* Subquery id 2 */
109809  int bUseTmp                     /* True if a temp table was used */
109810){
109811  assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
109812  if( pParse->explain==2 ){
109813    Vdbe *v = pParse->pVdbe;
109814    char *zMsg = sqlite3MPrintf(
109815        pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
109816        bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
109817    );
109818    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
109819  }
109820}
109821#else
109822/* No-op versions of the explainXXX() functions and macros. */
109823# define explainComposite(v,w,x,y,z)
109824#endif
109825
109826/*
109827** If the inner loop was generated using a non-null pOrderBy argument,
109828** then the results were placed in a sorter.  After the loop is terminated
109829** we need to run the sorter and output the results.  The following
109830** routine generates the code needed to do that.
109831*/
109832static void generateSortTail(
109833  Parse *pParse,    /* Parsing context */
109834  Select *p,        /* The SELECT statement */
109835  SortCtx *pSort,   /* Information on the ORDER BY clause */
109836  int nColumn,      /* Number of columns of data */
109837  SelectDest *pDest /* Write the sorted results here */
109838){
109839  Vdbe *v = pParse->pVdbe;                     /* The prepared statement */
109840  int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
109841  int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
109842  int addr;
109843  int addrOnce = 0;
109844  int iTab;
109845  ExprList *pOrderBy = pSort->pOrderBy;
109846  int eDest = pDest->eDest;
109847  int iParm = pDest->iSDParm;
109848  int regRow;
109849  int regRowid;
109850  int nKey;
109851  int iSortTab;                   /* Sorter cursor to read from */
109852  int nSortData;                  /* Trailing values to read from sorter */
109853  int i;
109854  int bSeq;                       /* True if sorter record includes seq. no. */
109855#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
109856  struct ExprList_item *aOutEx = p->pEList->a;
109857#endif
109858
109859  if( pSort->labelBkOut ){
109860    sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
109861    sqlite3VdbeGoto(v, addrBreak);
109862    sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
109863  }
109864  iTab = pSort->iECursor;
109865  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
109866    regRowid = 0;
109867    regRow = pDest->iSdst;
109868    nSortData = nColumn;
109869  }else{
109870    regRowid = sqlite3GetTempReg(pParse);
109871    regRow = sqlite3GetTempReg(pParse);
109872    nSortData = 1;
109873  }
109874  nKey = pOrderBy->nExpr - pSort->nOBSat;
109875  if( pSort->sortFlags & SORTFLAG_UseSorter ){
109876    int regSortOut = ++pParse->nMem;
109877    iSortTab = pParse->nTab++;
109878    if( pSort->labelBkOut ){
109879      addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
109880    }
109881    sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
109882    if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
109883    addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
109884    VdbeCoverage(v);
109885    codeOffset(v, p->iOffset, addrContinue);
109886    sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
109887    bSeq = 0;
109888  }else{
109889    addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
109890    codeOffset(v, p->iOffset, addrContinue);
109891    iSortTab = iTab;
109892    bSeq = 1;
109893  }
109894  for(i=0; i<nSortData; i++){
109895    sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
109896    VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
109897  }
109898  switch( eDest ){
109899    case SRT_EphemTab: {
109900      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
109901      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
109902      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
109903      break;
109904    }
109905#ifndef SQLITE_OMIT_SUBQUERY
109906    case SRT_Set: {
109907      assert( nColumn==1 );
109908      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
109909                        &pDest->affSdst, 1);
109910      sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
109911      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
109912      break;
109913    }
109914    case SRT_Mem: {
109915      assert( nColumn==1 );
109916      sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
109917      /* The LIMIT clause will terminate the loop for us */
109918      break;
109919    }
109920#endif
109921    default: {
109922      assert( eDest==SRT_Output || eDest==SRT_Coroutine );
109923      testcase( eDest==SRT_Output );
109924      testcase( eDest==SRT_Coroutine );
109925      if( eDest==SRT_Output ){
109926        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
109927        sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
109928      }else{
109929        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
109930      }
109931      break;
109932    }
109933  }
109934  if( regRowid ){
109935    sqlite3ReleaseTempReg(pParse, regRow);
109936    sqlite3ReleaseTempReg(pParse, regRowid);
109937  }
109938  /* The bottom of the loop
109939  */
109940  sqlite3VdbeResolveLabel(v, addrContinue);
109941  if( pSort->sortFlags & SORTFLAG_UseSorter ){
109942    sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
109943  }else{
109944    sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
109945  }
109946  if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
109947  sqlite3VdbeResolveLabel(v, addrBreak);
109948}
109949
109950/*
109951** Return a pointer to a string containing the 'declaration type' of the
109952** expression pExpr. The string may be treated as static by the caller.
109953**
109954** Also try to estimate the size of the returned value and return that
109955** result in *pEstWidth.
109956**
109957** The declaration type is the exact datatype definition extracted from the
109958** original CREATE TABLE statement if the expression is a column. The
109959** declaration type for a ROWID field is INTEGER. Exactly when an expression
109960** is considered a column can be complex in the presence of subqueries. The
109961** result-set expression in all of the following SELECT statements is
109962** considered a column by this function.
109963**
109964**   SELECT col FROM tbl;
109965**   SELECT (SELECT col FROM tbl;
109966**   SELECT (SELECT col FROM tbl);
109967**   SELECT abc FROM (SELECT col AS abc FROM tbl);
109968**
109969** The declaration type for any expression other than a column is NULL.
109970**
109971** This routine has either 3 or 6 parameters depending on whether or not
109972** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
109973*/
109974#ifdef SQLITE_ENABLE_COLUMN_METADATA
109975# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
109976#else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
109977# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
109978#endif
109979static const char *columnTypeImpl(
109980  NameContext *pNC,
109981  Expr *pExpr,
109982#ifdef SQLITE_ENABLE_COLUMN_METADATA
109983  const char **pzOrigDb,
109984  const char **pzOrigTab,
109985  const char **pzOrigCol,
109986#endif
109987  u8 *pEstWidth
109988){
109989  char const *zType = 0;
109990  int j;
109991  u8 estWidth = 1;
109992#ifdef SQLITE_ENABLE_COLUMN_METADATA
109993  char const *zOrigDb = 0;
109994  char const *zOrigTab = 0;
109995  char const *zOrigCol = 0;
109996#endif
109997
109998  if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
109999  switch( pExpr->op ){
110000    case TK_AGG_COLUMN:
110001    case TK_COLUMN: {
110002      /* The expression is a column. Locate the table the column is being
110003      ** extracted from in NameContext.pSrcList. This table may be real
110004      ** database table or a subquery.
110005      */
110006      Table *pTab = 0;            /* Table structure column is extracted from */
110007      Select *pS = 0;             /* Select the column is extracted from */
110008      int iCol = pExpr->iColumn;  /* Index of column in pTab */
110009      testcase( pExpr->op==TK_AGG_COLUMN );
110010      testcase( pExpr->op==TK_COLUMN );
110011      while( pNC && !pTab ){
110012        SrcList *pTabList = pNC->pSrcList;
110013        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
110014        if( j<pTabList->nSrc ){
110015          pTab = pTabList->a[j].pTab;
110016          pS = pTabList->a[j].pSelect;
110017        }else{
110018          pNC = pNC->pNext;
110019        }
110020      }
110021
110022      if( pTab==0 ){
110023        /* At one time, code such as "SELECT new.x" within a trigger would
110024        ** cause this condition to run.  Since then, we have restructured how
110025        ** trigger code is generated and so this condition is no longer
110026        ** possible. However, it can still be true for statements like
110027        ** the following:
110028        **
110029        **   CREATE TABLE t1(col INTEGER);
110030        **   SELECT (SELECT t1.col) FROM FROM t1;
110031        **
110032        ** when columnType() is called on the expression "t1.col" in the
110033        ** sub-select. In this case, set the column type to NULL, even
110034        ** though it should really be "INTEGER".
110035        **
110036        ** This is not a problem, as the column type of "t1.col" is never
110037        ** used. When columnType() is called on the expression
110038        ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
110039        ** branch below.  */
110040        break;
110041      }
110042
110043      assert( pTab && pExpr->pTab==pTab );
110044      if( pS ){
110045        /* The "table" is actually a sub-select or a view in the FROM clause
110046        ** of the SELECT statement. Return the declaration type and origin
110047        ** data for the result-set column of the sub-select.
110048        */
110049        if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
110050          /* If iCol is less than zero, then the expression requests the
110051          ** rowid of the sub-select or view. This expression is legal (see
110052          ** test case misc2.2.2) - it always evaluates to NULL.
110053          **
110054          ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been
110055          ** caught already by name resolution.
110056          */
110057          NameContext sNC;
110058          Expr *p = pS->pEList->a[iCol].pExpr;
110059          sNC.pSrcList = pS->pSrc;
110060          sNC.pNext = pNC;
110061          sNC.pParse = pNC->pParse;
110062          zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
110063        }
110064      }else if( pTab->pSchema ){
110065        /* A real table */
110066        assert( !pS );
110067        if( iCol<0 ) iCol = pTab->iPKey;
110068        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
110069#ifdef SQLITE_ENABLE_COLUMN_METADATA
110070        if( iCol<0 ){
110071          zType = "INTEGER";
110072          zOrigCol = "rowid";
110073        }else{
110074          zType = pTab->aCol[iCol].zType;
110075          zOrigCol = pTab->aCol[iCol].zName;
110076          estWidth = pTab->aCol[iCol].szEst;
110077        }
110078        zOrigTab = pTab->zName;
110079        if( pNC->pParse ){
110080          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
110081          zOrigDb = pNC->pParse->db->aDb[iDb].zName;
110082        }
110083#else
110084        if( iCol<0 ){
110085          zType = "INTEGER";
110086        }else{
110087          zType = pTab->aCol[iCol].zType;
110088          estWidth = pTab->aCol[iCol].szEst;
110089        }
110090#endif
110091      }
110092      break;
110093    }
110094#ifndef SQLITE_OMIT_SUBQUERY
110095    case TK_SELECT: {
110096      /* The expression is a sub-select. Return the declaration type and
110097      ** origin info for the single column in the result set of the SELECT
110098      ** statement.
110099      */
110100      NameContext sNC;
110101      Select *pS = pExpr->x.pSelect;
110102      Expr *p = pS->pEList->a[0].pExpr;
110103      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
110104      sNC.pSrcList = pS->pSrc;
110105      sNC.pNext = pNC;
110106      sNC.pParse = pNC->pParse;
110107      zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
110108      break;
110109    }
110110#endif
110111  }
110112
110113#ifdef SQLITE_ENABLE_COLUMN_METADATA
110114  if( pzOrigDb ){
110115    assert( pzOrigTab && pzOrigCol );
110116    *pzOrigDb = zOrigDb;
110117    *pzOrigTab = zOrigTab;
110118    *pzOrigCol = zOrigCol;
110119  }
110120#endif
110121  if( pEstWidth ) *pEstWidth = estWidth;
110122  return zType;
110123}
110124
110125/*
110126** Generate code that will tell the VDBE the declaration types of columns
110127** in the result set.
110128*/
110129static void generateColumnTypes(
110130  Parse *pParse,      /* Parser context */
110131  SrcList *pTabList,  /* List of tables */
110132  ExprList *pEList    /* Expressions defining the result set */
110133){
110134#ifndef SQLITE_OMIT_DECLTYPE
110135  Vdbe *v = pParse->pVdbe;
110136  int i;
110137  NameContext sNC;
110138  sNC.pSrcList = pTabList;
110139  sNC.pParse = pParse;
110140  for(i=0; i<pEList->nExpr; i++){
110141    Expr *p = pEList->a[i].pExpr;
110142    const char *zType;
110143#ifdef SQLITE_ENABLE_COLUMN_METADATA
110144    const char *zOrigDb = 0;
110145    const char *zOrigTab = 0;
110146    const char *zOrigCol = 0;
110147    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
110148
110149    /* The vdbe must make its own copy of the column-type and other
110150    ** column specific strings, in case the schema is reset before this
110151    ** virtual machine is deleted.
110152    */
110153    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
110154    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
110155    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
110156#else
110157    zType = columnType(&sNC, p, 0, 0, 0, 0);
110158#endif
110159    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
110160  }
110161#endif /* !defined(SQLITE_OMIT_DECLTYPE) */
110162}
110163
110164/*
110165** Generate code that will tell the VDBE the names of columns
110166** in the result set.  This information is used to provide the
110167** azCol[] values in the callback.
110168*/
110169static void generateColumnNames(
110170  Parse *pParse,      /* Parser context */
110171  SrcList *pTabList,  /* List of tables */
110172  ExprList *pEList    /* Expressions defining the result set */
110173){
110174  Vdbe *v = pParse->pVdbe;
110175  int i, j;
110176  sqlite3 *db = pParse->db;
110177  int fullNames, shortNames;
110178
110179#ifndef SQLITE_OMIT_EXPLAIN
110180  /* If this is an EXPLAIN, skip this step */
110181  if( pParse->explain ){
110182    return;
110183  }
110184#endif
110185
110186  if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
110187  pParse->colNamesSet = 1;
110188  fullNames = (db->flags & SQLITE_FullColNames)!=0;
110189  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
110190  sqlite3VdbeSetNumCols(v, pEList->nExpr);
110191  for(i=0; i<pEList->nExpr; i++){
110192    Expr *p;
110193    p = pEList->a[i].pExpr;
110194    if( NEVER(p==0) ) continue;
110195    if( pEList->a[i].zName ){
110196      char *zName = pEList->a[i].zName;
110197      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
110198    }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
110199      Table *pTab;
110200      char *zCol;
110201      int iCol = p->iColumn;
110202      for(j=0; ALWAYS(j<pTabList->nSrc); j++){
110203        if( pTabList->a[j].iCursor==p->iTable ) break;
110204      }
110205      assert( j<pTabList->nSrc );
110206      pTab = pTabList->a[j].pTab;
110207      if( iCol<0 ) iCol = pTab->iPKey;
110208      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
110209      if( iCol<0 ){
110210        zCol = "rowid";
110211      }else{
110212        zCol = pTab->aCol[iCol].zName;
110213      }
110214      if( !shortNames && !fullNames ){
110215        sqlite3VdbeSetColName(v, i, COLNAME_NAME,
110216            sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
110217      }else if( fullNames ){
110218        char *zName = 0;
110219        zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
110220        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
110221      }else{
110222        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
110223      }
110224    }else{
110225      const char *z = pEList->a[i].zSpan;
110226      z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
110227      sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
110228    }
110229  }
110230  generateColumnTypes(pParse, pTabList, pEList);
110231}
110232
110233/*
110234** Given an expression list (which is really the list of expressions
110235** that form the result set of a SELECT statement) compute appropriate
110236** column names for a table that would hold the expression list.
110237**
110238** All column names will be unique.
110239**
110240** Only the column names are computed.  Column.zType, Column.zColl,
110241** and other fields of Column are zeroed.
110242**
110243** Return SQLITE_OK on success.  If a memory allocation error occurs,
110244** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
110245*/
110246SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
110247  Parse *pParse,          /* Parsing context */
110248  ExprList *pEList,       /* Expr list from which to derive column names */
110249  i16 *pnCol,             /* Write the number of columns here */
110250  Column **paCol          /* Write the new column list here */
110251){
110252  sqlite3 *db = pParse->db;   /* Database connection */
110253  int i, j;                   /* Loop counters */
110254  int cnt;                    /* Index added to make the name unique */
110255  Column *aCol, *pCol;        /* For looping over result columns */
110256  int nCol;                   /* Number of columns in the result set */
110257  Expr *p;                    /* Expression for a single result column */
110258  char *zName;                /* Column name */
110259  int nName;                  /* Size of name in zName[] */
110260
110261  if( pEList ){
110262    nCol = pEList->nExpr;
110263    aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
110264    testcase( aCol==0 );
110265  }else{
110266    nCol = 0;
110267    aCol = 0;
110268  }
110269  *pnCol = nCol;
110270  *paCol = aCol;
110271
110272  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
110273    /* Get an appropriate name for the column
110274    */
110275    p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
110276    if( (zName = pEList->a[i].zName)!=0 ){
110277      /* If the column contains an "AS <name>" phrase, use <name> as the name */
110278      zName = sqlite3DbStrDup(db, zName);
110279    }else{
110280      Expr *pColExpr = p;  /* The expression that is the result column name */
110281      Table *pTab;         /* Table associated with this expression */
110282      while( pColExpr->op==TK_DOT ){
110283        pColExpr = pColExpr->pRight;
110284        assert( pColExpr!=0 );
110285      }
110286      if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
110287        /* For columns use the column name name */
110288        int iCol = pColExpr->iColumn;
110289        pTab = pColExpr->pTab;
110290        if( iCol<0 ) iCol = pTab->iPKey;
110291        zName = sqlite3MPrintf(db, "%s",
110292                 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
110293      }else if( pColExpr->op==TK_ID ){
110294        assert( !ExprHasProperty(pColExpr, EP_IntValue) );
110295        zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
110296      }else{
110297        /* Use the original text of the column expression as its name */
110298        zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
110299      }
110300    }
110301    if( db->mallocFailed ){
110302      sqlite3DbFree(db, zName);
110303      break;
110304    }
110305
110306    /* Make sure the column name is unique.  If the name is not unique,
110307    ** append an integer to the name so that it becomes unique.
110308    */
110309    nName = sqlite3Strlen30(zName);
110310    for(j=cnt=0; j<i; j++){
110311      if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
110312        char *zNewName;
110313        int k;
110314        for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
110315        if( k>=0 && zName[k]==':' ) nName = k;
110316        zName[nName] = 0;
110317        zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
110318        sqlite3DbFree(db, zName);
110319        zName = zNewName;
110320        j = -1;
110321        if( zName==0 ) break;
110322      }
110323    }
110324    pCol->zName = zName;
110325  }
110326  if( db->mallocFailed ){
110327    for(j=0; j<i; j++){
110328      sqlite3DbFree(db, aCol[j].zName);
110329    }
110330    sqlite3DbFree(db, aCol);
110331    *paCol = 0;
110332    *pnCol = 0;
110333    return SQLITE_NOMEM;
110334  }
110335  return SQLITE_OK;
110336}
110337
110338/*
110339** Add type and collation information to a column list based on
110340** a SELECT statement.
110341**
110342** The column list presumably came from selectColumnNamesFromExprList().
110343** The column list has only names, not types or collations.  This
110344** routine goes through and adds the types and collations.
110345**
110346** This routine requires that all identifiers in the SELECT
110347** statement be resolved.
110348*/
110349static void selectAddColumnTypeAndCollation(
110350  Parse *pParse,        /* Parsing contexts */
110351  Table *pTab,          /* Add column type information to this table */
110352  Select *pSelect       /* SELECT used to determine types and collations */
110353){
110354  sqlite3 *db = pParse->db;
110355  NameContext sNC;
110356  Column *pCol;
110357  CollSeq *pColl;
110358  int i;
110359  Expr *p;
110360  struct ExprList_item *a;
110361  u64 szAll = 0;
110362
110363  assert( pSelect!=0 );
110364  assert( (pSelect->selFlags & SF_Resolved)!=0 );
110365  assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
110366  if( db->mallocFailed ) return;
110367  memset(&sNC, 0, sizeof(sNC));
110368  sNC.pSrcList = pSelect->pSrc;
110369  a = pSelect->pEList->a;
110370  for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
110371    p = a[i].pExpr;
110372    if( pCol->zType==0 ){
110373      pCol->zType = sqlite3DbStrDup(db,
110374                        columnType(&sNC, p,0,0,0, &pCol->szEst));
110375    }
110376    szAll += pCol->szEst;
110377    pCol->affinity = sqlite3ExprAffinity(p);
110378    if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
110379    pColl = sqlite3ExprCollSeq(pParse, p);
110380    if( pColl && pCol->zColl==0 ){
110381      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
110382    }
110383  }
110384  pTab->szTabRow = sqlite3LogEst(szAll*4);
110385}
110386
110387/*
110388** Given a SELECT statement, generate a Table structure that describes
110389** the result set of that SELECT.
110390*/
110391SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
110392  Table *pTab;
110393  sqlite3 *db = pParse->db;
110394  int savedFlags;
110395
110396  savedFlags = db->flags;
110397  db->flags &= ~SQLITE_FullColNames;
110398  db->flags |= SQLITE_ShortColNames;
110399  sqlite3SelectPrep(pParse, pSelect, 0);
110400  if( pParse->nErr ) return 0;
110401  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
110402  db->flags = savedFlags;
110403  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
110404  if( pTab==0 ){
110405    return 0;
110406  }
110407  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
110408  ** is disabled */
110409  assert( db->lookaside.bEnabled==0 );
110410  pTab->nRef = 1;
110411  pTab->zName = 0;
110412  pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
110413  sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
110414  selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
110415  pTab->iPKey = -1;
110416  if( db->mallocFailed ){
110417    sqlite3DeleteTable(db, pTab);
110418    return 0;
110419  }
110420  return pTab;
110421}
110422
110423/*
110424** Get a VDBE for the given parser context.  Create a new one if necessary.
110425** If an error occurs, return NULL and leave a message in pParse.
110426*/
110427SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
110428  Vdbe *v = pParse->pVdbe;
110429  if( v==0 ){
110430    v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
110431    if( v ) sqlite3VdbeAddOp0(v, OP_Init);
110432    if( pParse->pToplevel==0
110433     && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
110434    ){
110435      pParse->okConstFactor = 1;
110436    }
110437
110438  }
110439  return v;
110440}
110441
110442
110443/*
110444** Compute the iLimit and iOffset fields of the SELECT based on the
110445** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
110446** that appear in the original SQL statement after the LIMIT and OFFSET
110447** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
110448** are the integer memory register numbers for counters used to compute
110449** the limit and offset.  If there is no limit and/or offset, then
110450** iLimit and iOffset are negative.
110451**
110452** This routine changes the values of iLimit and iOffset only if
110453** a limit or offset is defined by pLimit and pOffset.  iLimit and
110454** iOffset should have been preset to appropriate default values (zero)
110455** prior to calling this routine.
110456**
110457** The iOffset register (if it exists) is initialized to the value
110458** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
110459** iOffset+1 is initialized to LIMIT+OFFSET.
110460**
110461** Only if pLimit!=0 or pOffset!=0 do the limit registers get
110462** redefined.  The UNION ALL operator uses this property to force
110463** the reuse of the same limit and offset registers across multiple
110464** SELECT statements.
110465*/
110466static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
110467  Vdbe *v = 0;
110468  int iLimit = 0;
110469  int iOffset;
110470  int n;
110471  if( p->iLimit ) return;
110472
110473  /*
110474  ** "LIMIT -1" always shows all rows.  There is some
110475  ** controversy about what the correct behavior should be.
110476  ** The current implementation interprets "LIMIT 0" to mean
110477  ** no rows.
110478  */
110479  sqlite3ExprCacheClear(pParse);
110480  assert( p->pOffset==0 || p->pLimit!=0 );
110481  if( p->pLimit ){
110482    p->iLimit = iLimit = ++pParse->nMem;
110483    v = sqlite3GetVdbe(pParse);
110484    assert( v!=0 );
110485    if( sqlite3ExprIsInteger(p->pLimit, &n) ){
110486      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
110487      VdbeComment((v, "LIMIT counter"));
110488      if( n==0 ){
110489        sqlite3VdbeGoto(v, iBreak);
110490      }else if( n>=0 && p->nSelectRow>(u64)n ){
110491        p->nSelectRow = n;
110492      }
110493    }else{
110494      sqlite3ExprCode(pParse, p->pLimit, iLimit);
110495      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
110496      VdbeComment((v, "LIMIT counter"));
110497      sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
110498    }
110499    if( p->pOffset ){
110500      p->iOffset = iOffset = ++pParse->nMem;
110501      pParse->nMem++;   /* Allocate an extra register for limit+offset */
110502      sqlite3ExprCode(pParse, p->pOffset, iOffset);
110503      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
110504      VdbeComment((v, "OFFSET counter"));
110505      sqlite3VdbeAddOp3(v, OP_SetIfNotPos, iOffset, iOffset, 0);
110506      sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
110507      VdbeComment((v, "LIMIT+OFFSET"));
110508      sqlite3VdbeAddOp3(v, OP_SetIfNotPos, iLimit, iOffset+1, -1);
110509    }
110510  }
110511}
110512
110513#ifndef SQLITE_OMIT_COMPOUND_SELECT
110514/*
110515** Return the appropriate collating sequence for the iCol-th column of
110516** the result set for the compound-select statement "p".  Return NULL if
110517** the column has no default collating sequence.
110518**
110519** The collating sequence for the compound select is taken from the
110520** left-most term of the select that has a collating sequence.
110521*/
110522static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
110523  CollSeq *pRet;
110524  if( p->pPrior ){
110525    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
110526  }else{
110527    pRet = 0;
110528  }
110529  assert( iCol>=0 );
110530  /* iCol must be less than p->pEList->nExpr.  Otherwise an error would
110531  ** have been thrown during name resolution and we would not have gotten
110532  ** this far */
110533  if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
110534    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
110535  }
110536  return pRet;
110537}
110538
110539/*
110540** The select statement passed as the second parameter is a compound SELECT
110541** with an ORDER BY clause. This function allocates and returns a KeyInfo
110542** structure suitable for implementing the ORDER BY.
110543**
110544** Space to hold the KeyInfo structure is obtained from malloc. The calling
110545** function is responsible for ensuring that this structure is eventually
110546** freed.
110547*/
110548static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
110549  ExprList *pOrderBy = p->pOrderBy;
110550  int nOrderBy = p->pOrderBy->nExpr;
110551  sqlite3 *db = pParse->db;
110552  KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
110553  if( pRet ){
110554    int i;
110555    for(i=0; i<nOrderBy; i++){
110556      struct ExprList_item *pItem = &pOrderBy->a[i];
110557      Expr *pTerm = pItem->pExpr;
110558      CollSeq *pColl;
110559
110560      if( pTerm->flags & EP_Collate ){
110561        pColl = sqlite3ExprCollSeq(pParse, pTerm);
110562      }else{
110563        pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
110564        if( pColl==0 ) pColl = db->pDfltColl;
110565        pOrderBy->a[i].pExpr =
110566          sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
110567      }
110568      assert( sqlite3KeyInfoIsWriteable(pRet) );
110569      pRet->aColl[i] = pColl;
110570      pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
110571    }
110572  }
110573
110574  return pRet;
110575}
110576
110577#ifndef SQLITE_OMIT_CTE
110578/*
110579** This routine generates VDBE code to compute the content of a WITH RECURSIVE
110580** query of the form:
110581**
110582**   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
110583**                         \___________/             \_______________/
110584**                           p->pPrior                      p
110585**
110586**
110587** There is exactly one reference to the recursive-table in the FROM clause
110588** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
110589**
110590** The setup-query runs once to generate an initial set of rows that go
110591** into a Queue table.  Rows are extracted from the Queue table one by
110592** one.  Each row extracted from Queue is output to pDest.  Then the single
110593** extracted row (now in the iCurrent table) becomes the content of the
110594** recursive-table for a recursive-query run.  The output of the recursive-query
110595** is added back into the Queue table.  Then another row is extracted from Queue
110596** and the iteration continues until the Queue table is empty.
110597**
110598** If the compound query operator is UNION then no duplicate rows are ever
110599** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
110600** that have ever been inserted into Queue and causes duplicates to be
110601** discarded.  If the operator is UNION ALL, then duplicates are allowed.
110602**
110603** If the query has an ORDER BY, then entries in the Queue table are kept in
110604** ORDER BY order and the first entry is extracted for each cycle.  Without
110605** an ORDER BY, the Queue table is just a FIFO.
110606**
110607** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
110608** have been output to pDest.  A LIMIT of zero means to output no rows and a
110609** negative LIMIT means to output all rows.  If there is also an OFFSET clause
110610** with a positive value, then the first OFFSET outputs are discarded rather
110611** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
110612** rows have been skipped.
110613*/
110614static void generateWithRecursiveQuery(
110615  Parse *pParse,        /* Parsing context */
110616  Select *p,            /* The recursive SELECT to be coded */
110617  SelectDest *pDest     /* What to do with query results */
110618){
110619  SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
110620  int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
110621  Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
110622  Select *pSetup = p->pPrior;   /* The setup query */
110623  int addrTop;                  /* Top of the loop */
110624  int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
110625  int iCurrent = 0;             /* The Current table */
110626  int regCurrent;               /* Register holding Current table */
110627  int iQueue;                   /* The Queue table */
110628  int iDistinct = 0;            /* To ensure unique results if UNION */
110629  int eDest = SRT_Fifo;         /* How to write to Queue */
110630  SelectDest destQueue;         /* SelectDest targetting the Queue table */
110631  int i;                        /* Loop counter */
110632  int rc;                       /* Result code */
110633  ExprList *pOrderBy;           /* The ORDER BY clause */
110634  Expr *pLimit, *pOffset;       /* Saved LIMIT and OFFSET */
110635  int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
110636
110637  /* Obtain authorization to do a recursive query */
110638  if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
110639
110640  /* Process the LIMIT and OFFSET clauses, if they exist */
110641  addrBreak = sqlite3VdbeMakeLabel(v);
110642  computeLimitRegisters(pParse, p, addrBreak);
110643  pLimit = p->pLimit;
110644  pOffset = p->pOffset;
110645  regLimit = p->iLimit;
110646  regOffset = p->iOffset;
110647  p->pLimit = p->pOffset = 0;
110648  p->iLimit = p->iOffset = 0;
110649  pOrderBy = p->pOrderBy;
110650
110651  /* Locate the cursor number of the Current table */
110652  for(i=0; ALWAYS(i<pSrc->nSrc); i++){
110653    if( pSrc->a[i].fg.isRecursive ){
110654      iCurrent = pSrc->a[i].iCursor;
110655      break;
110656    }
110657  }
110658
110659  /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
110660  ** the Distinct table must be exactly one greater than Queue in order
110661  ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
110662  iQueue = pParse->nTab++;
110663  if( p->op==TK_UNION ){
110664    eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
110665    iDistinct = pParse->nTab++;
110666  }else{
110667    eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
110668  }
110669  sqlite3SelectDestInit(&destQueue, eDest, iQueue);
110670
110671  /* Allocate cursors for Current, Queue, and Distinct. */
110672  regCurrent = ++pParse->nMem;
110673  sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
110674  if( pOrderBy ){
110675    KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
110676    sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
110677                      (char*)pKeyInfo, P4_KEYINFO);
110678    destQueue.pOrderBy = pOrderBy;
110679  }else{
110680    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
110681  }
110682  VdbeComment((v, "Queue table"));
110683  if( iDistinct ){
110684    p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
110685    p->selFlags |= SF_UsesEphemeral;
110686  }
110687
110688  /* Detach the ORDER BY clause from the compound SELECT */
110689  p->pOrderBy = 0;
110690
110691  /* Store the results of the setup-query in Queue. */
110692  pSetup->pNext = 0;
110693  rc = sqlite3Select(pParse, pSetup, &destQueue);
110694  pSetup->pNext = p;
110695  if( rc ) goto end_of_recursive_query;
110696
110697  /* Find the next row in the Queue and output that row */
110698  addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
110699
110700  /* Transfer the next row in Queue over to Current */
110701  sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
110702  if( pOrderBy ){
110703    sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
110704  }else{
110705    sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
110706  }
110707  sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
110708
110709  /* Output the single row in Current */
110710  addrCont = sqlite3VdbeMakeLabel(v);
110711  codeOffset(v, regOffset, addrCont);
110712  selectInnerLoop(pParse, p, p->pEList, iCurrent,
110713      0, 0, pDest, addrCont, addrBreak);
110714  if( regLimit ){
110715    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
110716    VdbeCoverage(v);
110717  }
110718  sqlite3VdbeResolveLabel(v, addrCont);
110719
110720  /* Execute the recursive SELECT taking the single row in Current as
110721  ** the value for the recursive-table. Store the results in the Queue.
110722  */
110723  if( p->selFlags & SF_Aggregate ){
110724    sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
110725  }else{
110726    p->pPrior = 0;
110727    sqlite3Select(pParse, p, &destQueue);
110728    assert( p->pPrior==0 );
110729    p->pPrior = pSetup;
110730  }
110731
110732  /* Keep running the loop until the Queue is empty */
110733  sqlite3VdbeGoto(v, addrTop);
110734  sqlite3VdbeResolveLabel(v, addrBreak);
110735
110736end_of_recursive_query:
110737  sqlite3ExprListDelete(pParse->db, p->pOrderBy);
110738  p->pOrderBy = pOrderBy;
110739  p->pLimit = pLimit;
110740  p->pOffset = pOffset;
110741  return;
110742}
110743#endif /* SQLITE_OMIT_CTE */
110744
110745/* Forward references */
110746static int multiSelectOrderBy(
110747  Parse *pParse,        /* Parsing context */
110748  Select *p,            /* The right-most of SELECTs to be coded */
110749  SelectDest *pDest     /* What to do with query results */
110750);
110751
110752/*
110753** Handle the special case of a compound-select that originates from a
110754** VALUES clause.  By handling this as a special case, we avoid deep
110755** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
110756** on a VALUES clause.
110757**
110758** Because the Select object originates from a VALUES clause:
110759**   (1) It has no LIMIT or OFFSET
110760**   (2) All terms are UNION ALL
110761**   (3) There is no ORDER BY clause
110762*/
110763static int multiSelectValues(
110764  Parse *pParse,        /* Parsing context */
110765  Select *p,            /* The right-most of SELECTs to be coded */
110766  SelectDest *pDest     /* What to do with query results */
110767){
110768  Select *pPrior;
110769  int nRow = 1;
110770  int rc = 0;
110771  assert( p->selFlags & SF_MultiValue );
110772  do{
110773    assert( p->selFlags & SF_Values );
110774    assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
110775    assert( p->pLimit==0 );
110776    assert( p->pOffset==0 );
110777    assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
110778    if( p->pPrior==0 ) break;
110779    assert( p->pPrior->pNext==p );
110780    p = p->pPrior;
110781    nRow++;
110782  }while(1);
110783  while( p ){
110784    pPrior = p->pPrior;
110785    p->pPrior = 0;
110786    rc = sqlite3Select(pParse, p, pDest);
110787    p->pPrior = pPrior;
110788    if( rc ) break;
110789    p->nSelectRow = nRow;
110790    p = p->pNext;
110791  }
110792  return rc;
110793}
110794
110795/*
110796** This routine is called to process a compound query form from
110797** two or more separate queries using UNION, UNION ALL, EXCEPT, or
110798** INTERSECT
110799**
110800** "p" points to the right-most of the two queries.  the query on the
110801** left is p->pPrior.  The left query could also be a compound query
110802** in which case this routine will be called recursively.
110803**
110804** The results of the total query are to be written into a destination
110805** of type eDest with parameter iParm.
110806**
110807** Example 1:  Consider a three-way compound SQL statement.
110808**
110809**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
110810**
110811** This statement is parsed up as follows:
110812**
110813**     SELECT c FROM t3
110814**      |
110815**      `----->  SELECT b FROM t2
110816**                |
110817**                `------>  SELECT a FROM t1
110818**
110819** The arrows in the diagram above represent the Select.pPrior pointer.
110820** So if this routine is called with p equal to the t3 query, then
110821** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
110822**
110823** Notice that because of the way SQLite parses compound SELECTs, the
110824** individual selects always group from left to right.
110825*/
110826static int multiSelect(
110827  Parse *pParse,        /* Parsing context */
110828  Select *p,            /* The right-most of SELECTs to be coded */
110829  SelectDest *pDest     /* What to do with query results */
110830){
110831  int rc = SQLITE_OK;   /* Success code from a subroutine */
110832  Select *pPrior;       /* Another SELECT immediately to our left */
110833  Vdbe *v;              /* Generate code to this VDBE */
110834  SelectDest dest;      /* Alternative data destination */
110835  Select *pDelete = 0;  /* Chain of simple selects to delete */
110836  sqlite3 *db;          /* Database connection */
110837#ifndef SQLITE_OMIT_EXPLAIN
110838  int iSub1 = 0;        /* EQP id of left-hand query */
110839  int iSub2 = 0;        /* EQP id of right-hand query */
110840#endif
110841
110842  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
110843  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
110844  */
110845  assert( p && p->pPrior );  /* Calling function guarantees this much */
110846  assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
110847  db = pParse->db;
110848  pPrior = p->pPrior;
110849  dest = *pDest;
110850  if( pPrior->pOrderBy ){
110851    sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
110852      selectOpName(p->op));
110853    rc = 1;
110854    goto multi_select_end;
110855  }
110856  if( pPrior->pLimit ){
110857    sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
110858      selectOpName(p->op));
110859    rc = 1;
110860    goto multi_select_end;
110861  }
110862
110863  v = sqlite3GetVdbe(pParse);
110864  assert( v!=0 );  /* The VDBE already created by calling function */
110865
110866  /* Create the destination temporary table if necessary
110867  */
110868  if( dest.eDest==SRT_EphemTab ){
110869    assert( p->pEList );
110870    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
110871    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
110872    dest.eDest = SRT_Table;
110873  }
110874
110875  /* Special handling for a compound-select that originates as a VALUES clause.
110876  */
110877  if( p->selFlags & SF_MultiValue ){
110878    rc = multiSelectValues(pParse, p, &dest);
110879    goto multi_select_end;
110880  }
110881
110882  /* Make sure all SELECTs in the statement have the same number of elements
110883  ** in their result sets.
110884  */
110885  assert( p->pEList && pPrior->pEList );
110886  assert( p->pEList->nExpr==pPrior->pEList->nExpr );
110887
110888#ifndef SQLITE_OMIT_CTE
110889  if( p->selFlags & SF_Recursive ){
110890    generateWithRecursiveQuery(pParse, p, &dest);
110891  }else
110892#endif
110893
110894  /* Compound SELECTs that have an ORDER BY clause are handled separately.
110895  */
110896  if( p->pOrderBy ){
110897    return multiSelectOrderBy(pParse, p, pDest);
110898  }else
110899
110900  /* Generate code for the left and right SELECT statements.
110901  */
110902  switch( p->op ){
110903    case TK_ALL: {
110904      int addr = 0;
110905      int nLimit;
110906      assert( !pPrior->pLimit );
110907      pPrior->iLimit = p->iLimit;
110908      pPrior->iOffset = p->iOffset;
110909      pPrior->pLimit = p->pLimit;
110910      pPrior->pOffset = p->pOffset;
110911      explainSetInteger(iSub1, pParse->iNextSelectId);
110912      rc = sqlite3Select(pParse, pPrior, &dest);
110913      p->pLimit = 0;
110914      p->pOffset = 0;
110915      if( rc ){
110916        goto multi_select_end;
110917      }
110918      p->pPrior = 0;
110919      p->iLimit = pPrior->iLimit;
110920      p->iOffset = pPrior->iOffset;
110921      if( p->iLimit ){
110922        addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
110923        VdbeComment((v, "Jump ahead if LIMIT reached"));
110924        if( p->iOffset ){
110925          sqlite3VdbeAddOp3(v, OP_SetIfNotPos, p->iOffset, p->iOffset, 0);
110926          sqlite3VdbeAddOp3(v, OP_Add, p->iLimit, p->iOffset, p->iOffset+1);
110927          sqlite3VdbeAddOp3(v, OP_SetIfNotPos, p->iLimit, p->iOffset+1, -1);
110928        }
110929      }
110930      explainSetInteger(iSub2, pParse->iNextSelectId);
110931      rc = sqlite3Select(pParse, p, &dest);
110932      testcase( rc!=SQLITE_OK );
110933      pDelete = p->pPrior;
110934      p->pPrior = pPrior;
110935      p->nSelectRow += pPrior->nSelectRow;
110936      if( pPrior->pLimit
110937       && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
110938       && nLimit>0 && p->nSelectRow > (u64)nLimit
110939      ){
110940        p->nSelectRow = nLimit;
110941      }
110942      if( addr ){
110943        sqlite3VdbeJumpHere(v, addr);
110944      }
110945      break;
110946    }
110947    case TK_EXCEPT:
110948    case TK_UNION: {
110949      int unionTab;    /* Cursor number of the temporary table holding result */
110950      u8 op = 0;       /* One of the SRT_ operations to apply to self */
110951      int priorOp;     /* The SRT_ operation to apply to prior selects */
110952      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
110953      int addr;
110954      SelectDest uniondest;
110955
110956      testcase( p->op==TK_EXCEPT );
110957      testcase( p->op==TK_UNION );
110958      priorOp = SRT_Union;
110959      if( dest.eDest==priorOp ){
110960        /* We can reuse a temporary table generated by a SELECT to our
110961        ** right.
110962        */
110963        assert( p->pLimit==0 );      /* Not allowed on leftward elements */
110964        assert( p->pOffset==0 );     /* Not allowed on leftward elements */
110965        unionTab = dest.iSDParm;
110966      }else{
110967        /* We will need to create our own temporary table to hold the
110968        ** intermediate results.
110969        */
110970        unionTab = pParse->nTab++;
110971        assert( p->pOrderBy==0 );
110972        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
110973        assert( p->addrOpenEphm[0] == -1 );
110974        p->addrOpenEphm[0] = addr;
110975        findRightmost(p)->selFlags |= SF_UsesEphemeral;
110976        assert( p->pEList );
110977      }
110978
110979      /* Code the SELECT statements to our left
110980      */
110981      assert( !pPrior->pOrderBy );
110982      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
110983      explainSetInteger(iSub1, pParse->iNextSelectId);
110984      rc = sqlite3Select(pParse, pPrior, &uniondest);
110985      if( rc ){
110986        goto multi_select_end;
110987      }
110988
110989      /* Code the current SELECT statement
110990      */
110991      if( p->op==TK_EXCEPT ){
110992        op = SRT_Except;
110993      }else{
110994        assert( p->op==TK_UNION );
110995        op = SRT_Union;
110996      }
110997      p->pPrior = 0;
110998      pLimit = p->pLimit;
110999      p->pLimit = 0;
111000      pOffset = p->pOffset;
111001      p->pOffset = 0;
111002      uniondest.eDest = op;
111003      explainSetInteger(iSub2, pParse->iNextSelectId);
111004      rc = sqlite3Select(pParse, p, &uniondest);
111005      testcase( rc!=SQLITE_OK );
111006      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
111007      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
111008      sqlite3ExprListDelete(db, p->pOrderBy);
111009      pDelete = p->pPrior;
111010      p->pPrior = pPrior;
111011      p->pOrderBy = 0;
111012      if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
111013      sqlite3ExprDelete(db, p->pLimit);
111014      p->pLimit = pLimit;
111015      p->pOffset = pOffset;
111016      p->iLimit = 0;
111017      p->iOffset = 0;
111018
111019      /* Convert the data in the temporary table into whatever form
111020      ** it is that we currently need.
111021      */
111022      assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
111023      if( dest.eDest!=priorOp ){
111024        int iCont, iBreak, iStart;
111025        assert( p->pEList );
111026        if( dest.eDest==SRT_Output ){
111027          Select *pFirst = p;
111028          while( pFirst->pPrior ) pFirst = pFirst->pPrior;
111029          generateColumnNames(pParse, 0, pFirst->pEList);
111030        }
111031        iBreak = sqlite3VdbeMakeLabel(v);
111032        iCont = sqlite3VdbeMakeLabel(v);
111033        computeLimitRegisters(pParse, p, iBreak);
111034        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
111035        iStart = sqlite3VdbeCurrentAddr(v);
111036        selectInnerLoop(pParse, p, p->pEList, unionTab,
111037                        0, 0, &dest, iCont, iBreak);
111038        sqlite3VdbeResolveLabel(v, iCont);
111039        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
111040        sqlite3VdbeResolveLabel(v, iBreak);
111041        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
111042      }
111043      break;
111044    }
111045    default: assert( p->op==TK_INTERSECT ); {
111046      int tab1, tab2;
111047      int iCont, iBreak, iStart;
111048      Expr *pLimit, *pOffset;
111049      int addr;
111050      SelectDest intersectdest;
111051      int r1;
111052
111053      /* INTERSECT is different from the others since it requires
111054      ** two temporary tables.  Hence it has its own case.  Begin
111055      ** by allocating the tables we will need.
111056      */
111057      tab1 = pParse->nTab++;
111058      tab2 = pParse->nTab++;
111059      assert( p->pOrderBy==0 );
111060
111061      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
111062      assert( p->addrOpenEphm[0] == -1 );
111063      p->addrOpenEphm[0] = addr;
111064      findRightmost(p)->selFlags |= SF_UsesEphemeral;
111065      assert( p->pEList );
111066
111067      /* Code the SELECTs to our left into temporary table "tab1".
111068      */
111069      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
111070      explainSetInteger(iSub1, pParse->iNextSelectId);
111071      rc = sqlite3Select(pParse, pPrior, &intersectdest);
111072      if( rc ){
111073        goto multi_select_end;
111074      }
111075
111076      /* Code the current SELECT into temporary table "tab2"
111077      */
111078      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
111079      assert( p->addrOpenEphm[1] == -1 );
111080      p->addrOpenEphm[1] = addr;
111081      p->pPrior = 0;
111082      pLimit = p->pLimit;
111083      p->pLimit = 0;
111084      pOffset = p->pOffset;
111085      p->pOffset = 0;
111086      intersectdest.iSDParm = tab2;
111087      explainSetInteger(iSub2, pParse->iNextSelectId);
111088      rc = sqlite3Select(pParse, p, &intersectdest);
111089      testcase( rc!=SQLITE_OK );
111090      pDelete = p->pPrior;
111091      p->pPrior = pPrior;
111092      if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
111093      sqlite3ExprDelete(db, p->pLimit);
111094      p->pLimit = pLimit;
111095      p->pOffset = pOffset;
111096
111097      /* Generate code to take the intersection of the two temporary
111098      ** tables.
111099      */
111100      assert( p->pEList );
111101      if( dest.eDest==SRT_Output ){
111102        Select *pFirst = p;
111103        while( pFirst->pPrior ) pFirst = pFirst->pPrior;
111104        generateColumnNames(pParse, 0, pFirst->pEList);
111105      }
111106      iBreak = sqlite3VdbeMakeLabel(v);
111107      iCont = sqlite3VdbeMakeLabel(v);
111108      computeLimitRegisters(pParse, p, iBreak);
111109      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
111110      r1 = sqlite3GetTempReg(pParse);
111111      iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
111112      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
111113      sqlite3ReleaseTempReg(pParse, r1);
111114      selectInnerLoop(pParse, p, p->pEList, tab1,
111115                      0, 0, &dest, iCont, iBreak);
111116      sqlite3VdbeResolveLabel(v, iCont);
111117      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
111118      sqlite3VdbeResolveLabel(v, iBreak);
111119      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
111120      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
111121      break;
111122    }
111123  }
111124
111125  explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
111126
111127  /* Compute collating sequences used by
111128  ** temporary tables needed to implement the compound select.
111129  ** Attach the KeyInfo structure to all temporary tables.
111130  **
111131  ** This section is run by the right-most SELECT statement only.
111132  ** SELECT statements to the left always skip this part.  The right-most
111133  ** SELECT might also skip this part if it has no ORDER BY clause and
111134  ** no temp tables are required.
111135  */
111136  if( p->selFlags & SF_UsesEphemeral ){
111137    int i;                        /* Loop counter */
111138    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
111139    Select *pLoop;                /* For looping through SELECT statements */
111140    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
111141    int nCol;                     /* Number of columns in result set */
111142
111143    assert( p->pNext==0 );
111144    nCol = p->pEList->nExpr;
111145    pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
111146    if( !pKeyInfo ){
111147      rc = SQLITE_NOMEM;
111148      goto multi_select_end;
111149    }
111150    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
111151      *apColl = multiSelectCollSeq(pParse, p, i);
111152      if( 0==*apColl ){
111153        *apColl = db->pDfltColl;
111154      }
111155    }
111156
111157    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
111158      for(i=0; i<2; i++){
111159        int addr = pLoop->addrOpenEphm[i];
111160        if( addr<0 ){
111161          /* If [0] is unused then [1] is also unused.  So we can
111162          ** always safely abort as soon as the first unused slot is found */
111163          assert( pLoop->addrOpenEphm[1]<0 );
111164          break;
111165        }
111166        sqlite3VdbeChangeP2(v, addr, nCol);
111167        sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
111168                            P4_KEYINFO);
111169        pLoop->addrOpenEphm[i] = -1;
111170      }
111171    }
111172    sqlite3KeyInfoUnref(pKeyInfo);
111173  }
111174
111175multi_select_end:
111176  pDest->iSdst = dest.iSdst;
111177  pDest->nSdst = dest.nSdst;
111178  sqlite3SelectDelete(db, pDelete);
111179  return rc;
111180}
111181#endif /* SQLITE_OMIT_COMPOUND_SELECT */
111182
111183/*
111184** Error message for when two or more terms of a compound select have different
111185** size result sets.
111186*/
111187SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
111188  if( p->selFlags & SF_Values ){
111189    sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
111190  }else{
111191    sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
111192      " do not have the same number of result columns", selectOpName(p->op));
111193  }
111194}
111195
111196/*
111197** Code an output subroutine for a coroutine implementation of a
111198** SELECT statment.
111199**
111200** The data to be output is contained in pIn->iSdst.  There are
111201** pIn->nSdst columns to be output.  pDest is where the output should
111202** be sent.
111203**
111204** regReturn is the number of the register holding the subroutine
111205** return address.
111206**
111207** If regPrev>0 then it is the first register in a vector that
111208** records the previous output.  mem[regPrev] is a flag that is false
111209** if there has been no previous output.  If regPrev>0 then code is
111210** generated to suppress duplicates.  pKeyInfo is used for comparing
111211** keys.
111212**
111213** If the LIMIT found in p->iLimit is reached, jump immediately to
111214** iBreak.
111215*/
111216static int generateOutputSubroutine(
111217  Parse *pParse,          /* Parsing context */
111218  Select *p,              /* The SELECT statement */
111219  SelectDest *pIn,        /* Coroutine supplying data */
111220  SelectDest *pDest,      /* Where to send the data */
111221  int regReturn,          /* The return address register */
111222  int regPrev,            /* Previous result register.  No uniqueness if 0 */
111223  KeyInfo *pKeyInfo,      /* For comparing with previous entry */
111224  int iBreak              /* Jump here if we hit the LIMIT */
111225){
111226  Vdbe *v = pParse->pVdbe;
111227  int iContinue;
111228  int addr;
111229
111230  addr = sqlite3VdbeCurrentAddr(v);
111231  iContinue = sqlite3VdbeMakeLabel(v);
111232
111233  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
111234  */
111235  if( regPrev ){
111236    int addr1, addr2;
111237    addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
111238    addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
111239                              (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
111240    sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
111241    sqlite3VdbeJumpHere(v, addr1);
111242    sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
111243    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
111244  }
111245  if( pParse->db->mallocFailed ) return 0;
111246
111247  /* Suppress the first OFFSET entries if there is an OFFSET clause
111248  */
111249  codeOffset(v, p->iOffset, iContinue);
111250
111251  assert( pDest->eDest!=SRT_Exists );
111252  assert( pDest->eDest!=SRT_Table );
111253  switch( pDest->eDest ){
111254    /* Store the result as data using a unique key.
111255    */
111256    case SRT_EphemTab: {
111257      int r1 = sqlite3GetTempReg(pParse);
111258      int r2 = sqlite3GetTempReg(pParse);
111259      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
111260      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
111261      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
111262      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
111263      sqlite3ReleaseTempReg(pParse, r2);
111264      sqlite3ReleaseTempReg(pParse, r1);
111265      break;
111266    }
111267
111268#ifndef SQLITE_OMIT_SUBQUERY
111269    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
111270    ** then there should be a single item on the stack.  Write this
111271    ** item into the set table with bogus data.
111272    */
111273    case SRT_Set: {
111274      int r1;
111275      assert( pIn->nSdst==1 || pParse->nErr>0 );
111276      pDest->affSdst =
111277         sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
111278      r1 = sqlite3GetTempReg(pParse);
111279      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
111280      sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
111281      sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
111282      sqlite3ReleaseTempReg(pParse, r1);
111283      break;
111284    }
111285
111286    /* If this is a scalar select that is part of an expression, then
111287    ** store the results in the appropriate memory cell and break out
111288    ** of the scan loop.
111289    */
111290    case SRT_Mem: {
111291      assert( pIn->nSdst==1 || pParse->nErr>0 );  testcase( pIn->nSdst!=1 );
111292      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
111293      /* The LIMIT clause will jump out of the loop for us */
111294      break;
111295    }
111296#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
111297
111298    /* The results are stored in a sequence of registers
111299    ** starting at pDest->iSdst.  Then the co-routine yields.
111300    */
111301    case SRT_Coroutine: {
111302      if( pDest->iSdst==0 ){
111303        pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
111304        pDest->nSdst = pIn->nSdst;
111305      }
111306      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
111307      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
111308      break;
111309    }
111310
111311    /* If none of the above, then the result destination must be
111312    ** SRT_Output.  This routine is never called with any other
111313    ** destination other than the ones handled above or SRT_Output.
111314    **
111315    ** For SRT_Output, results are stored in a sequence of registers.
111316    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
111317    ** return the next row of result.
111318    */
111319    default: {
111320      assert( pDest->eDest==SRT_Output );
111321      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
111322      sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
111323      break;
111324    }
111325  }
111326
111327  /* Jump to the end of the loop if the LIMIT is reached.
111328  */
111329  if( p->iLimit ){
111330    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
111331  }
111332
111333  /* Generate the subroutine return
111334  */
111335  sqlite3VdbeResolveLabel(v, iContinue);
111336  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
111337
111338  return addr;
111339}
111340
111341/*
111342** Alternative compound select code generator for cases when there
111343** is an ORDER BY clause.
111344**
111345** We assume a query of the following form:
111346**
111347**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
111348**
111349** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
111350** is to code both <selectA> and <selectB> with the ORDER BY clause as
111351** co-routines.  Then run the co-routines in parallel and merge the results
111352** into the output.  In addition to the two coroutines (called selectA and
111353** selectB) there are 7 subroutines:
111354**
111355**    outA:    Move the output of the selectA coroutine into the output
111356**             of the compound query.
111357**
111358**    outB:    Move the output of the selectB coroutine into the output
111359**             of the compound query.  (Only generated for UNION and
111360**             UNION ALL.  EXCEPT and INSERTSECT never output a row that
111361**             appears only in B.)
111362**
111363**    AltB:    Called when there is data from both coroutines and A<B.
111364**
111365**    AeqB:    Called when there is data from both coroutines and A==B.
111366**
111367**    AgtB:    Called when there is data from both coroutines and A>B.
111368**
111369**    EofA:    Called when data is exhausted from selectA.
111370**
111371**    EofB:    Called when data is exhausted from selectB.
111372**
111373** The implementation of the latter five subroutines depend on which
111374** <operator> is used:
111375**
111376**
111377**             UNION ALL         UNION            EXCEPT          INTERSECT
111378**          -------------  -----------------  --------------  -----------------
111379**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
111380**
111381**   AeqB:   outA, nextA         nextA             nextA         outA, nextA
111382**
111383**   AgtB:   outB, nextB      outB, nextB          nextB            nextB
111384**
111385**   EofA:   outB, nextB      outB, nextB          halt             halt
111386**
111387**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
111388**
111389** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
111390** causes an immediate jump to EofA and an EOF on B following nextB causes
111391** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
111392** following nextX causes a jump to the end of the select processing.
111393**
111394** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
111395** within the output subroutine.  The regPrev register set holds the previously
111396** output value.  A comparison is made against this value and the output
111397** is skipped if the next results would be the same as the previous.
111398**
111399** The implementation plan is to implement the two coroutines and seven
111400** subroutines first, then put the control logic at the bottom.  Like this:
111401**
111402**          goto Init
111403**     coA: coroutine for left query (A)
111404**     coB: coroutine for right query (B)
111405**    outA: output one row of A
111406**    outB: output one row of B (UNION and UNION ALL only)
111407**    EofA: ...
111408**    EofB: ...
111409**    AltB: ...
111410**    AeqB: ...
111411**    AgtB: ...
111412**    Init: initialize coroutine registers
111413**          yield coA
111414**          if eof(A) goto EofA
111415**          yield coB
111416**          if eof(B) goto EofB
111417**    Cmpr: Compare A, B
111418**          Jump AltB, AeqB, AgtB
111419**     End: ...
111420**
111421** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
111422** actually called using Gosub and they do not Return.  EofA and EofB loop
111423** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
111424** and AgtB jump to either L2 or to one of EofA or EofB.
111425*/
111426#ifndef SQLITE_OMIT_COMPOUND_SELECT
111427static int multiSelectOrderBy(
111428  Parse *pParse,        /* Parsing context */
111429  Select *p,            /* The right-most of SELECTs to be coded */
111430  SelectDest *pDest     /* What to do with query results */
111431){
111432  int i, j;             /* Loop counters */
111433  Select *pPrior;       /* Another SELECT immediately to our left */
111434  Vdbe *v;              /* Generate code to this VDBE */
111435  SelectDest destA;     /* Destination for coroutine A */
111436  SelectDest destB;     /* Destination for coroutine B */
111437  int regAddrA;         /* Address register for select-A coroutine */
111438  int regAddrB;         /* Address register for select-B coroutine */
111439  int addrSelectA;      /* Address of the select-A coroutine */
111440  int addrSelectB;      /* Address of the select-B coroutine */
111441  int regOutA;          /* Address register for the output-A subroutine */
111442  int regOutB;          /* Address register for the output-B subroutine */
111443  int addrOutA;         /* Address of the output-A subroutine */
111444  int addrOutB = 0;     /* Address of the output-B subroutine */
111445  int addrEofA;         /* Address of the select-A-exhausted subroutine */
111446  int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
111447  int addrEofB;         /* Address of the select-B-exhausted subroutine */
111448  int addrAltB;         /* Address of the A<B subroutine */
111449  int addrAeqB;         /* Address of the A==B subroutine */
111450  int addrAgtB;         /* Address of the A>B subroutine */
111451  int regLimitA;        /* Limit register for select-A */
111452  int regLimitB;        /* Limit register for select-A */
111453  int regPrev;          /* A range of registers to hold previous output */
111454  int savedLimit;       /* Saved value of p->iLimit */
111455  int savedOffset;      /* Saved value of p->iOffset */
111456  int labelCmpr;        /* Label for the start of the merge algorithm */
111457  int labelEnd;         /* Label for the end of the overall SELECT stmt */
111458  int addr1;            /* Jump instructions that get retargetted */
111459  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
111460  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
111461  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
111462  sqlite3 *db;          /* Database connection */
111463  ExprList *pOrderBy;   /* The ORDER BY clause */
111464  int nOrderBy;         /* Number of terms in the ORDER BY clause */
111465  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
111466#ifndef SQLITE_OMIT_EXPLAIN
111467  int iSub1;            /* EQP id of left-hand query */
111468  int iSub2;            /* EQP id of right-hand query */
111469#endif
111470
111471  assert( p->pOrderBy!=0 );
111472  assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
111473  db = pParse->db;
111474  v = pParse->pVdbe;
111475  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
111476  labelEnd = sqlite3VdbeMakeLabel(v);
111477  labelCmpr = sqlite3VdbeMakeLabel(v);
111478
111479
111480  /* Patch up the ORDER BY clause
111481  */
111482  op = p->op;
111483  pPrior = p->pPrior;
111484  assert( pPrior->pOrderBy==0 );
111485  pOrderBy = p->pOrderBy;
111486  assert( pOrderBy );
111487  nOrderBy = pOrderBy->nExpr;
111488
111489  /* For operators other than UNION ALL we have to make sure that
111490  ** the ORDER BY clause covers every term of the result set.  Add
111491  ** terms to the ORDER BY clause as necessary.
111492  */
111493  if( op!=TK_ALL ){
111494    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
111495      struct ExprList_item *pItem;
111496      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
111497        assert( pItem->u.x.iOrderByCol>0 );
111498        if( pItem->u.x.iOrderByCol==i ) break;
111499      }
111500      if( j==nOrderBy ){
111501        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
111502        if( pNew==0 ) return SQLITE_NOMEM;
111503        pNew->flags |= EP_IntValue;
111504        pNew->u.iValue = i;
111505        pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
111506        if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
111507      }
111508    }
111509  }
111510
111511  /* Compute the comparison permutation and keyinfo that is used with
111512  ** the permutation used to determine if the next
111513  ** row of results comes from selectA or selectB.  Also add explicit
111514  ** collations to the ORDER BY clause terms so that when the subqueries
111515  ** to the right and the left are evaluated, they use the correct
111516  ** collation.
111517  */
111518  aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
111519  if( aPermute ){
111520    struct ExprList_item *pItem;
111521    for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
111522      assert( pItem->u.x.iOrderByCol>0 );
111523      assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
111524      aPermute[i] = pItem->u.x.iOrderByCol - 1;
111525    }
111526    pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
111527  }else{
111528    pKeyMerge = 0;
111529  }
111530
111531  /* Reattach the ORDER BY clause to the query.
111532  */
111533  p->pOrderBy = pOrderBy;
111534  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
111535
111536  /* Allocate a range of temporary registers and the KeyInfo needed
111537  ** for the logic that removes duplicate result rows when the
111538  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
111539  */
111540  if( op==TK_ALL ){
111541    regPrev = 0;
111542  }else{
111543    int nExpr = p->pEList->nExpr;
111544    assert( nOrderBy>=nExpr || db->mallocFailed );
111545    regPrev = pParse->nMem+1;
111546    pParse->nMem += nExpr+1;
111547    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
111548    pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
111549    if( pKeyDup ){
111550      assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
111551      for(i=0; i<nExpr; i++){
111552        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
111553        pKeyDup->aSortOrder[i] = 0;
111554      }
111555    }
111556  }
111557
111558  /* Separate the left and the right query from one another
111559  */
111560  p->pPrior = 0;
111561  pPrior->pNext = 0;
111562  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
111563  if( pPrior->pPrior==0 ){
111564    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
111565  }
111566
111567  /* Compute the limit registers */
111568  computeLimitRegisters(pParse, p, labelEnd);
111569  if( p->iLimit && op==TK_ALL ){
111570    regLimitA = ++pParse->nMem;
111571    regLimitB = ++pParse->nMem;
111572    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
111573                                  regLimitA);
111574    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
111575  }else{
111576    regLimitA = regLimitB = 0;
111577  }
111578  sqlite3ExprDelete(db, p->pLimit);
111579  p->pLimit = 0;
111580  sqlite3ExprDelete(db, p->pOffset);
111581  p->pOffset = 0;
111582
111583  regAddrA = ++pParse->nMem;
111584  regAddrB = ++pParse->nMem;
111585  regOutA = ++pParse->nMem;
111586  regOutB = ++pParse->nMem;
111587  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
111588  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
111589
111590  /* Generate a coroutine to evaluate the SELECT statement to the
111591  ** left of the compound operator - the "A" select.
111592  */
111593  addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
111594  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
111595  VdbeComment((v, "left SELECT"));
111596  pPrior->iLimit = regLimitA;
111597  explainSetInteger(iSub1, pParse->iNextSelectId);
111598  sqlite3Select(pParse, pPrior, &destA);
111599  sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA);
111600  sqlite3VdbeJumpHere(v, addr1);
111601
111602  /* Generate a coroutine to evaluate the SELECT statement on
111603  ** the right - the "B" select
111604  */
111605  addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
111606  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
111607  VdbeComment((v, "right SELECT"));
111608  savedLimit = p->iLimit;
111609  savedOffset = p->iOffset;
111610  p->iLimit = regLimitB;
111611  p->iOffset = 0;
111612  explainSetInteger(iSub2, pParse->iNextSelectId);
111613  sqlite3Select(pParse, p, &destB);
111614  p->iLimit = savedLimit;
111615  p->iOffset = savedOffset;
111616  sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB);
111617
111618  /* Generate a subroutine that outputs the current row of the A
111619  ** select as the next output row of the compound select.
111620  */
111621  VdbeNoopComment((v, "Output routine for A"));
111622  addrOutA = generateOutputSubroutine(pParse,
111623                 p, &destA, pDest, regOutA,
111624                 regPrev, pKeyDup, labelEnd);
111625
111626  /* Generate a subroutine that outputs the current row of the B
111627  ** select as the next output row of the compound select.
111628  */
111629  if( op==TK_ALL || op==TK_UNION ){
111630    VdbeNoopComment((v, "Output routine for B"));
111631    addrOutB = generateOutputSubroutine(pParse,
111632                 p, &destB, pDest, regOutB,
111633                 regPrev, pKeyDup, labelEnd);
111634  }
111635  sqlite3KeyInfoUnref(pKeyDup);
111636
111637  /* Generate a subroutine to run when the results from select A
111638  ** are exhausted and only data in select B remains.
111639  */
111640  if( op==TK_EXCEPT || op==TK_INTERSECT ){
111641    addrEofA_noB = addrEofA = labelEnd;
111642  }else{
111643    VdbeNoopComment((v, "eof-A subroutine"));
111644    addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
111645    addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
111646                                     VdbeCoverage(v);
111647    sqlite3VdbeGoto(v, addrEofA);
111648    p->nSelectRow += pPrior->nSelectRow;
111649  }
111650
111651  /* Generate a subroutine to run when the results from select B
111652  ** are exhausted and only data in select A remains.
111653  */
111654  if( op==TK_INTERSECT ){
111655    addrEofB = addrEofA;
111656    if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
111657  }else{
111658    VdbeNoopComment((v, "eof-B subroutine"));
111659    addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
111660    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
111661    sqlite3VdbeGoto(v, addrEofB);
111662  }
111663
111664  /* Generate code to handle the case of A<B
111665  */
111666  VdbeNoopComment((v, "A-lt-B subroutine"));
111667  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
111668  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
111669  sqlite3VdbeGoto(v, labelCmpr);
111670
111671  /* Generate code to handle the case of A==B
111672  */
111673  if( op==TK_ALL ){
111674    addrAeqB = addrAltB;
111675  }else if( op==TK_INTERSECT ){
111676    addrAeqB = addrAltB;
111677    addrAltB++;
111678  }else{
111679    VdbeNoopComment((v, "A-eq-B subroutine"));
111680    addrAeqB =
111681    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
111682    sqlite3VdbeGoto(v, labelCmpr);
111683  }
111684
111685  /* Generate code to handle the case of A>B
111686  */
111687  VdbeNoopComment((v, "A-gt-B subroutine"));
111688  addrAgtB = sqlite3VdbeCurrentAddr(v);
111689  if( op==TK_ALL || op==TK_UNION ){
111690    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
111691  }
111692  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
111693  sqlite3VdbeGoto(v, labelCmpr);
111694
111695  /* This code runs once to initialize everything.
111696  */
111697  sqlite3VdbeJumpHere(v, addr1);
111698  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
111699  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
111700
111701  /* Implement the main merge loop
111702  */
111703  sqlite3VdbeResolveLabel(v, labelCmpr);
111704  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
111705  sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
111706                         (char*)pKeyMerge, P4_KEYINFO);
111707  sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
111708  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
111709
111710  /* Jump to the this point in order to terminate the query.
111711  */
111712  sqlite3VdbeResolveLabel(v, labelEnd);
111713
111714  /* Set the number of output columns
111715  */
111716  if( pDest->eDest==SRT_Output ){
111717    Select *pFirst = pPrior;
111718    while( pFirst->pPrior ) pFirst = pFirst->pPrior;
111719    generateColumnNames(pParse, 0, pFirst->pEList);
111720  }
111721
111722  /* Reassembly the compound query so that it will be freed correctly
111723  ** by the calling function */
111724  if( p->pPrior ){
111725    sqlite3SelectDelete(db, p->pPrior);
111726  }
111727  p->pPrior = pPrior;
111728  pPrior->pNext = p;
111729
111730  /*** TBD:  Insert subroutine calls to close cursors on incomplete
111731  **** subqueries ****/
111732  explainComposite(pParse, p->op, iSub1, iSub2, 0);
111733  return pParse->nErr!=0;
111734}
111735#endif
111736
111737#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
111738/* Forward Declarations */
111739static void substExprList(sqlite3*, ExprList*, int, ExprList*);
111740static void substSelect(sqlite3*, Select *, int, ExprList*, int);
111741
111742/*
111743** Scan through the expression pExpr.  Replace every reference to
111744** a column in table number iTable with a copy of the iColumn-th
111745** entry in pEList.  (But leave references to the ROWID column
111746** unchanged.)
111747**
111748** This routine is part of the flattening procedure.  A subquery
111749** whose result set is defined by pEList appears as entry in the
111750** FROM clause of a SELECT such that the VDBE cursor assigned to that
111751** FORM clause entry is iTable.  This routine make the necessary
111752** changes to pExpr so that it refers directly to the source table
111753** of the subquery rather the result set of the subquery.
111754*/
111755static Expr *substExpr(
111756  sqlite3 *db,        /* Report malloc errors to this connection */
111757  Expr *pExpr,        /* Expr in which substitution occurs */
111758  int iTable,         /* Table to be substituted */
111759  ExprList *pEList    /* Substitute expressions */
111760){
111761  if( pExpr==0 ) return 0;
111762  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
111763    if( pExpr->iColumn<0 ){
111764      pExpr->op = TK_NULL;
111765    }else{
111766      Expr *pNew;
111767      assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
111768      assert( pExpr->pLeft==0 && pExpr->pRight==0 );
111769      pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
111770      sqlite3ExprDelete(db, pExpr);
111771      pExpr = pNew;
111772    }
111773  }else{
111774    pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
111775    pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
111776    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
111777      substSelect(db, pExpr->x.pSelect, iTable, pEList, 1);
111778    }else{
111779      substExprList(db, pExpr->x.pList, iTable, pEList);
111780    }
111781  }
111782  return pExpr;
111783}
111784static void substExprList(
111785  sqlite3 *db,         /* Report malloc errors here */
111786  ExprList *pList,     /* List to scan and in which to make substitutes */
111787  int iTable,          /* Table to be substituted */
111788  ExprList *pEList     /* Substitute values */
111789){
111790  int i;
111791  if( pList==0 ) return;
111792  for(i=0; i<pList->nExpr; i++){
111793    pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
111794  }
111795}
111796static void substSelect(
111797  sqlite3 *db,         /* Report malloc errors here */
111798  Select *p,           /* SELECT statement in which to make substitutions */
111799  int iTable,          /* Table to be replaced */
111800  ExprList *pEList,    /* Substitute values */
111801  int doPrior          /* Do substitutes on p->pPrior too */
111802){
111803  SrcList *pSrc;
111804  struct SrcList_item *pItem;
111805  int i;
111806  if( !p ) return;
111807  do{
111808    substExprList(db, p->pEList, iTable, pEList);
111809    substExprList(db, p->pGroupBy, iTable, pEList);
111810    substExprList(db, p->pOrderBy, iTable, pEList);
111811    p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
111812    p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
111813    pSrc = p->pSrc;
111814    assert( pSrc!=0 );
111815    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
111816      substSelect(db, pItem->pSelect, iTable, pEList, 1);
111817      if( pItem->fg.isTabFunc ){
111818        substExprList(db, pItem->u1.pFuncArg, iTable, pEList);
111819      }
111820    }
111821  }while( doPrior && (p = p->pPrior)!=0 );
111822}
111823#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
111824
111825#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
111826/*
111827** This routine attempts to flatten subqueries as a performance optimization.
111828** This routine returns 1 if it makes changes and 0 if no flattening occurs.
111829**
111830** To understand the concept of flattening, consider the following
111831** query:
111832**
111833**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
111834**
111835** The default way of implementing this query is to execute the
111836** subquery first and store the results in a temporary table, then
111837** run the outer query on that temporary table.  This requires two
111838** passes over the data.  Furthermore, because the temporary table
111839** has no indices, the WHERE clause on the outer query cannot be
111840** optimized.
111841**
111842** This routine attempts to rewrite queries such as the above into
111843** a single flat select, like this:
111844**
111845**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
111846**
111847** The code generated for this simplification gives the same result
111848** but only has to scan the data once.  And because indices might
111849** exist on the table t1, a complete scan of the data might be
111850** avoided.
111851**
111852** Flattening is only attempted if all of the following are true:
111853**
111854**   (1)  The subquery and the outer query do not both use aggregates.
111855**
111856**   (2)  The subquery is not an aggregate or (2a) the outer query is not a join
111857**        and (2b) the outer query does not use subqueries other than the one
111858**        FROM-clause subquery that is a candidate for flattening.  (2b is
111859**        due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
111860**
111861**   (3)  The subquery is not the right operand of a left outer join
111862**        (Originally ticket #306.  Strengthened by ticket #3300)
111863**
111864**   (4)  The subquery is not DISTINCT.
111865**
111866**  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
111867**        sub-queries that were excluded from this optimization. Restriction
111868**        (4) has since been expanded to exclude all DISTINCT subqueries.
111869**
111870**   (6)  The subquery does not use aggregates or the outer query is not
111871**        DISTINCT.
111872**
111873**   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
111874**        A FROM clause, consider adding a FROM close with the special
111875**        table sqlite_once that consists of a single row containing a
111876**        single NULL.
111877**
111878**   (8)  The subquery does not use LIMIT or the outer query is not a join.
111879**
111880**   (9)  The subquery does not use LIMIT or the outer query does not use
111881**        aggregates.
111882**
111883**  (**)  Restriction (10) was removed from the code on 2005-02-05 but we
111884**        accidently carried the comment forward until 2014-09-15.  Original
111885**        text: "The subquery does not use aggregates or the outer query
111886**        does not use LIMIT."
111887**
111888**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
111889**
111890**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
111891**        a separate restriction deriving from ticket #350.
111892**
111893**  (13)  The subquery and outer query do not both use LIMIT.
111894**
111895**  (14)  The subquery does not use OFFSET.
111896**
111897**  (15)  The outer query is not part of a compound select or the
111898**        subquery does not have a LIMIT clause.
111899**        (See ticket #2339 and ticket [02a8e81d44]).
111900**
111901**  (16)  The outer query is not an aggregate or the subquery does
111902**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
111903**        until we introduced the group_concat() function.
111904**
111905**  (17)  The sub-query is not a compound select, or it is a UNION ALL
111906**        compound clause made up entirely of non-aggregate queries, and
111907**        the parent query:
111908**
111909**          * is not itself part of a compound select,
111910**          * is not an aggregate or DISTINCT query, and
111911**          * is not a join
111912**
111913**        The parent and sub-query may contain WHERE clauses. Subject to
111914**        rules (11), (13) and (14), they may also contain ORDER BY,
111915**        LIMIT and OFFSET clauses.  The subquery cannot use any compound
111916**        operator other than UNION ALL because all the other compound
111917**        operators have an implied DISTINCT which is disallowed by
111918**        restriction (4).
111919**
111920**        Also, each component of the sub-query must return the same number
111921**        of result columns. This is actually a requirement for any compound
111922**        SELECT statement, but all the code here does is make sure that no
111923**        such (illegal) sub-query is flattened. The caller will detect the
111924**        syntax error and return a detailed message.
111925**
111926**  (18)  If the sub-query is a compound select, then all terms of the
111927**        ORDER by clause of the parent must be simple references to
111928**        columns of the sub-query.
111929**
111930**  (19)  The subquery does not use LIMIT or the outer query does not
111931**        have a WHERE clause.
111932**
111933**  (20)  If the sub-query is a compound select, then it must not use
111934**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
111935**        somewhat by saying that the terms of the ORDER BY clause must
111936**        appear as unmodified result columns in the outer query.  But we
111937**        have other optimizations in mind to deal with that case.
111938**
111939**  (21)  The subquery does not use LIMIT or the outer query is not
111940**        DISTINCT.  (See ticket [752e1646fc]).
111941**
111942**  (22)  The subquery is not a recursive CTE.
111943**
111944**  (23)  The parent is not a recursive CTE, or the sub-query is not a
111945**        compound query. This restriction is because transforming the
111946**        parent to a compound query confuses the code that handles
111947**        recursive queries in multiSelect().
111948**
111949**  (24)  The subquery is not an aggregate that uses the built-in min() or
111950**        or max() functions.  (Without this restriction, a query like:
111951**        "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
111952**        return the value X for which Y was maximal.)
111953**
111954**
111955** In this routine, the "p" parameter is a pointer to the outer query.
111956** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
111957** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
111958**
111959** If flattening is not attempted, this routine is a no-op and returns 0.
111960** If flattening is attempted this routine returns 1.
111961**
111962** All of the expression analysis must occur on both the outer query and
111963** the subquery before this routine runs.
111964*/
111965static int flattenSubquery(
111966  Parse *pParse,       /* Parsing context */
111967  Select *p,           /* The parent or outer SELECT statement */
111968  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
111969  int isAgg,           /* True if outer SELECT uses aggregate functions */
111970  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
111971){
111972  const char *zSavedAuthContext = pParse->zAuthContext;
111973  Select *pParent;    /* Current UNION ALL term of the other query */
111974  Select *pSub;       /* The inner query or "subquery" */
111975  Select *pSub1;      /* Pointer to the rightmost select in sub-query */
111976  SrcList *pSrc;      /* The FROM clause of the outer query */
111977  SrcList *pSubSrc;   /* The FROM clause of the subquery */
111978  ExprList *pList;    /* The result set of the outer query */
111979  int iParent;        /* VDBE cursor number of the pSub result set temp table */
111980  int i;              /* Loop counter */
111981  Expr *pWhere;                    /* The WHERE clause */
111982  struct SrcList_item *pSubitem;   /* The subquery */
111983  sqlite3 *db = pParse->db;
111984
111985  /* Check to see if flattening is permitted.  Return 0 if not.
111986  */
111987  assert( p!=0 );
111988  assert( p->pPrior==0 );  /* Unable to flatten compound queries */
111989  if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
111990  pSrc = p->pSrc;
111991  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
111992  pSubitem = &pSrc->a[iFrom];
111993  iParent = pSubitem->iCursor;
111994  pSub = pSubitem->pSelect;
111995  assert( pSub!=0 );
111996  if( subqueryIsAgg ){
111997    if( isAgg ) return 0;                                /* Restriction (1)   */
111998    if( pSrc->nSrc>1 ) return 0;                         /* Restriction (2a)  */
111999    if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
112000     || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
112001     || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
112002    ){
112003      return 0;                                          /* Restriction (2b)  */
112004    }
112005  }
112006
112007  pSubSrc = pSub->pSrc;
112008  assert( pSubSrc );
112009  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
112010  ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
112011  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
112012  ** became arbitrary expressions, we were forced to add restrictions (13)
112013  ** and (14). */
112014  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
112015  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
112016  if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
112017    return 0;                                            /* Restriction (15) */
112018  }
112019  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
112020  if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
112021  if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
112022     return 0;         /* Restrictions (8)(9) */
112023  }
112024  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
112025     return 0;         /* Restriction (6)  */
112026  }
112027  if( p->pOrderBy && pSub->pOrderBy ){
112028     return 0;                                           /* Restriction (11) */
112029  }
112030  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
112031  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
112032  if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
112033     return 0;         /* Restriction (21) */
112034  }
112035  testcase( pSub->selFlags & SF_Recursive );
112036  testcase( pSub->selFlags & SF_MinMaxAgg );
112037  if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
112038    return 0; /* Restrictions (22) and (24) */
112039  }
112040  if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
112041    return 0; /* Restriction (23) */
112042  }
112043
112044  /* OBSOLETE COMMENT 1:
112045  ** Restriction 3:  If the subquery is a join, make sure the subquery is
112046  ** not used as the right operand of an outer join.  Examples of why this
112047  ** is not allowed:
112048  **
112049  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
112050  **
112051  ** If we flatten the above, we would get
112052  **
112053  **         (t1 LEFT OUTER JOIN t2) JOIN t3
112054  **
112055  ** which is not at all the same thing.
112056  **
112057  ** OBSOLETE COMMENT 2:
112058  ** Restriction 12:  If the subquery is the right operand of a left outer
112059  ** join, make sure the subquery has no WHERE clause.
112060  ** An examples of why this is not allowed:
112061  **
112062  **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
112063  **
112064  ** If we flatten the above, we would get
112065  **
112066  **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
112067  **
112068  ** But the t2.x>0 test will always fail on a NULL row of t2, which
112069  ** effectively converts the OUTER JOIN into an INNER JOIN.
112070  **
112071  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
112072  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
112073  ** is fraught with danger.  Best to avoid the whole thing.  If the
112074  ** subquery is the right term of a LEFT JOIN, then do not flatten.
112075  */
112076  if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
112077    return 0;
112078  }
112079
112080  /* Restriction 17: If the sub-query is a compound SELECT, then it must
112081  ** use only the UNION ALL operator. And none of the simple select queries
112082  ** that make up the compound SELECT are allowed to be aggregate or distinct
112083  ** queries.
112084  */
112085  if( pSub->pPrior ){
112086    if( pSub->pOrderBy ){
112087      return 0;  /* Restriction 20 */
112088    }
112089    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
112090      return 0;
112091    }
112092    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
112093      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
112094      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
112095      assert( pSub->pSrc!=0 );
112096      assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
112097      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
112098       || (pSub1->pPrior && pSub1->op!=TK_ALL)
112099       || pSub1->pSrc->nSrc<1
112100      ){
112101        return 0;
112102      }
112103      testcase( pSub1->pSrc->nSrc>1 );
112104    }
112105
112106    /* Restriction 18. */
112107    if( p->pOrderBy ){
112108      int ii;
112109      for(ii=0; ii<p->pOrderBy->nExpr; ii++){
112110        if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
112111      }
112112    }
112113  }
112114
112115  /***** If we reach this point, flattening is permitted. *****/
112116  SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
112117                   pSub->zSelName, pSub, iFrom));
112118
112119  /* Authorize the subquery */
112120  pParse->zAuthContext = pSubitem->zName;
112121  TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
112122  testcase( i==SQLITE_DENY );
112123  pParse->zAuthContext = zSavedAuthContext;
112124
112125  /* If the sub-query is a compound SELECT statement, then (by restrictions
112126  ** 17 and 18 above) it must be a UNION ALL and the parent query must
112127  ** be of the form:
112128  **
112129  **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
112130  **
112131  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
112132  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
112133  ** OFFSET clauses and joins them to the left-hand-side of the original
112134  ** using UNION ALL operators. In this case N is the number of simple
112135  ** select statements in the compound sub-query.
112136  **
112137  ** Example:
112138  **
112139  **     SELECT a+1 FROM (
112140  **        SELECT x FROM tab
112141  **        UNION ALL
112142  **        SELECT y FROM tab
112143  **        UNION ALL
112144  **        SELECT abs(z*2) FROM tab2
112145  **     ) WHERE a!=5 ORDER BY 1
112146  **
112147  ** Transformed into:
112148  **
112149  **     SELECT x+1 FROM tab WHERE x+1!=5
112150  **     UNION ALL
112151  **     SELECT y+1 FROM tab WHERE y+1!=5
112152  **     UNION ALL
112153  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
112154  **     ORDER BY 1
112155  **
112156  ** We call this the "compound-subquery flattening".
112157  */
112158  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
112159    Select *pNew;
112160    ExprList *pOrderBy = p->pOrderBy;
112161    Expr *pLimit = p->pLimit;
112162    Expr *pOffset = p->pOffset;
112163    Select *pPrior = p->pPrior;
112164    p->pOrderBy = 0;
112165    p->pSrc = 0;
112166    p->pPrior = 0;
112167    p->pLimit = 0;
112168    p->pOffset = 0;
112169    pNew = sqlite3SelectDup(db, p, 0);
112170    sqlite3SelectSetName(pNew, pSub->zSelName);
112171    p->pOffset = pOffset;
112172    p->pLimit = pLimit;
112173    p->pOrderBy = pOrderBy;
112174    p->pSrc = pSrc;
112175    p->op = TK_ALL;
112176    if( pNew==0 ){
112177      p->pPrior = pPrior;
112178    }else{
112179      pNew->pPrior = pPrior;
112180      if( pPrior ) pPrior->pNext = pNew;
112181      pNew->pNext = p;
112182      p->pPrior = pNew;
112183      SELECTTRACE(2,pParse,p,
112184         ("compound-subquery flattener creates %s.%p as peer\n",
112185         pNew->zSelName, pNew));
112186    }
112187    if( db->mallocFailed ) return 1;
112188  }
112189
112190  /* Begin flattening the iFrom-th entry of the FROM clause
112191  ** in the outer query.
112192  */
112193  pSub = pSub1 = pSubitem->pSelect;
112194
112195  /* Delete the transient table structure associated with the
112196  ** subquery
112197  */
112198  sqlite3DbFree(db, pSubitem->zDatabase);
112199  sqlite3DbFree(db, pSubitem->zName);
112200  sqlite3DbFree(db, pSubitem->zAlias);
112201  pSubitem->zDatabase = 0;
112202  pSubitem->zName = 0;
112203  pSubitem->zAlias = 0;
112204  pSubitem->pSelect = 0;
112205
112206  /* Defer deleting the Table object associated with the
112207  ** subquery until code generation is
112208  ** complete, since there may still exist Expr.pTab entries that
112209  ** refer to the subquery even after flattening.  Ticket #3346.
112210  **
112211  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
112212  */
112213  if( ALWAYS(pSubitem->pTab!=0) ){
112214    Table *pTabToDel = pSubitem->pTab;
112215    if( pTabToDel->nRef==1 ){
112216      Parse *pToplevel = sqlite3ParseToplevel(pParse);
112217      pTabToDel->pNextZombie = pToplevel->pZombieTab;
112218      pToplevel->pZombieTab = pTabToDel;
112219    }else{
112220      pTabToDel->nRef--;
112221    }
112222    pSubitem->pTab = 0;
112223  }
112224
112225  /* The following loop runs once for each term in a compound-subquery
112226  ** flattening (as described above).  If we are doing a different kind
112227  ** of flattening - a flattening other than a compound-subquery flattening -
112228  ** then this loop only runs once.
112229  **
112230  ** This loop moves all of the FROM elements of the subquery into the
112231  ** the FROM clause of the outer query.  Before doing this, remember
112232  ** the cursor number for the original outer query FROM element in
112233  ** iParent.  The iParent cursor will never be used.  Subsequent code
112234  ** will scan expressions looking for iParent references and replace
112235  ** those references with expressions that resolve to the subquery FROM
112236  ** elements we are now copying in.
112237  */
112238  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
112239    int nSubSrc;
112240    u8 jointype = 0;
112241    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
112242    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
112243    pSrc = pParent->pSrc;     /* FROM clause of the outer query */
112244
112245    if( pSrc ){
112246      assert( pParent==p );  /* First time through the loop */
112247      jointype = pSubitem->fg.jointype;
112248    }else{
112249      assert( pParent!=p );  /* 2nd and subsequent times through the loop */
112250      pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
112251      if( pSrc==0 ){
112252        assert( db->mallocFailed );
112253        break;
112254      }
112255    }
112256
112257    /* The subquery uses a single slot of the FROM clause of the outer
112258    ** query.  If the subquery has more than one element in its FROM clause,
112259    ** then expand the outer query to make space for it to hold all elements
112260    ** of the subquery.
112261    **
112262    ** Example:
112263    **
112264    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
112265    **
112266    ** The outer query has 3 slots in its FROM clause.  One slot of the
112267    ** outer query (the middle slot) is used by the subquery.  The next
112268    ** block of code will expand the outer query FROM clause to 4 slots.
112269    ** The middle slot is expanded to two slots in order to make space
112270    ** for the two elements in the FROM clause of the subquery.
112271    */
112272    if( nSubSrc>1 ){
112273      pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
112274      if( db->mallocFailed ){
112275        break;
112276      }
112277    }
112278
112279    /* Transfer the FROM clause terms from the subquery into the
112280    ** outer query.
112281    */
112282    for(i=0; i<nSubSrc; i++){
112283      sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
112284      pSrc->a[i+iFrom] = pSubSrc->a[i];
112285      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
112286    }
112287    pSrc->a[iFrom].fg.jointype = jointype;
112288
112289    /* Now begin substituting subquery result set expressions for
112290    ** references to the iParent in the outer query.
112291    **
112292    ** Example:
112293    **
112294    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
112295    **   \                     \_____________ subquery __________/          /
112296    **    \_____________________ outer query ______________________________/
112297    **
112298    ** We look at every expression in the outer query and every place we see
112299    ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
112300    */
112301    pList = pParent->pEList;
112302    for(i=0; i<pList->nExpr; i++){
112303      if( pList->a[i].zName==0 ){
112304        char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
112305        sqlite3Dequote(zName);
112306        pList->a[i].zName = zName;
112307      }
112308    }
112309    if( pSub->pOrderBy ){
112310      /* At this point, any non-zero iOrderByCol values indicate that the
112311      ** ORDER BY column expression is identical to the iOrderByCol'th
112312      ** expression returned by SELECT statement pSub. Since these values
112313      ** do not necessarily correspond to columns in SELECT statement pParent,
112314      ** zero them before transfering the ORDER BY clause.
112315      **
112316      ** Not doing this may cause an error if a subsequent call to this
112317      ** function attempts to flatten a compound sub-query into pParent
112318      ** (the only way this can happen is if the compound sub-query is
112319      ** currently part of pSub->pSrc). See ticket [d11a6e908f].  */
112320      ExprList *pOrderBy = pSub->pOrderBy;
112321      for(i=0; i<pOrderBy->nExpr; i++){
112322        pOrderBy->a[i].u.x.iOrderByCol = 0;
112323      }
112324      assert( pParent->pOrderBy==0 );
112325      assert( pSub->pPrior==0 );
112326      pParent->pOrderBy = pOrderBy;
112327      pSub->pOrderBy = 0;
112328    }
112329    pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
112330    if( subqueryIsAgg ){
112331      assert( pParent->pHaving==0 );
112332      pParent->pHaving = pParent->pWhere;
112333      pParent->pWhere = pWhere;
112334      pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
112335                                  sqlite3ExprDup(db, pSub->pHaving, 0));
112336      assert( pParent->pGroupBy==0 );
112337      pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
112338    }else{
112339      pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
112340    }
112341    substSelect(db, pParent, iParent, pSub->pEList, 0);
112342
112343    /* The flattened query is distinct if either the inner or the
112344    ** outer query is distinct.
112345    */
112346    pParent->selFlags |= pSub->selFlags & SF_Distinct;
112347
112348    /*
112349    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
112350    **
112351    ** One is tempted to try to add a and b to combine the limits.  But this
112352    ** does not work if either limit is negative.
112353    */
112354    if( pSub->pLimit ){
112355      pParent->pLimit = pSub->pLimit;
112356      pSub->pLimit = 0;
112357    }
112358  }
112359
112360  /* Finially, delete what is left of the subquery and return
112361  ** success.
112362  */
112363  sqlite3SelectDelete(db, pSub1);
112364
112365#if SELECTTRACE_ENABLED
112366  if( sqlite3SelectTrace & 0x100 ){
112367    SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
112368    sqlite3TreeViewSelect(0, p, 0);
112369  }
112370#endif
112371
112372  return 1;
112373}
112374#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
112375
112376
112377
112378#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
112379/*
112380** Make copies of relevant WHERE clause terms of the outer query into
112381** the WHERE clause of subquery.  Example:
112382**
112383**    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
112384**
112385** Transformed into:
112386**
112387**    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
112388**     WHERE x=5 AND y=10;
112389**
112390** The hope is that the terms added to the inner query will make it more
112391** efficient.
112392**
112393** Do not attempt this optimization if:
112394**
112395**   (1) The inner query is an aggregate.  (In that case, we'd really want
112396**       to copy the outer WHERE-clause terms onto the HAVING clause of the
112397**       inner query.  But they probably won't help there so do not bother.)
112398**
112399**   (2) The inner query is the recursive part of a common table expression.
112400**
112401**   (3) The inner query has a LIMIT clause (since the changes to the WHERE
112402**       close would change the meaning of the LIMIT).
112403**
112404**   (4) The inner query is the right operand of a LEFT JOIN.  (The caller
112405**       enforces this restriction since this routine does not have enough
112406**       information to know.)
112407**
112408**   (5) The WHERE clause expression originates in the ON or USING clause
112409**       of a LEFT JOIN.
112410**
112411** Return 0 if no changes are made and non-zero if one or more WHERE clause
112412** terms are duplicated into the subquery.
112413*/
112414static int pushDownWhereTerms(
112415  sqlite3 *db,          /* The database connection (for malloc()) */
112416  Select *pSubq,        /* The subquery whose WHERE clause is to be augmented */
112417  Expr *pWhere,         /* The WHERE clause of the outer query */
112418  int iCursor           /* Cursor number of the subquery */
112419){
112420  Expr *pNew;
112421  int nChng = 0;
112422  if( pWhere==0 ) return 0;
112423  if( (pSubq->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
112424     return 0; /* restrictions (1) and (2) */
112425  }
112426  if( pSubq->pLimit!=0 ){
112427     return 0; /* restriction (3) */
112428  }
112429  while( pWhere->op==TK_AND ){
112430    nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor);
112431    pWhere = pWhere->pLeft;
112432  }
112433  if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */
112434  if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
112435    nChng++;
112436    while( pSubq ){
112437      pNew = sqlite3ExprDup(db, pWhere, 0);
112438      pNew = substExpr(db, pNew, iCursor, pSubq->pEList);
112439      pSubq->pWhere = sqlite3ExprAnd(db, pSubq->pWhere, pNew);
112440      pSubq = pSubq->pPrior;
112441    }
112442  }
112443  return nChng;
112444}
112445#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
112446
112447/*
112448** Based on the contents of the AggInfo structure indicated by the first
112449** argument, this function checks if the following are true:
112450**
112451**    * the query contains just a single aggregate function,
112452**    * the aggregate function is either min() or max(), and
112453**    * the argument to the aggregate function is a column value.
112454**
112455** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
112456** is returned as appropriate. Also, *ppMinMax is set to point to the
112457** list of arguments passed to the aggregate before returning.
112458**
112459** Or, if the conditions above are not met, *ppMinMax is set to 0 and
112460** WHERE_ORDERBY_NORMAL is returned.
112461*/
112462static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
112463  int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
112464
112465  *ppMinMax = 0;
112466  if( pAggInfo->nFunc==1 ){
112467    Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
112468    ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
112469
112470    assert( pExpr->op==TK_AGG_FUNCTION );
112471    if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
112472      const char *zFunc = pExpr->u.zToken;
112473      if( sqlite3StrICmp(zFunc, "min")==0 ){
112474        eRet = WHERE_ORDERBY_MIN;
112475        *ppMinMax = pEList;
112476      }else if( sqlite3StrICmp(zFunc, "max")==0 ){
112477        eRet = WHERE_ORDERBY_MAX;
112478        *ppMinMax = pEList;
112479      }
112480    }
112481  }
112482
112483  assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
112484  return eRet;
112485}
112486
112487/*
112488** The select statement passed as the first argument is an aggregate query.
112489** The second argument is the associated aggregate-info object. This
112490** function tests if the SELECT is of the form:
112491**
112492**   SELECT count(*) FROM <tbl>
112493**
112494** where table is a database table, not a sub-select or view. If the query
112495** does match this pattern, then a pointer to the Table object representing
112496** <tbl> is returned. Otherwise, 0 is returned.
112497*/
112498static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
112499  Table *pTab;
112500  Expr *pExpr;
112501
112502  assert( !p->pGroupBy );
112503
112504  if( p->pWhere || p->pEList->nExpr!=1
112505   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
112506  ){
112507    return 0;
112508  }
112509  pTab = p->pSrc->a[0].pTab;
112510  pExpr = p->pEList->a[0].pExpr;
112511  assert( pTab && !pTab->pSelect && pExpr );
112512
112513  if( IsVirtual(pTab) ) return 0;
112514  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
112515  if( NEVER(pAggInfo->nFunc==0) ) return 0;
112516  if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
112517  if( pExpr->flags&EP_Distinct ) return 0;
112518
112519  return pTab;
112520}
112521
112522/*
112523** If the source-list item passed as an argument was augmented with an
112524** INDEXED BY clause, then try to locate the specified index. If there
112525** was such a clause and the named index cannot be found, return
112526** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
112527** pFrom->pIndex and return SQLITE_OK.
112528*/
112529SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
112530  if( pFrom->pTab && pFrom->fg.isIndexedBy ){
112531    Table *pTab = pFrom->pTab;
112532    char *zIndexedBy = pFrom->u1.zIndexedBy;
112533    Index *pIdx;
112534    for(pIdx=pTab->pIndex;
112535        pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
112536        pIdx=pIdx->pNext
112537    );
112538    if( !pIdx ){
112539      sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
112540      pParse->checkSchema = 1;
112541      return SQLITE_ERROR;
112542    }
112543    pFrom->pIBIndex = pIdx;
112544  }
112545  return SQLITE_OK;
112546}
112547/*
112548** Detect compound SELECT statements that use an ORDER BY clause with
112549** an alternative collating sequence.
112550**
112551**    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
112552**
112553** These are rewritten as a subquery:
112554**
112555**    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
112556**     ORDER BY ... COLLATE ...
112557**
112558** This transformation is necessary because the multiSelectOrderBy() routine
112559** above that generates the code for a compound SELECT with an ORDER BY clause
112560** uses a merge algorithm that requires the same collating sequence on the
112561** result columns as on the ORDER BY clause.  See ticket
112562** http://www.sqlite.org/src/info/6709574d2a
112563**
112564** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
112565** The UNION ALL operator works fine with multiSelectOrderBy() even when
112566** there are COLLATE terms in the ORDER BY.
112567*/
112568static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
112569  int i;
112570  Select *pNew;
112571  Select *pX;
112572  sqlite3 *db;
112573  struct ExprList_item *a;
112574  SrcList *pNewSrc;
112575  Parse *pParse;
112576  Token dummy;
112577
112578  if( p->pPrior==0 ) return WRC_Continue;
112579  if( p->pOrderBy==0 ) return WRC_Continue;
112580  for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
112581  if( pX==0 ) return WRC_Continue;
112582  a = p->pOrderBy->a;
112583  for(i=p->pOrderBy->nExpr-1; i>=0; i--){
112584    if( a[i].pExpr->flags & EP_Collate ) break;
112585  }
112586  if( i<0 ) return WRC_Continue;
112587
112588  /* If we reach this point, that means the transformation is required. */
112589
112590  pParse = pWalker->pParse;
112591  db = pParse->db;
112592  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
112593  if( pNew==0 ) return WRC_Abort;
112594  memset(&dummy, 0, sizeof(dummy));
112595  pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
112596  if( pNewSrc==0 ) return WRC_Abort;
112597  *pNew = *p;
112598  p->pSrc = pNewSrc;
112599  p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
112600  p->op = TK_SELECT;
112601  p->pWhere = 0;
112602  pNew->pGroupBy = 0;
112603  pNew->pHaving = 0;
112604  pNew->pOrderBy = 0;
112605  p->pPrior = 0;
112606  p->pNext = 0;
112607  p->pWith = 0;
112608  p->selFlags &= ~SF_Compound;
112609  assert( (p->selFlags & SF_Converted)==0 );
112610  p->selFlags |= SF_Converted;
112611  assert( pNew->pPrior!=0 );
112612  pNew->pPrior->pNext = pNew;
112613  pNew->pLimit = 0;
112614  pNew->pOffset = 0;
112615  return WRC_Continue;
112616}
112617
112618#ifndef SQLITE_OMIT_CTE
112619/*
112620** Argument pWith (which may be NULL) points to a linked list of nested
112621** WITH contexts, from inner to outermost. If the table identified by
112622** FROM clause element pItem is really a common-table-expression (CTE)
112623** then return a pointer to the CTE definition for that table. Otherwise
112624** return NULL.
112625**
112626** If a non-NULL value is returned, set *ppContext to point to the With
112627** object that the returned CTE belongs to.
112628*/
112629static struct Cte *searchWith(
112630  With *pWith,                    /* Current outermost WITH clause */
112631  struct SrcList_item *pItem,     /* FROM clause element to resolve */
112632  With **ppContext                /* OUT: WITH clause return value belongs to */
112633){
112634  const char *zName;
112635  if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
112636    With *p;
112637    for(p=pWith; p; p=p->pOuter){
112638      int i;
112639      for(i=0; i<p->nCte; i++){
112640        if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
112641          *ppContext = p;
112642          return &p->a[i];
112643        }
112644      }
112645    }
112646  }
112647  return 0;
112648}
112649
112650/* The code generator maintains a stack of active WITH clauses
112651** with the inner-most WITH clause being at the top of the stack.
112652**
112653** This routine pushes the WITH clause passed as the second argument
112654** onto the top of the stack. If argument bFree is true, then this
112655** WITH clause will never be popped from the stack. In this case it
112656** should be freed along with the Parse object. In other cases, when
112657** bFree==0, the With object will be freed along with the SELECT
112658** statement with which it is associated.
112659*/
112660SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
112661  assert( bFree==0 || pParse->pWith==0 );
112662  if( pWith ){
112663    pWith->pOuter = pParse->pWith;
112664    pParse->pWith = pWith;
112665    pParse->bFreeWith = bFree;
112666  }
112667}
112668
112669/*
112670** This function checks if argument pFrom refers to a CTE declared by
112671** a WITH clause on the stack currently maintained by the parser. And,
112672** if currently processing a CTE expression, if it is a recursive
112673** reference to the current CTE.
112674**
112675** If pFrom falls into either of the two categories above, pFrom->pTab
112676** and other fields are populated accordingly. The caller should check
112677** (pFrom->pTab!=0) to determine whether or not a successful match
112678** was found.
112679**
112680** Whether or not a match is found, SQLITE_OK is returned if no error
112681** occurs. If an error does occur, an error message is stored in the
112682** parser and some error code other than SQLITE_OK returned.
112683*/
112684static int withExpand(
112685  Walker *pWalker,
112686  struct SrcList_item *pFrom
112687){
112688  Parse *pParse = pWalker->pParse;
112689  sqlite3 *db = pParse->db;
112690  struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
112691  With *pWith;                    /* WITH clause that pCte belongs to */
112692
112693  assert( pFrom->pTab==0 );
112694
112695  pCte = searchWith(pParse->pWith, pFrom, &pWith);
112696  if( pCte ){
112697    Table *pTab;
112698    ExprList *pEList;
112699    Select *pSel;
112700    Select *pLeft;                /* Left-most SELECT statement */
112701    int bMayRecursive;            /* True if compound joined by UNION [ALL] */
112702    With *pSavedWith;             /* Initial value of pParse->pWith */
112703
112704    /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
112705    ** recursive reference to CTE pCte. Leave an error in pParse and return
112706    ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
112707    ** In this case, proceed.  */
112708    if( pCte->zCteErr ){
112709      sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
112710      return SQLITE_ERROR;
112711    }
112712
112713    assert( pFrom->pTab==0 );
112714    pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
112715    if( pTab==0 ) return WRC_Abort;
112716    pTab->nRef = 1;
112717    pTab->zName = sqlite3DbStrDup(db, pCte->zName);
112718    pTab->iPKey = -1;
112719    pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
112720    pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
112721    pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
112722    if( db->mallocFailed ) return SQLITE_NOMEM;
112723    assert( pFrom->pSelect );
112724
112725    /* Check if this is a recursive CTE. */
112726    pSel = pFrom->pSelect;
112727    bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
112728    if( bMayRecursive ){
112729      int i;
112730      SrcList *pSrc = pFrom->pSelect->pSrc;
112731      for(i=0; i<pSrc->nSrc; i++){
112732        struct SrcList_item *pItem = &pSrc->a[i];
112733        if( pItem->zDatabase==0
112734         && pItem->zName!=0
112735         && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
112736          ){
112737          pItem->pTab = pTab;
112738          pItem->fg.isRecursive = 1;
112739          pTab->nRef++;
112740          pSel->selFlags |= SF_Recursive;
112741        }
112742      }
112743    }
112744
112745    /* Only one recursive reference is permitted. */
112746    if( pTab->nRef>2 ){
112747      sqlite3ErrorMsg(
112748          pParse, "multiple references to recursive table: %s", pCte->zName
112749      );
112750      return SQLITE_ERROR;
112751    }
112752    assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
112753
112754    pCte->zCteErr = "circular reference: %s";
112755    pSavedWith = pParse->pWith;
112756    pParse->pWith = pWith;
112757    sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
112758
112759    for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
112760    pEList = pLeft->pEList;
112761    if( pCte->pCols ){
112762      if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
112763        sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
112764            pCte->zName, pEList->nExpr, pCte->pCols->nExpr
112765        );
112766        pParse->pWith = pSavedWith;
112767        return SQLITE_ERROR;
112768      }
112769      pEList = pCte->pCols;
112770    }
112771
112772    sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
112773    if( bMayRecursive ){
112774      if( pSel->selFlags & SF_Recursive ){
112775        pCte->zCteErr = "multiple recursive references: %s";
112776      }else{
112777        pCte->zCteErr = "recursive reference in a subquery: %s";
112778      }
112779      sqlite3WalkSelect(pWalker, pSel);
112780    }
112781    pCte->zCteErr = 0;
112782    pParse->pWith = pSavedWith;
112783  }
112784
112785  return SQLITE_OK;
112786}
112787#endif
112788
112789#ifndef SQLITE_OMIT_CTE
112790/*
112791** If the SELECT passed as the second argument has an associated WITH
112792** clause, pop it from the stack stored as part of the Parse object.
112793**
112794** This function is used as the xSelectCallback2() callback by
112795** sqlite3SelectExpand() when walking a SELECT tree to resolve table
112796** names and other FROM clause elements.
112797*/
112798static void selectPopWith(Walker *pWalker, Select *p){
112799  Parse *pParse = pWalker->pParse;
112800  With *pWith = findRightmost(p)->pWith;
112801  if( pWith!=0 ){
112802    assert( pParse->pWith==pWith );
112803    pParse->pWith = pWith->pOuter;
112804  }
112805}
112806#else
112807#define selectPopWith 0
112808#endif
112809
112810/*
112811** This routine is a Walker callback for "expanding" a SELECT statement.
112812** "Expanding" means to do the following:
112813**
112814**    (1)  Make sure VDBE cursor numbers have been assigned to every
112815**         element of the FROM clause.
112816**
112817**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
112818**         defines FROM clause.  When views appear in the FROM clause,
112819**         fill pTabList->a[].pSelect with a copy of the SELECT statement
112820**         that implements the view.  A copy is made of the view's SELECT
112821**         statement so that we can freely modify or delete that statement
112822**         without worrying about messing up the persistent representation
112823**         of the view.
112824**
112825**    (3)  Add terms to the WHERE clause to accommodate the NATURAL keyword
112826**         on joins and the ON and USING clause of joins.
112827**
112828**    (4)  Scan the list of columns in the result set (pEList) looking
112829**         for instances of the "*" operator or the TABLE.* operator.
112830**         If found, expand each "*" to be every column in every table
112831**         and TABLE.* to be every column in TABLE.
112832**
112833*/
112834static int selectExpander(Walker *pWalker, Select *p){
112835  Parse *pParse = pWalker->pParse;
112836  int i, j, k;
112837  SrcList *pTabList;
112838  ExprList *pEList;
112839  struct SrcList_item *pFrom;
112840  sqlite3 *db = pParse->db;
112841  Expr *pE, *pRight, *pExpr;
112842  u16 selFlags = p->selFlags;
112843
112844  p->selFlags |= SF_Expanded;
112845  if( db->mallocFailed  ){
112846    return WRC_Abort;
112847  }
112848  if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
112849    return WRC_Prune;
112850  }
112851  pTabList = p->pSrc;
112852  pEList = p->pEList;
112853  if( pWalker->xSelectCallback2==selectPopWith ){
112854    sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
112855  }
112856
112857  /* Make sure cursor numbers have been assigned to all entries in
112858  ** the FROM clause of the SELECT statement.
112859  */
112860  sqlite3SrcListAssignCursors(pParse, pTabList);
112861
112862  /* Look up every table named in the FROM clause of the select.  If
112863  ** an entry of the FROM clause is a subquery instead of a table or view,
112864  ** then create a transient table structure to describe the subquery.
112865  */
112866  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
112867    Table *pTab;
112868    assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
112869    if( pFrom->fg.isRecursive ) continue;
112870    assert( pFrom->pTab==0 );
112871#ifndef SQLITE_OMIT_CTE
112872    if( withExpand(pWalker, pFrom) ) return WRC_Abort;
112873    if( pFrom->pTab ) {} else
112874#endif
112875    if( pFrom->zName==0 ){
112876#ifndef SQLITE_OMIT_SUBQUERY
112877      Select *pSel = pFrom->pSelect;
112878      /* A sub-query in the FROM clause of a SELECT */
112879      assert( pSel!=0 );
112880      assert( pFrom->pTab==0 );
112881      if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
112882      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
112883      if( pTab==0 ) return WRC_Abort;
112884      pTab->nRef = 1;
112885      pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
112886      while( pSel->pPrior ){ pSel = pSel->pPrior; }
112887      sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
112888      pTab->iPKey = -1;
112889      pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
112890      pTab->tabFlags |= TF_Ephemeral;
112891#endif
112892    }else{
112893      /* An ordinary table or view name in the FROM clause */
112894      assert( pFrom->pTab==0 );
112895      pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
112896      if( pTab==0 ) return WRC_Abort;
112897      if( pTab->nRef==0xffff ){
112898        sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
112899           pTab->zName);
112900        pFrom->pTab = 0;
112901        return WRC_Abort;
112902      }
112903      pTab->nRef++;
112904#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
112905      if( pTab->pSelect || IsVirtual(pTab) ){
112906        i16 nCol;
112907        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
112908        assert( pFrom->pSelect==0 );
112909        if( pFrom->fg.isTabFunc && !IsVirtual(pTab) ){
112910          sqlite3ErrorMsg(pParse, "'%s' is not a function", pTab->zName);
112911          return WRC_Abort;
112912        }
112913        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
112914        sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
112915        nCol = pTab->nCol;
112916        pTab->nCol = -1;
112917        sqlite3WalkSelect(pWalker, pFrom->pSelect);
112918        pTab->nCol = nCol;
112919      }
112920#endif
112921    }
112922
112923    /* Locate the index named by the INDEXED BY clause, if any. */
112924    if( sqlite3IndexedByLookup(pParse, pFrom) ){
112925      return WRC_Abort;
112926    }
112927  }
112928
112929  /* Process NATURAL keywords, and ON and USING clauses of joins.
112930  */
112931  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
112932    return WRC_Abort;
112933  }
112934
112935  /* For every "*" that occurs in the column list, insert the names of
112936  ** all columns in all tables.  And for every TABLE.* insert the names
112937  ** of all columns in TABLE.  The parser inserted a special expression
112938  ** with the TK_ALL operator for each "*" that it found in the column list.
112939  ** The following code just has to locate the TK_ALL expressions and expand
112940  ** each one to the list of all columns in all tables.
112941  **
112942  ** The first loop just checks to see if there are any "*" operators
112943  ** that need expanding.
112944  */
112945  for(k=0; k<pEList->nExpr; k++){
112946    pE = pEList->a[k].pExpr;
112947    if( pE->op==TK_ALL ) break;
112948    assert( pE->op!=TK_DOT || pE->pRight!=0 );
112949    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
112950    if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
112951  }
112952  if( k<pEList->nExpr ){
112953    /*
112954    ** If we get here it means the result set contains one or more "*"
112955    ** operators that need to be expanded.  Loop through each expression
112956    ** in the result set and expand them one by one.
112957    */
112958    struct ExprList_item *a = pEList->a;
112959    ExprList *pNew = 0;
112960    int flags = pParse->db->flags;
112961    int longNames = (flags & SQLITE_FullColNames)!=0
112962                      && (flags & SQLITE_ShortColNames)==0;
112963
112964    for(k=0; k<pEList->nExpr; k++){
112965      pE = a[k].pExpr;
112966      pRight = pE->pRight;
112967      assert( pE->op!=TK_DOT || pRight!=0 );
112968      if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
112969        /* This particular expression does not need to be expanded.
112970        */
112971        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
112972        if( pNew ){
112973          pNew->a[pNew->nExpr-1].zName = a[k].zName;
112974          pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
112975          a[k].zName = 0;
112976          a[k].zSpan = 0;
112977        }
112978        a[k].pExpr = 0;
112979      }else{
112980        /* This expression is a "*" or a "TABLE.*" and needs to be
112981        ** expanded. */
112982        int tableSeen = 0;      /* Set to 1 when TABLE matches */
112983        char *zTName = 0;       /* text of name of TABLE */
112984        if( pE->op==TK_DOT ){
112985          assert( pE->pLeft!=0 );
112986          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
112987          zTName = pE->pLeft->u.zToken;
112988        }
112989        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
112990          Table *pTab = pFrom->pTab;
112991          Select *pSub = pFrom->pSelect;
112992          char *zTabName = pFrom->zAlias;
112993          const char *zSchemaName = 0;
112994          int iDb;
112995          if( zTabName==0 ){
112996            zTabName = pTab->zName;
112997          }
112998          if( db->mallocFailed ) break;
112999          if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
113000            pSub = 0;
113001            if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
113002              continue;
113003            }
113004            iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
113005            zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
113006          }
113007          for(j=0; j<pTab->nCol; j++){
113008            char *zName = pTab->aCol[j].zName;
113009            char *zColname;  /* The computed column name */
113010            char *zToFree;   /* Malloced string that needs to be freed */
113011            Token sColname;  /* Computed column name as a token */
113012
113013            assert( zName );
113014            if( zTName && pSub
113015             && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
113016            ){
113017              continue;
113018            }
113019
113020            /* If a column is marked as 'hidden' (currently only possible
113021            ** for virtual tables), do not include it in the expanded
113022            ** result-set list.
113023            */
113024            if( IsHiddenColumn(&pTab->aCol[j]) ){
113025              assert(IsVirtual(pTab));
113026              continue;
113027            }
113028            tableSeen = 1;
113029
113030            if( i>0 && zTName==0 ){
113031              if( (pFrom->fg.jointype & JT_NATURAL)!=0
113032                && tableAndColumnIndex(pTabList, i, zName, 0, 0)
113033              ){
113034                /* In a NATURAL join, omit the join columns from the
113035                ** table to the right of the join */
113036                continue;
113037              }
113038              if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
113039                /* In a join with a USING clause, omit columns in the
113040                ** using clause from the table on the right. */
113041                continue;
113042              }
113043            }
113044            pRight = sqlite3Expr(db, TK_ID, zName);
113045            zColname = zName;
113046            zToFree = 0;
113047            if( longNames || pTabList->nSrc>1 ){
113048              Expr *pLeft;
113049              pLeft = sqlite3Expr(db, TK_ID, zTabName);
113050              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
113051              if( zSchemaName ){
113052                pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
113053                pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
113054              }
113055              if( longNames ){
113056                zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
113057                zToFree = zColname;
113058              }
113059            }else{
113060              pExpr = pRight;
113061            }
113062            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
113063            sColname.z = zColname;
113064            sColname.n = sqlite3Strlen30(zColname);
113065            sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
113066            if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
113067              struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
113068              if( pSub ){
113069                pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
113070                testcase( pX->zSpan==0 );
113071              }else{
113072                pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
113073                                           zSchemaName, zTabName, zColname);
113074                testcase( pX->zSpan==0 );
113075              }
113076              pX->bSpanIsTab = 1;
113077            }
113078            sqlite3DbFree(db, zToFree);
113079          }
113080        }
113081        if( !tableSeen ){
113082          if( zTName ){
113083            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
113084          }else{
113085            sqlite3ErrorMsg(pParse, "no tables specified");
113086          }
113087        }
113088      }
113089    }
113090    sqlite3ExprListDelete(db, pEList);
113091    p->pEList = pNew;
113092  }
113093#if SQLITE_MAX_COLUMN
113094  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
113095    sqlite3ErrorMsg(pParse, "too many columns in result set");
113096  }
113097#endif
113098  return WRC_Continue;
113099}
113100
113101/*
113102** No-op routine for the parse-tree walker.
113103**
113104** When this routine is the Walker.xExprCallback then expression trees
113105** are walked without any actions being taken at each node.  Presumably,
113106** when this routine is used for Walker.xExprCallback then
113107** Walker.xSelectCallback is set to do something useful for every
113108** subquery in the parser tree.
113109*/
113110static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
113111  UNUSED_PARAMETER2(NotUsed, NotUsed2);
113112  return WRC_Continue;
113113}
113114
113115/*
113116** This routine "expands" a SELECT statement and all of its subqueries.
113117** For additional information on what it means to "expand" a SELECT
113118** statement, see the comment on the selectExpand worker callback above.
113119**
113120** Expanding a SELECT statement is the first step in processing a
113121** SELECT statement.  The SELECT statement must be expanded before
113122** name resolution is performed.
113123**
113124** If anything goes wrong, an error message is written into pParse.
113125** The calling function can detect the problem by looking at pParse->nErr
113126** and/or pParse->db->mallocFailed.
113127*/
113128static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
113129  Walker w;
113130  memset(&w, 0, sizeof(w));
113131  w.xExprCallback = exprWalkNoop;
113132  w.pParse = pParse;
113133  if( pParse->hasCompound ){
113134    w.xSelectCallback = convertCompoundSelectToSubquery;
113135    sqlite3WalkSelect(&w, pSelect);
113136  }
113137  w.xSelectCallback = selectExpander;
113138  if( (pSelect->selFlags & SF_MultiValue)==0 ){
113139    w.xSelectCallback2 = selectPopWith;
113140  }
113141  sqlite3WalkSelect(&w, pSelect);
113142}
113143
113144
113145#ifndef SQLITE_OMIT_SUBQUERY
113146/*
113147** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
113148** interface.
113149**
113150** For each FROM-clause subquery, add Column.zType and Column.zColl
113151** information to the Table structure that represents the result set
113152** of that subquery.
113153**
113154** The Table structure that represents the result set was constructed
113155** by selectExpander() but the type and collation information was omitted
113156** at that point because identifiers had not yet been resolved.  This
113157** routine is called after identifier resolution.
113158*/
113159static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
113160  Parse *pParse;
113161  int i;
113162  SrcList *pTabList;
113163  struct SrcList_item *pFrom;
113164
113165  assert( p->selFlags & SF_Resolved );
113166  assert( (p->selFlags & SF_HasTypeInfo)==0 );
113167  p->selFlags |= SF_HasTypeInfo;
113168  pParse = pWalker->pParse;
113169  pTabList = p->pSrc;
113170  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
113171    Table *pTab = pFrom->pTab;
113172    assert( pTab!=0 );
113173    if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
113174      /* A sub-query in the FROM clause of a SELECT */
113175      Select *pSel = pFrom->pSelect;
113176      if( pSel ){
113177        while( pSel->pPrior ) pSel = pSel->pPrior;
113178        selectAddColumnTypeAndCollation(pParse, pTab, pSel);
113179      }
113180    }
113181  }
113182}
113183#endif
113184
113185
113186/*
113187** This routine adds datatype and collating sequence information to
113188** the Table structures of all FROM-clause subqueries in a
113189** SELECT statement.
113190**
113191** Use this routine after name resolution.
113192*/
113193static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
113194#ifndef SQLITE_OMIT_SUBQUERY
113195  Walker w;
113196  memset(&w, 0, sizeof(w));
113197  w.xSelectCallback2 = selectAddSubqueryTypeInfo;
113198  w.xExprCallback = exprWalkNoop;
113199  w.pParse = pParse;
113200  sqlite3WalkSelect(&w, pSelect);
113201#endif
113202}
113203
113204
113205/*
113206** This routine sets up a SELECT statement for processing.  The
113207** following is accomplished:
113208**
113209**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
113210**     *  Ephemeral Table objects are created for all FROM-clause subqueries.
113211**     *  ON and USING clauses are shifted into WHERE statements
113212**     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
113213**     *  Identifiers in expression are matched to tables.
113214**
113215** This routine acts recursively on all subqueries within the SELECT.
113216*/
113217SQLITE_PRIVATE void sqlite3SelectPrep(
113218  Parse *pParse,         /* The parser context */
113219  Select *p,             /* The SELECT statement being coded. */
113220  NameContext *pOuterNC  /* Name context for container */
113221){
113222  sqlite3 *db;
113223  if( NEVER(p==0) ) return;
113224  db = pParse->db;
113225  if( db->mallocFailed ) return;
113226  if( p->selFlags & SF_HasTypeInfo ) return;
113227  sqlite3SelectExpand(pParse, p);
113228  if( pParse->nErr || db->mallocFailed ) return;
113229  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
113230  if( pParse->nErr || db->mallocFailed ) return;
113231  sqlite3SelectAddTypeInfo(pParse, p);
113232}
113233
113234/*
113235** Reset the aggregate accumulator.
113236**
113237** The aggregate accumulator is a set of memory cells that hold
113238** intermediate results while calculating an aggregate.  This
113239** routine generates code that stores NULLs in all of those memory
113240** cells.
113241*/
113242static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
113243  Vdbe *v = pParse->pVdbe;
113244  int i;
113245  struct AggInfo_func *pFunc;
113246  int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
113247  if( nReg==0 ) return;
113248#ifdef SQLITE_DEBUG
113249  /* Verify that all AggInfo registers are within the range specified by
113250  ** AggInfo.mnReg..AggInfo.mxReg */
113251  assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
113252  for(i=0; i<pAggInfo->nColumn; i++){
113253    assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
113254         && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
113255  }
113256  for(i=0; i<pAggInfo->nFunc; i++){
113257    assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
113258         && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
113259  }
113260#endif
113261  sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
113262  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
113263    if( pFunc->iDistinct>=0 ){
113264      Expr *pE = pFunc->pExpr;
113265      assert( !ExprHasProperty(pE, EP_xIsSelect) );
113266      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
113267        sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
113268           "argument");
113269        pFunc->iDistinct = -1;
113270      }else{
113271        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
113272        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
113273                          (char*)pKeyInfo, P4_KEYINFO);
113274      }
113275    }
113276  }
113277}
113278
113279/*
113280** Invoke the OP_AggFinalize opcode for every aggregate function
113281** in the AggInfo structure.
113282*/
113283static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
113284  Vdbe *v = pParse->pVdbe;
113285  int i;
113286  struct AggInfo_func *pF;
113287  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
113288    ExprList *pList = pF->pExpr->x.pList;
113289    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
113290    sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
113291                      (void*)pF->pFunc, P4_FUNCDEF);
113292  }
113293}
113294
113295/*
113296** Update the accumulator memory cells for an aggregate based on
113297** the current cursor position.
113298*/
113299static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
113300  Vdbe *v = pParse->pVdbe;
113301  int i;
113302  int regHit = 0;
113303  int addrHitTest = 0;
113304  struct AggInfo_func *pF;
113305  struct AggInfo_col *pC;
113306
113307  pAggInfo->directMode = 1;
113308  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
113309    int nArg;
113310    int addrNext = 0;
113311    int regAgg;
113312    ExprList *pList = pF->pExpr->x.pList;
113313    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
113314    if( pList ){
113315      nArg = pList->nExpr;
113316      regAgg = sqlite3GetTempRange(pParse, nArg);
113317      sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
113318    }else{
113319      nArg = 0;
113320      regAgg = 0;
113321    }
113322    if( pF->iDistinct>=0 ){
113323      addrNext = sqlite3VdbeMakeLabel(v);
113324      testcase( nArg==0 );  /* Error condition */
113325      testcase( nArg>1 );   /* Also an error */
113326      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
113327    }
113328    if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
113329      CollSeq *pColl = 0;
113330      struct ExprList_item *pItem;
113331      int j;
113332      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
113333      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
113334        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
113335      }
113336      if( !pColl ){
113337        pColl = pParse->db->pDfltColl;
113338      }
113339      if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
113340      sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
113341    }
113342    sqlite3VdbeAddOp4(v, OP_AggStep0, 0, regAgg, pF->iMem,
113343                      (void*)pF->pFunc, P4_FUNCDEF);
113344    sqlite3VdbeChangeP5(v, (u8)nArg);
113345    sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
113346    sqlite3ReleaseTempRange(pParse, regAgg, nArg);
113347    if( addrNext ){
113348      sqlite3VdbeResolveLabel(v, addrNext);
113349      sqlite3ExprCacheClear(pParse);
113350    }
113351  }
113352
113353  /* Before populating the accumulator registers, clear the column cache.
113354  ** Otherwise, if any of the required column values are already present
113355  ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
113356  ** to pC->iMem. But by the time the value is used, the original register
113357  ** may have been used, invalidating the underlying buffer holding the
113358  ** text or blob value. See ticket [883034dcb5].
113359  **
113360  ** Another solution would be to change the OP_SCopy used to copy cached
113361  ** values to an OP_Copy.
113362  */
113363  if( regHit ){
113364    addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
113365  }
113366  sqlite3ExprCacheClear(pParse);
113367  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
113368    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
113369  }
113370  pAggInfo->directMode = 0;
113371  sqlite3ExprCacheClear(pParse);
113372  if( addrHitTest ){
113373    sqlite3VdbeJumpHere(v, addrHitTest);
113374  }
113375}
113376
113377/*
113378** Add a single OP_Explain instruction to the VDBE to explain a simple
113379** count(*) query ("SELECT count(*) FROM pTab").
113380*/
113381#ifndef SQLITE_OMIT_EXPLAIN
113382static void explainSimpleCount(
113383  Parse *pParse,                  /* Parse context */
113384  Table *pTab,                    /* Table being queried */
113385  Index *pIdx                     /* Index used to optimize scan, or NULL */
113386){
113387  if( pParse->explain==2 ){
113388    int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
113389    char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
113390        pTab->zName,
113391        bCover ? " USING COVERING INDEX " : "",
113392        bCover ? pIdx->zName : ""
113393    );
113394    sqlite3VdbeAddOp4(
113395        pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
113396    );
113397  }
113398}
113399#else
113400# define explainSimpleCount(a,b,c)
113401#endif
113402
113403/*
113404** Generate code for the SELECT statement given in the p argument.
113405**
113406** The results are returned according to the SelectDest structure.
113407** See comments in sqliteInt.h for further information.
113408**
113409** This routine returns the number of errors.  If any errors are
113410** encountered, then an appropriate error message is left in
113411** pParse->zErrMsg.
113412**
113413** This routine does NOT free the Select structure passed in.  The
113414** calling function needs to do that.
113415*/
113416SQLITE_PRIVATE int sqlite3Select(
113417  Parse *pParse,         /* The parser context */
113418  Select *p,             /* The SELECT statement being coded. */
113419  SelectDest *pDest      /* What to do with the query results */
113420){
113421  int i, j;              /* Loop counters */
113422  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
113423  Vdbe *v;               /* The virtual machine under construction */
113424  int isAgg;             /* True for select lists like "count(*)" */
113425  ExprList *pEList = 0;  /* List of columns to extract. */
113426  SrcList *pTabList;     /* List of tables to select from */
113427  Expr *pWhere;          /* The WHERE clause.  May be NULL */
113428  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
113429  Expr *pHaving;         /* The HAVING clause.  May be NULL */
113430  int rc = 1;            /* Value to return from this function */
113431  DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
113432  SortCtx sSort;         /* Info on how to code the ORDER BY clause */
113433  AggInfo sAggInfo;      /* Information used by aggregate queries */
113434  int iEnd;              /* Address of the end of the query */
113435  sqlite3 *db;           /* The database connection */
113436
113437#ifndef SQLITE_OMIT_EXPLAIN
113438  int iRestoreSelectId = pParse->iSelectId;
113439  pParse->iSelectId = pParse->iNextSelectId++;
113440#endif
113441
113442  db = pParse->db;
113443  if( p==0 || db->mallocFailed || pParse->nErr ){
113444    return 1;
113445  }
113446  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
113447  memset(&sAggInfo, 0, sizeof(sAggInfo));
113448#if SELECTTRACE_ENABLED
113449  pParse->nSelectIndent++;
113450  SELECTTRACE(1,pParse,p, ("begin processing:\n"));
113451  if( sqlite3SelectTrace & 0x100 ){
113452    sqlite3TreeViewSelect(0, p, 0);
113453  }
113454#endif
113455
113456  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
113457  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
113458  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
113459  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
113460  if( IgnorableOrderby(pDest) ){
113461    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
113462           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
113463           pDest->eDest==SRT_Queue  || pDest->eDest==SRT_DistFifo ||
113464           pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
113465    /* If ORDER BY makes no difference in the output then neither does
113466    ** DISTINCT so it can be removed too. */
113467    sqlite3ExprListDelete(db, p->pOrderBy);
113468    p->pOrderBy = 0;
113469    p->selFlags &= ~SF_Distinct;
113470  }
113471  sqlite3SelectPrep(pParse, p, 0);
113472  memset(&sSort, 0, sizeof(sSort));
113473  sSort.pOrderBy = p->pOrderBy;
113474  pTabList = p->pSrc;
113475  if( pParse->nErr || db->mallocFailed ){
113476    goto select_end;
113477  }
113478  assert( p->pEList!=0 );
113479  isAgg = (p->selFlags & SF_Aggregate)!=0;
113480#if SELECTTRACE_ENABLED
113481  if( sqlite3SelectTrace & 0x100 ){
113482    SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
113483    sqlite3TreeViewSelect(0, p, 0);
113484  }
113485#endif
113486
113487
113488  /* If writing to memory or generating a set
113489  ** only a single column may be output.
113490  */
113491#ifndef SQLITE_OMIT_SUBQUERY
113492  if( checkForMultiColumnSelectError(pParse, pDest, p->pEList->nExpr) ){
113493    goto select_end;
113494  }
113495#endif
113496
113497  /* Try to flatten subqueries in the FROM clause up into the main query
113498  */
113499#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
113500  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
113501    struct SrcList_item *pItem = &pTabList->a[i];
113502    Select *pSub = pItem->pSelect;
113503    int isAggSub;
113504    Table *pTab = pItem->pTab;
113505    if( pSub==0 ) continue;
113506
113507    /* Catch mismatch in the declared columns of a view and the number of
113508    ** columns in the SELECT on the RHS */
113509    if( pTab->nCol!=pSub->pEList->nExpr ){
113510      sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
113511                      pTab->nCol, pTab->zName, pSub->pEList->nExpr);
113512      goto select_end;
113513    }
113514
113515    isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
113516    if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
113517      /* This subquery can be absorbed into its parent. */
113518      if( isAggSub ){
113519        isAgg = 1;
113520        p->selFlags |= SF_Aggregate;
113521      }
113522      i = -1;
113523    }
113524    pTabList = p->pSrc;
113525    if( db->mallocFailed ) goto select_end;
113526    if( !IgnorableOrderby(pDest) ){
113527      sSort.pOrderBy = p->pOrderBy;
113528    }
113529  }
113530#endif
113531
113532  /* Get a pointer the VDBE under construction, allocating a new VDBE if one
113533  ** does not already exist */
113534  v = sqlite3GetVdbe(pParse);
113535  if( v==0 ) goto select_end;
113536
113537#ifndef SQLITE_OMIT_COMPOUND_SELECT
113538  /* Handle compound SELECT statements using the separate multiSelect()
113539  ** procedure.
113540  */
113541  if( p->pPrior ){
113542    rc = multiSelect(pParse, p, pDest);
113543    explainSetInteger(pParse->iSelectId, iRestoreSelectId);
113544#if SELECTTRACE_ENABLED
113545    SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
113546    pParse->nSelectIndent--;
113547#endif
113548    return rc;
113549  }
113550#endif
113551
113552  /* Generate code for all sub-queries in the FROM clause
113553  */
113554#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
113555  for(i=0; i<pTabList->nSrc; i++){
113556    struct SrcList_item *pItem = &pTabList->a[i];
113557    SelectDest dest;
113558    Select *pSub = pItem->pSelect;
113559    if( pSub==0 ) continue;
113560
113561    /* Sometimes the code for a subquery will be generated more than
113562    ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
113563    ** for example.  In that case, do not regenerate the code to manifest
113564    ** a view or the co-routine to implement a view.  The first instance
113565    ** is sufficient, though the subroutine to manifest the view does need
113566    ** to be invoked again. */
113567    if( pItem->addrFillSub ){
113568      if( pItem->fg.viaCoroutine==0 ){
113569        sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
113570      }
113571      continue;
113572    }
113573
113574    /* Increment Parse.nHeight by the height of the largest expression
113575    ** tree referred to by this, the parent select. The child select
113576    ** may contain expression trees of at most
113577    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
113578    ** more conservative than necessary, but much easier than enforcing
113579    ** an exact limit.
113580    */
113581    pParse->nHeight += sqlite3SelectExprHeight(p);
113582
113583    /* Make copies of constant WHERE-clause terms in the outer query down
113584    ** inside the subquery.  This can help the subquery to run more efficiently.
113585    */
113586    if( (pItem->fg.jointype & JT_OUTER)==0
113587     && pushDownWhereTerms(db, pSub, p->pWhere, pItem->iCursor)
113588    ){
113589#if SELECTTRACE_ENABLED
113590      if( sqlite3SelectTrace & 0x100 ){
113591        SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
113592        sqlite3TreeViewSelect(0, p, 0);
113593      }
113594#endif
113595    }
113596
113597    /* Generate code to implement the subquery
113598    */
113599    if( pTabList->nSrc==1
113600     && (p->selFlags & SF_All)==0
113601     && OptimizationEnabled(db, SQLITE_SubqCoroutine)
113602    ){
113603      /* Implement a co-routine that will return a single row of the result
113604      ** set on each invocation.
113605      */
113606      int addrTop = sqlite3VdbeCurrentAddr(v)+1;
113607      pItem->regReturn = ++pParse->nMem;
113608      sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
113609      VdbeComment((v, "%s", pItem->pTab->zName));
113610      pItem->addrFillSub = addrTop;
113611      sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
113612      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
113613      sqlite3Select(pParse, pSub, &dest);
113614      pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
113615      pItem->fg.viaCoroutine = 1;
113616      pItem->regResult = dest.iSdst;
113617      sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn);
113618      sqlite3VdbeJumpHere(v, addrTop-1);
113619      sqlite3ClearTempRegCache(pParse);
113620    }else{
113621      /* Generate a subroutine that will fill an ephemeral table with
113622      ** the content of this subquery.  pItem->addrFillSub will point
113623      ** to the address of the generated subroutine.  pItem->regReturn
113624      ** is a register allocated to hold the subroutine return address
113625      */
113626      int topAddr;
113627      int onceAddr = 0;
113628      int retAddr;
113629      assert( pItem->addrFillSub==0 );
113630      pItem->regReturn = ++pParse->nMem;
113631      topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
113632      pItem->addrFillSub = topAddr+1;
113633      if( pItem->fg.isCorrelated==0 ){
113634        /* If the subquery is not correlated and if we are not inside of
113635        ** a trigger, then we only need to compute the value of the subquery
113636        ** once. */
113637        onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
113638        VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
113639      }else{
113640        VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
113641      }
113642      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
113643      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
113644      sqlite3Select(pParse, pSub, &dest);
113645      pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
113646      if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
113647      retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
113648      VdbeComment((v, "end %s", pItem->pTab->zName));
113649      sqlite3VdbeChangeP1(v, topAddr, retAddr);
113650      sqlite3ClearTempRegCache(pParse);
113651    }
113652    if( db->mallocFailed ) goto select_end;
113653    pParse->nHeight -= sqlite3SelectExprHeight(p);
113654  }
113655#endif
113656
113657  /* Various elements of the SELECT copied into local variables for
113658  ** convenience */
113659  pEList = p->pEList;
113660  pWhere = p->pWhere;
113661  pGroupBy = p->pGroupBy;
113662  pHaving = p->pHaving;
113663  sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
113664
113665#if SELECTTRACE_ENABLED
113666  if( sqlite3SelectTrace & 0x400 ){
113667    SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
113668    sqlite3TreeViewSelect(0, p, 0);
113669  }
113670#endif
113671
113672  /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
113673  ** if the select-list is the same as the ORDER BY list, then this query
113674  ** can be rewritten as a GROUP BY. In other words, this:
113675  **
113676  **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
113677  **
113678  ** is transformed to:
113679  **
113680  **     SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
113681  **
113682  ** The second form is preferred as a single index (or temp-table) may be
113683  ** used for both the ORDER BY and DISTINCT processing. As originally
113684  ** written the query must use a temp-table for at least one of the ORDER
113685  ** BY and DISTINCT, and an index or separate temp-table for the other.
113686  */
113687  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
113688   && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
113689  ){
113690    p->selFlags &= ~SF_Distinct;
113691    pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
113692    /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
113693    ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
113694    ** original setting of the SF_Distinct flag, not the current setting */
113695    assert( sDistinct.isTnct );
113696  }
113697
113698  /* If there is an ORDER BY clause, then create an ephemeral index to
113699  ** do the sorting.  But this sorting ephemeral index might end up
113700  ** being unused if the data can be extracted in pre-sorted order.
113701  ** If that is the case, then the OP_OpenEphemeral instruction will be
113702  ** changed to an OP_Noop once we figure out that the sorting index is
113703  ** not needed.  The sSort.addrSortIndex variable is used to facilitate
113704  ** that change.
113705  */
113706  if( sSort.pOrderBy ){
113707    KeyInfo *pKeyInfo;
113708    pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
113709    sSort.iECursor = pParse->nTab++;
113710    sSort.addrSortIndex =
113711      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
113712          sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
113713          (char*)pKeyInfo, P4_KEYINFO
113714      );
113715  }else{
113716    sSort.addrSortIndex = -1;
113717  }
113718
113719  /* If the output is destined for a temporary table, open that table.
113720  */
113721  if( pDest->eDest==SRT_EphemTab ){
113722    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
113723  }
113724
113725  /* Set the limiter.
113726  */
113727  iEnd = sqlite3VdbeMakeLabel(v);
113728  p->nSelectRow = LARGEST_INT64;
113729  computeLimitRegisters(pParse, p, iEnd);
113730  if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
113731    sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
113732    sSort.sortFlags |= SORTFLAG_UseSorter;
113733  }
113734
113735  /* Open an ephemeral index to use for the distinct set.
113736  */
113737  if( p->selFlags & SF_Distinct ){
113738    sDistinct.tabTnct = pParse->nTab++;
113739    sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
113740                             sDistinct.tabTnct, 0, 0,
113741                             (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
113742                             P4_KEYINFO);
113743    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
113744    sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
113745  }else{
113746    sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
113747  }
113748
113749  if( !isAgg && pGroupBy==0 ){
113750    /* No aggregate functions and no GROUP BY clause */
113751    u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
113752
113753    /* Begin the database scan. */
113754    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
113755                               p->pEList, wctrlFlags, 0);
113756    if( pWInfo==0 ) goto select_end;
113757    if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
113758      p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
113759    }
113760    if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
113761      sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
113762    }
113763    if( sSort.pOrderBy ){
113764      sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
113765      if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
113766        sSort.pOrderBy = 0;
113767      }
113768    }
113769
113770    /* If sorting index that was created by a prior OP_OpenEphemeral
113771    ** instruction ended up not being needed, then change the OP_OpenEphemeral
113772    ** into an OP_Noop.
113773    */
113774    if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
113775      sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
113776    }
113777
113778    /* Use the standard inner loop. */
113779    selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
113780                    sqlite3WhereContinueLabel(pWInfo),
113781                    sqlite3WhereBreakLabel(pWInfo));
113782
113783    /* End the database scan loop.
113784    */
113785    sqlite3WhereEnd(pWInfo);
113786  }else{
113787    /* This case when there exist aggregate functions or a GROUP BY clause
113788    ** or both */
113789    NameContext sNC;    /* Name context for processing aggregate information */
113790    int iAMem;          /* First Mem address for storing current GROUP BY */
113791    int iBMem;          /* First Mem address for previous GROUP BY */
113792    int iUseFlag;       /* Mem address holding flag indicating that at least
113793                        ** one row of the input to the aggregator has been
113794                        ** processed */
113795    int iAbortFlag;     /* Mem address which causes query abort if positive */
113796    int groupBySort;    /* Rows come from source in GROUP BY order */
113797    int addrEnd;        /* End of processing for this SELECT */
113798    int sortPTab = 0;   /* Pseudotable used to decode sorting results */
113799    int sortOut = 0;    /* Output register from the sorter */
113800    int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
113801
113802    /* Remove any and all aliases between the result set and the
113803    ** GROUP BY clause.
113804    */
113805    if( pGroupBy ){
113806      int k;                        /* Loop counter */
113807      struct ExprList_item *pItem;  /* For looping over expression in a list */
113808
113809      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
113810        pItem->u.x.iAlias = 0;
113811      }
113812      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
113813        pItem->u.x.iAlias = 0;
113814      }
113815      if( p->nSelectRow>100 ) p->nSelectRow = 100;
113816    }else{
113817      p->nSelectRow = 1;
113818    }
113819
113820    /* If there is both a GROUP BY and an ORDER BY clause and they are
113821    ** identical, then it may be possible to disable the ORDER BY clause
113822    ** on the grounds that the GROUP BY will cause elements to come out
113823    ** in the correct order. It also may not - the GROUP BY might use a
113824    ** database index that causes rows to be grouped together as required
113825    ** but not actually sorted. Either way, record the fact that the
113826    ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
113827    ** variable.  */
113828    if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
113829      orderByGrp = 1;
113830    }
113831
113832    /* Create a label to jump to when we want to abort the query */
113833    addrEnd = sqlite3VdbeMakeLabel(v);
113834
113835    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
113836    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
113837    ** SELECT statement.
113838    */
113839    memset(&sNC, 0, sizeof(sNC));
113840    sNC.pParse = pParse;
113841    sNC.pSrcList = pTabList;
113842    sNC.pAggInfo = &sAggInfo;
113843    sAggInfo.mnReg = pParse->nMem+1;
113844    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
113845    sAggInfo.pGroupBy = pGroupBy;
113846    sqlite3ExprAnalyzeAggList(&sNC, pEList);
113847    sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
113848    if( pHaving ){
113849      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
113850    }
113851    sAggInfo.nAccumulator = sAggInfo.nColumn;
113852    for(i=0; i<sAggInfo.nFunc; i++){
113853      assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
113854      sNC.ncFlags |= NC_InAggFunc;
113855      sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
113856      sNC.ncFlags &= ~NC_InAggFunc;
113857    }
113858    sAggInfo.mxReg = pParse->nMem;
113859    if( db->mallocFailed ) goto select_end;
113860
113861    /* Processing for aggregates with GROUP BY is very different and
113862    ** much more complex than aggregates without a GROUP BY.
113863    */
113864    if( pGroupBy ){
113865      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
113866      int addr1;          /* A-vs-B comparision jump */
113867      int addrOutputRow;  /* Start of subroutine that outputs a result row */
113868      int regOutputRow;   /* Return address register for output subroutine */
113869      int addrSetAbort;   /* Set the abort flag and return */
113870      int addrTopOfLoop;  /* Top of the input loop */
113871      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
113872      int addrReset;      /* Subroutine for resetting the accumulator */
113873      int regReset;       /* Return address register for reset subroutine */
113874
113875      /* If there is a GROUP BY clause we might need a sorting index to
113876      ** implement it.  Allocate that sorting index now.  If it turns out
113877      ** that we do not need it after all, the OP_SorterOpen instruction
113878      ** will be converted into a Noop.
113879      */
113880      sAggInfo.sortingIdx = pParse->nTab++;
113881      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
113882      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
113883          sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
113884          0, (char*)pKeyInfo, P4_KEYINFO);
113885
113886      /* Initialize memory locations used by GROUP BY aggregate processing
113887      */
113888      iUseFlag = ++pParse->nMem;
113889      iAbortFlag = ++pParse->nMem;
113890      regOutputRow = ++pParse->nMem;
113891      addrOutputRow = sqlite3VdbeMakeLabel(v);
113892      regReset = ++pParse->nMem;
113893      addrReset = sqlite3VdbeMakeLabel(v);
113894      iAMem = pParse->nMem + 1;
113895      pParse->nMem += pGroupBy->nExpr;
113896      iBMem = pParse->nMem + 1;
113897      pParse->nMem += pGroupBy->nExpr;
113898      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
113899      VdbeComment((v, "clear abort flag"));
113900      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
113901      VdbeComment((v, "indicate accumulator empty"));
113902      sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
113903
113904      /* Begin a loop that will extract all source rows in GROUP BY order.
113905      ** This might involve two separate loops with an OP_Sort in between, or
113906      ** it might be a single loop that uses an index to extract information
113907      ** in the right order to begin with.
113908      */
113909      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
113910      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
113911          WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
113912      );
113913      if( pWInfo==0 ) goto select_end;
113914      if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
113915        /* The optimizer is able to deliver rows in group by order so
113916        ** we do not have to sort.  The OP_OpenEphemeral table will be
113917        ** cancelled later because we still need to use the pKeyInfo
113918        */
113919        groupBySort = 0;
113920      }else{
113921        /* Rows are coming out in undetermined order.  We have to push
113922        ** each row into a sorting index, terminate the first loop,
113923        ** then loop over the sorting index in order to get the output
113924        ** in sorted order
113925        */
113926        int regBase;
113927        int regRecord;
113928        int nCol;
113929        int nGroupBy;
113930
113931        explainTempTable(pParse,
113932            (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
113933                    "DISTINCT" : "GROUP BY");
113934
113935        groupBySort = 1;
113936        nGroupBy = pGroupBy->nExpr;
113937        nCol = nGroupBy;
113938        j = nGroupBy;
113939        for(i=0; i<sAggInfo.nColumn; i++){
113940          if( sAggInfo.aCol[i].iSorterColumn>=j ){
113941            nCol++;
113942            j++;
113943          }
113944        }
113945        regBase = sqlite3GetTempRange(pParse, nCol);
113946        sqlite3ExprCacheClear(pParse);
113947        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
113948        j = nGroupBy;
113949        for(i=0; i<sAggInfo.nColumn; i++){
113950          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
113951          if( pCol->iSorterColumn>=j ){
113952            int r1 = j + regBase;
113953            int r2;
113954
113955            r2 = sqlite3ExprCodeGetColumn(pParse,
113956                               pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
113957            if( r1!=r2 ){
113958              sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
113959            }
113960            j++;
113961          }
113962        }
113963        regRecord = sqlite3GetTempReg(pParse);
113964        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
113965        sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
113966        sqlite3ReleaseTempReg(pParse, regRecord);
113967        sqlite3ReleaseTempRange(pParse, regBase, nCol);
113968        sqlite3WhereEnd(pWInfo);
113969        sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
113970        sortOut = sqlite3GetTempReg(pParse);
113971        sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
113972        sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
113973        VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
113974        sAggInfo.useSortingIdx = 1;
113975        sqlite3ExprCacheClear(pParse);
113976
113977      }
113978
113979      /* If the index or temporary table used by the GROUP BY sort
113980      ** will naturally deliver rows in the order required by the ORDER BY
113981      ** clause, cancel the ephemeral table open coded earlier.
113982      **
113983      ** This is an optimization - the correct answer should result regardless.
113984      ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
113985      ** disable this optimization for testing purposes.  */
113986      if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
113987       && (groupBySort || sqlite3WhereIsSorted(pWInfo))
113988      ){
113989        sSort.pOrderBy = 0;
113990        sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
113991      }
113992
113993      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
113994      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
113995      ** Then compare the current GROUP BY terms against the GROUP BY terms
113996      ** from the previous row currently stored in a0, a1, a2...
113997      */
113998      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
113999      sqlite3ExprCacheClear(pParse);
114000      if( groupBySort ){
114001        sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
114002                          sortOut, sortPTab);
114003      }
114004      for(j=0; j<pGroupBy->nExpr; j++){
114005        if( groupBySort ){
114006          sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
114007        }else{
114008          sAggInfo.directMode = 1;
114009          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
114010        }
114011      }
114012      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
114013                          (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
114014      addr1 = sqlite3VdbeCurrentAddr(v);
114015      sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
114016
114017      /* Generate code that runs whenever the GROUP BY changes.
114018      ** Changes in the GROUP BY are detected by the previous code
114019      ** block.  If there were no changes, this block is skipped.
114020      **
114021      ** This code copies current group by terms in b0,b1,b2,...
114022      ** over to a0,a1,a2.  It then calls the output subroutine
114023      ** and resets the aggregate accumulator registers in preparation
114024      ** for the next GROUP BY batch.
114025      */
114026      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
114027      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
114028      VdbeComment((v, "output one row"));
114029      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
114030      VdbeComment((v, "check abort flag"));
114031      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
114032      VdbeComment((v, "reset accumulator"));
114033
114034      /* Update the aggregate accumulators based on the content of
114035      ** the current row
114036      */
114037      sqlite3VdbeJumpHere(v, addr1);
114038      updateAccumulator(pParse, &sAggInfo);
114039      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
114040      VdbeComment((v, "indicate data in accumulator"));
114041
114042      /* End of the loop
114043      */
114044      if( groupBySort ){
114045        sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
114046        VdbeCoverage(v);
114047      }else{
114048        sqlite3WhereEnd(pWInfo);
114049        sqlite3VdbeChangeToNoop(v, addrSortingIdx);
114050      }
114051
114052      /* Output the final row of result
114053      */
114054      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
114055      VdbeComment((v, "output final row"));
114056
114057      /* Jump over the subroutines
114058      */
114059      sqlite3VdbeGoto(v, addrEnd);
114060
114061      /* Generate a subroutine that outputs a single row of the result
114062      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
114063      ** is less than or equal to zero, the subroutine is a no-op.  If
114064      ** the processing calls for the query to abort, this subroutine
114065      ** increments the iAbortFlag memory location before returning in
114066      ** order to signal the caller to abort.
114067      */
114068      addrSetAbort = sqlite3VdbeCurrentAddr(v);
114069      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
114070      VdbeComment((v, "set abort flag"));
114071      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
114072      sqlite3VdbeResolveLabel(v, addrOutputRow);
114073      addrOutputRow = sqlite3VdbeCurrentAddr(v);
114074      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
114075      VdbeCoverage(v);
114076      VdbeComment((v, "Groupby result generator entry point"));
114077      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
114078      finalizeAggFunctions(pParse, &sAggInfo);
114079      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
114080      selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
114081                      &sDistinct, pDest,
114082                      addrOutputRow+1, addrSetAbort);
114083      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
114084      VdbeComment((v, "end groupby result generator"));
114085
114086      /* Generate a subroutine that will reset the group-by accumulator
114087      */
114088      sqlite3VdbeResolveLabel(v, addrReset);
114089      resetAccumulator(pParse, &sAggInfo);
114090      sqlite3VdbeAddOp1(v, OP_Return, regReset);
114091
114092    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
114093    else {
114094      ExprList *pDel = 0;
114095#ifndef SQLITE_OMIT_BTREECOUNT
114096      Table *pTab;
114097      if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
114098        /* If isSimpleCount() returns a pointer to a Table structure, then
114099        ** the SQL statement is of the form:
114100        **
114101        **   SELECT count(*) FROM <tbl>
114102        **
114103        ** where the Table structure returned represents table <tbl>.
114104        **
114105        ** This statement is so common that it is optimized specially. The
114106        ** OP_Count instruction is executed either on the intkey table that
114107        ** contains the data for table <tbl> or on one of its indexes. It
114108        ** is better to execute the op on an index, as indexes are almost
114109        ** always spread across less pages than their corresponding tables.
114110        */
114111        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
114112        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
114113        Index *pIdx;                         /* Iterator variable */
114114        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
114115        Index *pBest = 0;                    /* Best index found so far */
114116        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
114117
114118        sqlite3CodeVerifySchema(pParse, iDb);
114119        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
114120
114121        /* Search for the index that has the lowest scan cost.
114122        **
114123        ** (2011-04-15) Do not do a full scan of an unordered index.
114124        **
114125        ** (2013-10-03) Do not count the entries in a partial index.
114126        **
114127        ** In practice the KeyInfo structure will not be used. It is only
114128        ** passed to keep OP_OpenRead happy.
114129        */
114130        if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
114131        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
114132          if( pIdx->bUnordered==0
114133           && pIdx->szIdxRow<pTab->szTabRow
114134           && pIdx->pPartIdxWhere==0
114135           && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
114136          ){
114137            pBest = pIdx;
114138          }
114139        }
114140        if( pBest ){
114141          iRoot = pBest->tnum;
114142          pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
114143        }
114144
114145        /* Open a read-only cursor, execute the OP_Count, close the cursor. */
114146        sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
114147        if( pKeyInfo ){
114148          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
114149        }
114150        sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
114151        sqlite3VdbeAddOp1(v, OP_Close, iCsr);
114152        explainSimpleCount(pParse, pTab, pBest);
114153      }else
114154#endif /* SQLITE_OMIT_BTREECOUNT */
114155      {
114156        /* Check if the query is of one of the following forms:
114157        **
114158        **   SELECT min(x) FROM ...
114159        **   SELECT max(x) FROM ...
114160        **
114161        ** If it is, then ask the code in where.c to attempt to sort results
114162        ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
114163        ** If where.c is able to produce results sorted in this order, then
114164        ** add vdbe code to break out of the processing loop after the
114165        ** first iteration (since the first iteration of the loop is
114166        ** guaranteed to operate on the row with the minimum or maximum
114167        ** value of x, the only row required).
114168        **
114169        ** A special flag must be passed to sqlite3WhereBegin() to slightly
114170        ** modify behavior as follows:
114171        **
114172        **   + If the query is a "SELECT min(x)", then the loop coded by
114173        **     where.c should not iterate over any values with a NULL value
114174        **     for x.
114175        **
114176        **   + The optimizer code in where.c (the thing that decides which
114177        **     index or indices to use) should place a different priority on
114178        **     satisfying the 'ORDER BY' clause than it does in other cases.
114179        **     Refer to code and comments in where.c for details.
114180        */
114181        ExprList *pMinMax = 0;
114182        u8 flag = WHERE_ORDERBY_NORMAL;
114183
114184        assert( p->pGroupBy==0 );
114185        assert( flag==0 );
114186        if( p->pHaving==0 ){
114187          flag = minMaxQuery(&sAggInfo, &pMinMax);
114188        }
114189        assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
114190
114191        if( flag ){
114192          pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
114193          pDel = pMinMax;
114194          if( pMinMax && !db->mallocFailed ){
114195            pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
114196            pMinMax->a[0].pExpr->op = TK_COLUMN;
114197          }
114198        }
114199
114200        /* This case runs if the aggregate has no GROUP BY clause.  The
114201        ** processing is much simpler since there is only a single row
114202        ** of output.
114203        */
114204        resetAccumulator(pParse, &sAggInfo);
114205        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
114206        if( pWInfo==0 ){
114207          sqlite3ExprListDelete(db, pDel);
114208          goto select_end;
114209        }
114210        updateAccumulator(pParse, &sAggInfo);
114211        assert( pMinMax==0 || pMinMax->nExpr==1 );
114212        if( sqlite3WhereIsOrdered(pWInfo)>0 ){
114213          sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
114214          VdbeComment((v, "%s() by index",
114215                (flag==WHERE_ORDERBY_MIN?"min":"max")));
114216        }
114217        sqlite3WhereEnd(pWInfo);
114218        finalizeAggFunctions(pParse, &sAggInfo);
114219      }
114220
114221      sSort.pOrderBy = 0;
114222      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
114223      selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
114224                      pDest, addrEnd, addrEnd);
114225      sqlite3ExprListDelete(db, pDel);
114226    }
114227    sqlite3VdbeResolveLabel(v, addrEnd);
114228
114229  } /* endif aggregate query */
114230
114231  if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
114232    explainTempTable(pParse, "DISTINCT");
114233  }
114234
114235  /* If there is an ORDER BY clause, then we need to sort the results
114236  ** and send them to the callback one by one.
114237  */
114238  if( sSort.pOrderBy ){
114239    explainTempTable(pParse,
114240                     sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
114241    generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
114242  }
114243
114244  /* Jump here to skip this query
114245  */
114246  sqlite3VdbeResolveLabel(v, iEnd);
114247
114248  /* The SELECT has been coded. If there is an error in the Parse structure,
114249  ** set the return code to 1. Otherwise 0. */
114250  rc = (pParse->nErr>0);
114251
114252  /* Control jumps to here if an error is encountered above, or upon
114253  ** successful coding of the SELECT.
114254  */
114255select_end:
114256  explainSetInteger(pParse->iSelectId, iRestoreSelectId);
114257
114258  /* Identify column names if results of the SELECT are to be output.
114259  */
114260  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
114261    generateColumnNames(pParse, pTabList, pEList);
114262  }
114263
114264  sqlite3DbFree(db, sAggInfo.aCol);
114265  sqlite3DbFree(db, sAggInfo.aFunc);
114266#if SELECTTRACE_ENABLED
114267  SELECTTRACE(1,pParse,p,("end processing\n"));
114268  pParse->nSelectIndent--;
114269#endif
114270  return rc;
114271}
114272
114273/************** End of select.c **********************************************/
114274/************** Begin file table.c *******************************************/
114275/*
114276** 2001 September 15
114277**
114278** The author disclaims copyright to this source code.  In place of
114279** a legal notice, here is a blessing:
114280**
114281**    May you do good and not evil.
114282**    May you find forgiveness for yourself and forgive others.
114283**    May you share freely, never taking more than you give.
114284**
114285*************************************************************************
114286** This file contains the sqlite3_get_table() and sqlite3_free_table()
114287** interface routines.  These are just wrappers around the main
114288** interface routine of sqlite3_exec().
114289**
114290** These routines are in a separate files so that they will not be linked
114291** if they are not used.
114292*/
114293/* #include "sqliteInt.h" */
114294/* #include <stdlib.h> */
114295/* #include <string.h> */
114296
114297#ifndef SQLITE_OMIT_GET_TABLE
114298
114299/*
114300** This structure is used to pass data from sqlite3_get_table() through
114301** to the callback function is uses to build the result.
114302*/
114303typedef struct TabResult {
114304  char **azResult;   /* Accumulated output */
114305  char *zErrMsg;     /* Error message text, if an error occurs */
114306  u32 nAlloc;        /* Slots allocated for azResult[] */
114307  u32 nRow;          /* Number of rows in the result */
114308  u32 nColumn;       /* Number of columns in the result */
114309  u32 nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
114310  int rc;            /* Return code from sqlite3_exec() */
114311} TabResult;
114312
114313/*
114314** This routine is called once for each row in the result table.  Its job
114315** is to fill in the TabResult structure appropriately, allocating new
114316** memory as necessary.
114317*/
114318static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
114319  TabResult *p = (TabResult*)pArg;  /* Result accumulator */
114320  int need;                         /* Slots needed in p->azResult[] */
114321  int i;                            /* Loop counter */
114322  char *z;                          /* A single column of result */
114323
114324  /* Make sure there is enough space in p->azResult to hold everything
114325  ** we need to remember from this invocation of the callback.
114326  */
114327  if( p->nRow==0 && argv!=0 ){
114328    need = nCol*2;
114329  }else{
114330    need = nCol;
114331  }
114332  if( p->nData + need > p->nAlloc ){
114333    char **azNew;
114334    p->nAlloc = p->nAlloc*2 + need;
114335    azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
114336    if( azNew==0 ) goto malloc_failed;
114337    p->azResult = azNew;
114338  }
114339
114340  /* If this is the first row, then generate an extra row containing
114341  ** the names of all columns.
114342  */
114343  if( p->nRow==0 ){
114344    p->nColumn = nCol;
114345    for(i=0; i<nCol; i++){
114346      z = sqlite3_mprintf("%s", colv[i]);
114347      if( z==0 ) goto malloc_failed;
114348      p->azResult[p->nData++] = z;
114349    }
114350  }else if( (int)p->nColumn!=nCol ){
114351    sqlite3_free(p->zErrMsg);
114352    p->zErrMsg = sqlite3_mprintf(
114353       "sqlite3_get_table() called with two or more incompatible queries"
114354    );
114355    p->rc = SQLITE_ERROR;
114356    return 1;
114357  }
114358
114359  /* Copy over the row data
114360  */
114361  if( argv!=0 ){
114362    for(i=0; i<nCol; i++){
114363      if( argv[i]==0 ){
114364        z = 0;
114365      }else{
114366        int n = sqlite3Strlen30(argv[i])+1;
114367        z = sqlite3_malloc64( n );
114368        if( z==0 ) goto malloc_failed;
114369        memcpy(z, argv[i], n);
114370      }
114371      p->azResult[p->nData++] = z;
114372    }
114373    p->nRow++;
114374  }
114375  return 0;
114376
114377malloc_failed:
114378  p->rc = SQLITE_NOMEM;
114379  return 1;
114380}
114381
114382/*
114383** Query the database.  But instead of invoking a callback for each row,
114384** malloc() for space to hold the result and return the entire results
114385** at the conclusion of the call.
114386**
114387** The result that is written to ***pazResult is held in memory obtained
114388** from malloc().  But the caller cannot free this memory directly.
114389** Instead, the entire table should be passed to sqlite3_free_table() when
114390** the calling procedure is finished using it.
114391*/
114392SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
114393  sqlite3 *db,                /* The database on which the SQL executes */
114394  const char *zSql,           /* The SQL to be executed */
114395  char ***pazResult,          /* Write the result table here */
114396  int *pnRow,                 /* Write the number of rows in the result here */
114397  int *pnColumn,              /* Write the number of columns of result here */
114398  char **pzErrMsg             /* Write error messages here */
114399){
114400  int rc;
114401  TabResult res;
114402
114403#ifdef SQLITE_ENABLE_API_ARMOR
114404  if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
114405#endif
114406  *pazResult = 0;
114407  if( pnColumn ) *pnColumn = 0;
114408  if( pnRow ) *pnRow = 0;
114409  if( pzErrMsg ) *pzErrMsg = 0;
114410  res.zErrMsg = 0;
114411  res.nRow = 0;
114412  res.nColumn = 0;
114413  res.nData = 1;
114414  res.nAlloc = 20;
114415  res.rc = SQLITE_OK;
114416  res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
114417  if( res.azResult==0 ){
114418     db->errCode = SQLITE_NOMEM;
114419     return SQLITE_NOMEM;
114420  }
114421  res.azResult[0] = 0;
114422  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
114423  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
114424  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
114425  if( (rc&0xff)==SQLITE_ABORT ){
114426    sqlite3_free_table(&res.azResult[1]);
114427    if( res.zErrMsg ){
114428      if( pzErrMsg ){
114429        sqlite3_free(*pzErrMsg);
114430        *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
114431      }
114432      sqlite3_free(res.zErrMsg);
114433    }
114434    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
114435    return res.rc;
114436  }
114437  sqlite3_free(res.zErrMsg);
114438  if( rc!=SQLITE_OK ){
114439    sqlite3_free_table(&res.azResult[1]);
114440    return rc;
114441  }
114442  if( res.nAlloc>res.nData ){
114443    char **azNew;
114444    azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
114445    if( azNew==0 ){
114446      sqlite3_free_table(&res.azResult[1]);
114447      db->errCode = SQLITE_NOMEM;
114448      return SQLITE_NOMEM;
114449    }
114450    res.azResult = azNew;
114451  }
114452  *pazResult = &res.azResult[1];
114453  if( pnColumn ) *pnColumn = res.nColumn;
114454  if( pnRow ) *pnRow = res.nRow;
114455  return rc;
114456}
114457
114458/*
114459** This routine frees the space the sqlite3_get_table() malloced.
114460*/
114461SQLITE_API void SQLITE_STDCALL sqlite3_free_table(
114462  char **azResult            /* Result returned from sqlite3_get_table() */
114463){
114464  if( azResult ){
114465    int i, n;
114466    azResult--;
114467    assert( azResult!=0 );
114468    n = SQLITE_PTR_TO_INT(azResult[0]);
114469    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
114470    sqlite3_free(azResult);
114471  }
114472}
114473
114474#endif /* SQLITE_OMIT_GET_TABLE */
114475
114476/************** End of table.c ***********************************************/
114477/************** Begin file trigger.c *****************************************/
114478/*
114479**
114480** The author disclaims copyright to this source code.  In place of
114481** a legal notice, here is a blessing:
114482**
114483**    May you do good and not evil.
114484**    May you find forgiveness for yourself and forgive others.
114485**    May you share freely, never taking more than you give.
114486**
114487*************************************************************************
114488** This file contains the implementation for TRIGGERs
114489*/
114490/* #include "sqliteInt.h" */
114491
114492#ifndef SQLITE_OMIT_TRIGGER
114493/*
114494** Delete a linked list of TriggerStep structures.
114495*/
114496SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
114497  while( pTriggerStep ){
114498    TriggerStep * pTmp = pTriggerStep;
114499    pTriggerStep = pTriggerStep->pNext;
114500
114501    sqlite3ExprDelete(db, pTmp->pWhere);
114502    sqlite3ExprListDelete(db, pTmp->pExprList);
114503    sqlite3SelectDelete(db, pTmp->pSelect);
114504    sqlite3IdListDelete(db, pTmp->pIdList);
114505
114506    sqlite3DbFree(db, pTmp);
114507  }
114508}
114509
114510/*
114511** Given table pTab, return a list of all the triggers attached to
114512** the table. The list is connected by Trigger.pNext pointers.
114513**
114514** All of the triggers on pTab that are in the same database as pTab
114515** are already attached to pTab->pTrigger.  But there might be additional
114516** triggers on pTab in the TEMP schema.  This routine prepends all
114517** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
114518** and returns the combined list.
114519**
114520** To state it another way:  This routine returns a list of all triggers
114521** that fire off of pTab.  The list will include any TEMP triggers on
114522** pTab as well as the triggers lised in pTab->pTrigger.
114523*/
114524SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
114525  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
114526  Trigger *pList = 0;                  /* List of triggers to return */
114527
114528  if( pParse->disableTriggers ){
114529    return 0;
114530  }
114531
114532  if( pTmpSchema!=pTab->pSchema ){
114533    HashElem *p;
114534    assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
114535    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
114536      Trigger *pTrig = (Trigger *)sqliteHashData(p);
114537      if( pTrig->pTabSchema==pTab->pSchema
114538       && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
114539      ){
114540        pTrig->pNext = (pList ? pList : pTab->pTrigger);
114541        pList = pTrig;
114542      }
114543    }
114544  }
114545
114546  return (pList ? pList : pTab->pTrigger);
114547}
114548
114549/*
114550** This is called by the parser when it sees a CREATE TRIGGER statement
114551** up to the point of the BEGIN before the trigger actions.  A Trigger
114552** structure is generated based on the information available and stored
114553** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
114554** sqlite3FinishTrigger() function is called to complete the trigger
114555** construction process.
114556*/
114557SQLITE_PRIVATE void sqlite3BeginTrigger(
114558  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
114559  Token *pName1,      /* The name of the trigger */
114560  Token *pName2,      /* The name of the trigger */
114561  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
114562  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
114563  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
114564  SrcList *pTableName,/* The name of the table/view the trigger applies to */
114565  Expr *pWhen,        /* WHEN clause */
114566  int isTemp,         /* True if the TEMPORARY keyword is present */
114567  int noErr           /* Suppress errors if the trigger already exists */
114568){
114569  Trigger *pTrigger = 0;  /* The new trigger */
114570  Table *pTab;            /* Table that the trigger fires off of */
114571  char *zName = 0;        /* Name of the trigger */
114572  sqlite3 *db = pParse->db;  /* The database connection */
114573  int iDb;                /* The database to store the trigger in */
114574  Token *pName;           /* The unqualified db name */
114575  DbFixer sFix;           /* State vector for the DB fixer */
114576  int iTabDb;             /* Index of the database holding pTab */
114577
114578  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
114579  assert( pName2!=0 );
114580  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
114581  assert( op>0 && op<0xff );
114582  if( isTemp ){
114583    /* If TEMP was specified, then the trigger name may not be qualified. */
114584    if( pName2->n>0 ){
114585      sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
114586      goto trigger_cleanup;
114587    }
114588    iDb = 1;
114589    pName = pName1;
114590  }else{
114591    /* Figure out the db that the trigger will be created in */
114592    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
114593    if( iDb<0 ){
114594      goto trigger_cleanup;
114595    }
114596  }
114597  if( !pTableName || db->mallocFailed ){
114598    goto trigger_cleanup;
114599  }
114600
114601  /* A long-standing parser bug is that this syntax was allowed:
114602  **
114603  **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
114604  **                                                 ^^^^^^^^
114605  **
114606  ** To maintain backwards compatibility, ignore the database
114607  ** name on pTableName if we are reparsing out of SQLITE_MASTER.
114608  */
114609  if( db->init.busy && iDb!=1 ){
114610    sqlite3DbFree(db, pTableName->a[0].zDatabase);
114611    pTableName->a[0].zDatabase = 0;
114612  }
114613
114614  /* If the trigger name was unqualified, and the table is a temp table,
114615  ** then set iDb to 1 to create the trigger in the temporary database.
114616  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
114617  ** exist, the error is caught by the block below.
114618  */
114619  pTab = sqlite3SrcListLookup(pParse, pTableName);
114620  if( db->init.busy==0 && pName2->n==0 && pTab
114621        && pTab->pSchema==db->aDb[1].pSchema ){
114622    iDb = 1;
114623  }
114624
114625  /* Ensure the table name matches database name and that the table exists */
114626  if( db->mallocFailed ) goto trigger_cleanup;
114627  assert( pTableName->nSrc==1 );
114628  sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
114629  if( sqlite3FixSrcList(&sFix, pTableName) ){
114630    goto trigger_cleanup;
114631  }
114632  pTab = sqlite3SrcListLookup(pParse, pTableName);
114633  if( !pTab ){
114634    /* The table does not exist. */
114635    if( db->init.iDb==1 ){
114636      /* Ticket #3810.
114637      ** Normally, whenever a table is dropped, all associated triggers are
114638      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
114639      ** and the table is dropped by a different database connection, the
114640      ** trigger is not visible to the database connection that does the
114641      ** drop so the trigger cannot be dropped.  This results in an
114642      ** "orphaned trigger" - a trigger whose associated table is missing.
114643      */
114644      db->init.orphanTrigger = 1;
114645    }
114646    goto trigger_cleanup;
114647  }
114648  if( IsVirtual(pTab) ){
114649    sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
114650    goto trigger_cleanup;
114651  }
114652
114653  /* Check that the trigger name is not reserved and that no trigger of the
114654  ** specified name exists */
114655  zName = sqlite3NameFromToken(db, pName);
114656  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
114657    goto trigger_cleanup;
114658  }
114659  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
114660  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
114661    if( !noErr ){
114662      sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
114663    }else{
114664      assert( !db->init.busy );
114665      sqlite3CodeVerifySchema(pParse, iDb);
114666    }
114667    goto trigger_cleanup;
114668  }
114669
114670  /* Do not create a trigger on a system table */
114671  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
114672    sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
114673    goto trigger_cleanup;
114674  }
114675
114676  /* INSTEAD of triggers are only for views and views only support INSTEAD
114677  ** of triggers.
114678  */
114679  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
114680    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
114681        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
114682    goto trigger_cleanup;
114683  }
114684  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
114685    sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
114686        " trigger on table: %S", pTableName, 0);
114687    goto trigger_cleanup;
114688  }
114689  iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
114690
114691#ifndef SQLITE_OMIT_AUTHORIZATION
114692  {
114693    int code = SQLITE_CREATE_TRIGGER;
114694    const char *zDb = db->aDb[iTabDb].zName;
114695    const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
114696    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
114697    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
114698      goto trigger_cleanup;
114699    }
114700    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
114701      goto trigger_cleanup;
114702    }
114703  }
114704#endif
114705
114706  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
114707  ** cannot appear on views.  So we might as well translate every
114708  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
114709  ** elsewhere.
114710  */
114711  if (tr_tm == TK_INSTEAD){
114712    tr_tm = TK_BEFORE;
114713  }
114714
114715  /* Build the Trigger object */
114716  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
114717  if( pTrigger==0 ) goto trigger_cleanup;
114718  pTrigger->zName = zName;
114719  zName = 0;
114720  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
114721  pTrigger->pSchema = db->aDb[iDb].pSchema;
114722  pTrigger->pTabSchema = pTab->pSchema;
114723  pTrigger->op = (u8)op;
114724  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
114725  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
114726  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
114727  assert( pParse->pNewTrigger==0 );
114728  pParse->pNewTrigger = pTrigger;
114729
114730trigger_cleanup:
114731  sqlite3DbFree(db, zName);
114732  sqlite3SrcListDelete(db, pTableName);
114733  sqlite3IdListDelete(db, pColumns);
114734  sqlite3ExprDelete(db, pWhen);
114735  if( !pParse->pNewTrigger ){
114736    sqlite3DeleteTrigger(db, pTrigger);
114737  }else{
114738    assert( pParse->pNewTrigger==pTrigger );
114739  }
114740}
114741
114742/*
114743** This routine is called after all of the trigger actions have been parsed
114744** in order to complete the process of building the trigger.
114745*/
114746SQLITE_PRIVATE void sqlite3FinishTrigger(
114747  Parse *pParse,          /* Parser context */
114748  TriggerStep *pStepList, /* The triggered program */
114749  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
114750){
114751  Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
114752  char *zName;                            /* Name of trigger */
114753  sqlite3 *db = pParse->db;               /* The database */
114754  DbFixer sFix;                           /* Fixer object */
114755  int iDb;                                /* Database containing the trigger */
114756  Token nameToken;                        /* Trigger name for error reporting */
114757
114758  pParse->pNewTrigger = 0;
114759  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
114760  zName = pTrig->zName;
114761  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
114762  pTrig->step_list = pStepList;
114763  while( pStepList ){
114764    pStepList->pTrig = pTrig;
114765    pStepList = pStepList->pNext;
114766  }
114767  nameToken.z = pTrig->zName;
114768  nameToken.n = sqlite3Strlen30(nameToken.z);
114769  sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
114770  if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
114771   || sqlite3FixExpr(&sFix, pTrig->pWhen)
114772  ){
114773    goto triggerfinish_cleanup;
114774  }
114775
114776  /* if we are not initializing,
114777  ** build the sqlite_master entry
114778  */
114779  if( !db->init.busy ){
114780    Vdbe *v;
114781    char *z;
114782
114783    /* Make an entry in the sqlite_master table */
114784    v = sqlite3GetVdbe(pParse);
114785    if( v==0 ) goto triggerfinish_cleanup;
114786    sqlite3BeginWriteOperation(pParse, 0, iDb);
114787    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
114788    sqlite3NestedParse(pParse,
114789       "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
114790       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
114791       pTrig->table, z);
114792    sqlite3DbFree(db, z);
114793    sqlite3ChangeCookie(pParse, iDb);
114794    sqlite3VdbeAddParseSchemaOp(v, iDb,
114795        sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
114796  }
114797
114798  if( db->init.busy ){
114799    Trigger *pLink = pTrig;
114800    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
114801    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
114802    pTrig = sqlite3HashInsert(pHash, zName, pTrig);
114803    if( pTrig ){
114804      db->mallocFailed = 1;
114805    }else if( pLink->pSchema==pLink->pTabSchema ){
114806      Table *pTab;
114807      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
114808      assert( pTab!=0 );
114809      pLink->pNext = pTab->pTrigger;
114810      pTab->pTrigger = pLink;
114811    }
114812  }
114813
114814triggerfinish_cleanup:
114815  sqlite3DeleteTrigger(db, pTrig);
114816  assert( !pParse->pNewTrigger );
114817  sqlite3DeleteTriggerStep(db, pStepList);
114818}
114819
114820/*
114821** Turn a SELECT statement (that the pSelect parameter points to) into
114822** a trigger step.  Return a pointer to a TriggerStep structure.
114823**
114824** The parser calls this routine when it finds a SELECT statement in
114825** body of a TRIGGER.
114826*/
114827SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
114828  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
114829  if( pTriggerStep==0 ) {
114830    sqlite3SelectDelete(db, pSelect);
114831    return 0;
114832  }
114833  pTriggerStep->op = TK_SELECT;
114834  pTriggerStep->pSelect = pSelect;
114835  pTriggerStep->orconf = OE_Default;
114836  return pTriggerStep;
114837}
114838
114839/*
114840** Allocate space to hold a new trigger step.  The allocated space
114841** holds both the TriggerStep object and the TriggerStep.target.z string.
114842**
114843** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
114844*/
114845static TriggerStep *triggerStepAllocate(
114846  sqlite3 *db,                /* Database connection */
114847  u8 op,                      /* Trigger opcode */
114848  Token *pName                /* The target name */
114849){
114850  TriggerStep *pTriggerStep;
114851
114852  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
114853  if( pTriggerStep ){
114854    char *z = (char*)&pTriggerStep[1];
114855    memcpy(z, pName->z, pName->n);
114856    sqlite3Dequote(z);
114857    pTriggerStep->zTarget = z;
114858    pTriggerStep->op = op;
114859  }
114860  return pTriggerStep;
114861}
114862
114863/*
114864** Build a trigger step out of an INSERT statement.  Return a pointer
114865** to the new trigger step.
114866**
114867** The parser calls this routine when it sees an INSERT inside the
114868** body of a trigger.
114869*/
114870SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
114871  sqlite3 *db,        /* The database connection */
114872  Token *pTableName,  /* Name of the table into which we insert */
114873  IdList *pColumn,    /* List of columns in pTableName to insert into */
114874  Select *pSelect,    /* A SELECT statement that supplies values */
114875  u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
114876){
114877  TriggerStep *pTriggerStep;
114878
114879  assert(pSelect != 0 || db->mallocFailed);
114880
114881  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
114882  if( pTriggerStep ){
114883    pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
114884    pTriggerStep->pIdList = pColumn;
114885    pTriggerStep->orconf = orconf;
114886  }else{
114887    sqlite3IdListDelete(db, pColumn);
114888  }
114889  sqlite3SelectDelete(db, pSelect);
114890
114891  return pTriggerStep;
114892}
114893
114894/*
114895** Construct a trigger step that implements an UPDATE statement and return
114896** a pointer to that trigger step.  The parser calls this routine when it
114897** sees an UPDATE statement inside the body of a CREATE TRIGGER.
114898*/
114899SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
114900  sqlite3 *db,         /* The database connection */
114901  Token *pTableName,   /* Name of the table to be updated */
114902  ExprList *pEList,    /* The SET clause: list of column and new values */
114903  Expr *pWhere,        /* The WHERE clause */
114904  u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
114905){
114906  TriggerStep *pTriggerStep;
114907
114908  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
114909  if( pTriggerStep ){
114910    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
114911    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
114912    pTriggerStep->orconf = orconf;
114913  }
114914  sqlite3ExprListDelete(db, pEList);
114915  sqlite3ExprDelete(db, pWhere);
114916  return pTriggerStep;
114917}
114918
114919/*
114920** Construct a trigger step that implements a DELETE statement and return
114921** a pointer to that trigger step.  The parser calls this routine when it
114922** sees a DELETE statement inside the body of a CREATE TRIGGER.
114923*/
114924SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
114925  sqlite3 *db,            /* Database connection */
114926  Token *pTableName,      /* The table from which rows are deleted */
114927  Expr *pWhere            /* The WHERE clause */
114928){
114929  TriggerStep *pTriggerStep;
114930
114931  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
114932  if( pTriggerStep ){
114933    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
114934    pTriggerStep->orconf = OE_Default;
114935  }
114936  sqlite3ExprDelete(db, pWhere);
114937  return pTriggerStep;
114938}
114939
114940/*
114941** Recursively delete a Trigger structure
114942*/
114943SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
114944  if( pTrigger==0 ) return;
114945  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
114946  sqlite3DbFree(db, pTrigger->zName);
114947  sqlite3DbFree(db, pTrigger->table);
114948  sqlite3ExprDelete(db, pTrigger->pWhen);
114949  sqlite3IdListDelete(db, pTrigger->pColumns);
114950  sqlite3DbFree(db, pTrigger);
114951}
114952
114953/*
114954** This function is called to drop a trigger from the database schema.
114955**
114956** This may be called directly from the parser and therefore identifies
114957** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
114958** same job as this routine except it takes a pointer to the trigger
114959** instead of the trigger name.
114960**/
114961SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
114962  Trigger *pTrigger = 0;
114963  int i;
114964  const char *zDb;
114965  const char *zName;
114966  sqlite3 *db = pParse->db;
114967
114968  if( db->mallocFailed ) goto drop_trigger_cleanup;
114969  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
114970    goto drop_trigger_cleanup;
114971  }
114972
114973  assert( pName->nSrc==1 );
114974  zDb = pName->a[0].zDatabase;
114975  zName = pName->a[0].zName;
114976  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
114977  for(i=OMIT_TEMPDB; i<db->nDb; i++){
114978    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
114979    if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
114980    assert( sqlite3SchemaMutexHeld(db, j, 0) );
114981    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
114982    if( pTrigger ) break;
114983  }
114984  if( !pTrigger ){
114985    if( !noErr ){
114986      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
114987    }else{
114988      sqlite3CodeVerifyNamedSchema(pParse, zDb);
114989    }
114990    pParse->checkSchema = 1;
114991    goto drop_trigger_cleanup;
114992  }
114993  sqlite3DropTriggerPtr(pParse, pTrigger);
114994
114995drop_trigger_cleanup:
114996  sqlite3SrcListDelete(db, pName);
114997}
114998
114999/*
115000** Return a pointer to the Table structure for the table that a trigger
115001** is set on.
115002*/
115003static Table *tableOfTrigger(Trigger *pTrigger){
115004  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
115005}
115006
115007
115008/*
115009** Drop a trigger given a pointer to that trigger.
115010*/
115011SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
115012  Table   *pTable;
115013  Vdbe *v;
115014  sqlite3 *db = pParse->db;
115015  int iDb;
115016
115017  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
115018  assert( iDb>=0 && iDb<db->nDb );
115019  pTable = tableOfTrigger(pTrigger);
115020  assert( pTable );
115021  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
115022#ifndef SQLITE_OMIT_AUTHORIZATION
115023  {
115024    int code = SQLITE_DROP_TRIGGER;
115025    const char *zDb = db->aDb[iDb].zName;
115026    const char *zTab = SCHEMA_TABLE(iDb);
115027    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
115028    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
115029      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
115030      return;
115031    }
115032  }
115033#endif
115034
115035  /* Generate code to destroy the database record of the trigger.
115036  */
115037  assert( pTable!=0 );
115038  if( (v = sqlite3GetVdbe(pParse))!=0 ){
115039    int base;
115040    static const int iLn = VDBE_OFFSET_LINENO(2);
115041    static const VdbeOpList dropTrigger[] = {
115042      { OP_Rewind,     0, ADDR(9),  0},
115043      { OP_String8,    0, 1,        0}, /* 1 */
115044      { OP_Column,     0, 1,        2},
115045      { OP_Ne,         2, ADDR(8),  1},
115046      { OP_String8,    0, 1,        0}, /* 4: "trigger" */
115047      { OP_Column,     0, 0,        2},
115048      { OP_Ne,         2, ADDR(8),  1},
115049      { OP_Delete,     0, 0,        0},
115050      { OP_Next,       0, ADDR(1),  0}, /* 8 */
115051    };
115052
115053    sqlite3BeginWriteOperation(pParse, 0, iDb);
115054    sqlite3OpenMasterTable(pParse, iDb);
115055    base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger, iLn);
115056    sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
115057    sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
115058    sqlite3ChangeCookie(pParse, iDb);
115059    sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
115060    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
115061    if( pParse->nMem<3 ){
115062      pParse->nMem = 3;
115063    }
115064  }
115065}
115066
115067/*
115068** Remove a trigger from the hash tables of the sqlite* pointer.
115069*/
115070SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
115071  Trigger *pTrigger;
115072  Hash *pHash;
115073
115074  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
115075  pHash = &(db->aDb[iDb].pSchema->trigHash);
115076  pTrigger = sqlite3HashInsert(pHash, zName, 0);
115077  if( ALWAYS(pTrigger) ){
115078    if( pTrigger->pSchema==pTrigger->pTabSchema ){
115079      Table *pTab = tableOfTrigger(pTrigger);
115080      Trigger **pp;
115081      for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
115082      *pp = (*pp)->pNext;
115083    }
115084    sqlite3DeleteTrigger(db, pTrigger);
115085    db->flags |= SQLITE_InternChanges;
115086  }
115087}
115088
115089/*
115090** pEList is the SET clause of an UPDATE statement.  Each entry
115091** in pEList is of the format <id>=<expr>.  If any of the entries
115092** in pEList have an <id> which matches an identifier in pIdList,
115093** then return TRUE.  If pIdList==NULL, then it is considered a
115094** wildcard that matches anything.  Likewise if pEList==NULL then
115095** it matches anything so always return true.  Return false only
115096** if there is no match.
115097*/
115098static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
115099  int e;
115100  if( pIdList==0 || NEVER(pEList==0) ) return 1;
115101  for(e=0; e<pEList->nExpr; e++){
115102    if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
115103  }
115104  return 0;
115105}
115106
115107/*
115108** Return a list of all triggers on table pTab if there exists at least
115109** one trigger that must be fired when an operation of type 'op' is
115110** performed on the table, and, if that operation is an UPDATE, if at
115111** least one of the columns in pChanges is being modified.
115112*/
115113SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
115114  Parse *pParse,          /* Parse context */
115115  Table *pTab,            /* The table the contains the triggers */
115116  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
115117  ExprList *pChanges,     /* Columns that change in an UPDATE statement */
115118  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
115119){
115120  int mask = 0;
115121  Trigger *pList = 0;
115122  Trigger *p;
115123
115124  if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
115125    pList = sqlite3TriggerList(pParse, pTab);
115126  }
115127  assert( pList==0 || IsVirtual(pTab)==0 );
115128  for(p=pList; p; p=p->pNext){
115129    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
115130      mask |= p->tr_tm;
115131    }
115132  }
115133  if( pMask ){
115134    *pMask = mask;
115135  }
115136  return (mask ? pList : 0);
115137}
115138
115139/*
115140** Convert the pStep->zTarget string into a SrcList and return a pointer
115141** to that SrcList.
115142**
115143** This routine adds a specific database name, if needed, to the target when
115144** forming the SrcList.  This prevents a trigger in one database from
115145** referring to a target in another database.  An exception is when the
115146** trigger is in TEMP in which case it can refer to any other database it
115147** wants.
115148*/
115149static SrcList *targetSrcList(
115150  Parse *pParse,       /* The parsing context */
115151  TriggerStep *pStep   /* The trigger containing the target token */
115152){
115153  sqlite3 *db = pParse->db;
115154  int iDb;             /* Index of the database to use */
115155  SrcList *pSrc;       /* SrcList to be returned */
115156
115157  pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
115158  if( pSrc ){
115159    assert( pSrc->nSrc>0 );
115160    pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
115161    iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
115162    if( iDb==0 || iDb>=2 ){
115163      assert( iDb<db->nDb );
115164      pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
115165    }
115166  }
115167  return pSrc;
115168}
115169
115170/*
115171** Generate VDBE code for the statements inside the body of a single
115172** trigger.
115173*/
115174static int codeTriggerProgram(
115175  Parse *pParse,            /* The parser context */
115176  TriggerStep *pStepList,   /* List of statements inside the trigger body */
115177  int orconf                /* Conflict algorithm. (OE_Abort, etc) */
115178){
115179  TriggerStep *pStep;
115180  Vdbe *v = pParse->pVdbe;
115181  sqlite3 *db = pParse->db;
115182
115183  assert( pParse->pTriggerTab && pParse->pToplevel );
115184  assert( pStepList );
115185  assert( v!=0 );
115186  for(pStep=pStepList; pStep; pStep=pStep->pNext){
115187    /* Figure out the ON CONFLICT policy that will be used for this step
115188    ** of the trigger program. If the statement that caused this trigger
115189    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
115190    ** the ON CONFLICT policy that was specified as part of the trigger
115191    ** step statement. Example:
115192    **
115193    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
115194    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
115195    **   END;
115196    **
115197    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
115198    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
115199    */
115200    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
115201    assert( pParse->okConstFactor==0 );
115202
115203    switch( pStep->op ){
115204      case TK_UPDATE: {
115205        sqlite3Update(pParse,
115206          targetSrcList(pParse, pStep),
115207          sqlite3ExprListDup(db, pStep->pExprList, 0),
115208          sqlite3ExprDup(db, pStep->pWhere, 0),
115209          pParse->eOrconf
115210        );
115211        break;
115212      }
115213      case TK_INSERT: {
115214        sqlite3Insert(pParse,
115215          targetSrcList(pParse, pStep),
115216          sqlite3SelectDup(db, pStep->pSelect, 0),
115217          sqlite3IdListDup(db, pStep->pIdList),
115218          pParse->eOrconf
115219        );
115220        break;
115221      }
115222      case TK_DELETE: {
115223        sqlite3DeleteFrom(pParse,
115224          targetSrcList(pParse, pStep),
115225          sqlite3ExprDup(db, pStep->pWhere, 0)
115226        );
115227        break;
115228      }
115229      default: assert( pStep->op==TK_SELECT ); {
115230        SelectDest sDest;
115231        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
115232        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
115233        sqlite3Select(pParse, pSelect, &sDest);
115234        sqlite3SelectDelete(db, pSelect);
115235        break;
115236      }
115237    }
115238    if( pStep->op!=TK_SELECT ){
115239      sqlite3VdbeAddOp0(v, OP_ResetCount);
115240    }
115241  }
115242
115243  return 0;
115244}
115245
115246#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
115247/*
115248** This function is used to add VdbeComment() annotations to a VDBE
115249** program. It is not used in production code, only for debugging.
115250*/
115251static const char *onErrorText(int onError){
115252  switch( onError ){
115253    case OE_Abort:    return "abort";
115254    case OE_Rollback: return "rollback";
115255    case OE_Fail:     return "fail";
115256    case OE_Replace:  return "replace";
115257    case OE_Ignore:   return "ignore";
115258    case OE_Default:  return "default";
115259  }
115260  return "n/a";
115261}
115262#endif
115263
115264/*
115265** Parse context structure pFrom has just been used to create a sub-vdbe
115266** (trigger program). If an error has occurred, transfer error information
115267** from pFrom to pTo.
115268*/
115269static void transferParseError(Parse *pTo, Parse *pFrom){
115270  assert( pFrom->zErrMsg==0 || pFrom->nErr );
115271  assert( pTo->zErrMsg==0 || pTo->nErr );
115272  if( pTo->nErr==0 ){
115273    pTo->zErrMsg = pFrom->zErrMsg;
115274    pTo->nErr = pFrom->nErr;
115275    pTo->rc = pFrom->rc;
115276  }else{
115277    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
115278  }
115279}
115280
115281/*
115282** Create and populate a new TriggerPrg object with a sub-program
115283** implementing trigger pTrigger with ON CONFLICT policy orconf.
115284*/
115285static TriggerPrg *codeRowTrigger(
115286  Parse *pParse,       /* Current parse context */
115287  Trigger *pTrigger,   /* Trigger to code */
115288  Table *pTab,         /* The table pTrigger is attached to */
115289  int orconf           /* ON CONFLICT policy to code trigger program with */
115290){
115291  Parse *pTop = sqlite3ParseToplevel(pParse);
115292  sqlite3 *db = pParse->db;   /* Database handle */
115293  TriggerPrg *pPrg;           /* Value to return */
115294  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
115295  Vdbe *v;                    /* Temporary VM */
115296  NameContext sNC;            /* Name context for sub-vdbe */
115297  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
115298  Parse *pSubParse;           /* Parse context for sub-vdbe */
115299  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
115300
115301  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
115302  assert( pTop->pVdbe );
115303
115304  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
115305  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
115306  ** list of the top-level Parse object sooner rather than later.  */
115307  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
115308  if( !pPrg ) return 0;
115309  pPrg->pNext = pTop->pTriggerPrg;
115310  pTop->pTriggerPrg = pPrg;
115311  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
115312  if( !pProgram ) return 0;
115313  sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
115314  pPrg->pTrigger = pTrigger;
115315  pPrg->orconf = orconf;
115316  pPrg->aColmask[0] = 0xffffffff;
115317  pPrg->aColmask[1] = 0xffffffff;
115318
115319  /* Allocate and populate a new Parse context to use for coding the
115320  ** trigger sub-program.  */
115321  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
115322  if( !pSubParse ) return 0;
115323  memset(&sNC, 0, sizeof(sNC));
115324  sNC.pParse = pSubParse;
115325  pSubParse->db = db;
115326  pSubParse->pTriggerTab = pTab;
115327  pSubParse->pToplevel = pTop;
115328  pSubParse->zAuthContext = pTrigger->zName;
115329  pSubParse->eTriggerOp = pTrigger->op;
115330  pSubParse->nQueryLoop = pParse->nQueryLoop;
115331
115332  v = sqlite3GetVdbe(pSubParse);
115333  if( v ){
115334    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
115335      pTrigger->zName, onErrorText(orconf),
115336      (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
115337        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
115338        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
115339        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
115340      pTab->zName
115341    ));
115342#ifndef SQLITE_OMIT_TRACE
115343    sqlite3VdbeChangeP4(v, -1,
115344      sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
115345    );
115346#endif
115347
115348    /* If one was specified, code the WHEN clause. If it evaluates to false
115349    ** (or NULL) the sub-vdbe is immediately halted by jumping to the
115350    ** OP_Halt inserted at the end of the program.  */
115351    if( pTrigger->pWhen ){
115352      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
115353      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
115354       && db->mallocFailed==0
115355      ){
115356        iEndTrigger = sqlite3VdbeMakeLabel(v);
115357        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
115358      }
115359      sqlite3ExprDelete(db, pWhen);
115360    }
115361
115362    /* Code the trigger program into the sub-vdbe. */
115363    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
115364
115365    /* Insert an OP_Halt at the end of the sub-program. */
115366    if( iEndTrigger ){
115367      sqlite3VdbeResolveLabel(v, iEndTrigger);
115368    }
115369    sqlite3VdbeAddOp0(v, OP_Halt);
115370    VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
115371
115372    transferParseError(pParse, pSubParse);
115373    if( db->mallocFailed==0 ){
115374      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
115375    }
115376    pProgram->nMem = pSubParse->nMem;
115377    pProgram->nCsr = pSubParse->nTab;
115378    pProgram->nOnce = pSubParse->nOnce;
115379    pProgram->token = (void *)pTrigger;
115380    pPrg->aColmask[0] = pSubParse->oldmask;
115381    pPrg->aColmask[1] = pSubParse->newmask;
115382    sqlite3VdbeDelete(v);
115383  }
115384
115385  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
115386  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
115387  sqlite3ParserReset(pSubParse);
115388  sqlite3StackFree(db, pSubParse);
115389
115390  return pPrg;
115391}
115392
115393/*
115394** Return a pointer to a TriggerPrg object containing the sub-program for
115395** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
115396** TriggerPrg object exists, a new object is allocated and populated before
115397** being returned.
115398*/
115399static TriggerPrg *getRowTrigger(
115400  Parse *pParse,       /* Current parse context */
115401  Trigger *pTrigger,   /* Trigger to code */
115402  Table *pTab,         /* The table trigger pTrigger is attached to */
115403  int orconf           /* ON CONFLICT algorithm. */
115404){
115405  Parse *pRoot = sqlite3ParseToplevel(pParse);
115406  TriggerPrg *pPrg;
115407
115408  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
115409
115410  /* It may be that this trigger has already been coded (or is in the
115411  ** process of being coded). If this is the case, then an entry with
115412  ** a matching TriggerPrg.pTrigger field will be present somewhere
115413  ** in the Parse.pTriggerPrg list. Search for such an entry.  */
115414  for(pPrg=pRoot->pTriggerPrg;
115415      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
115416      pPrg=pPrg->pNext
115417  );
115418
115419  /* If an existing TriggerPrg could not be located, create a new one. */
115420  if( !pPrg ){
115421    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
115422  }
115423
115424  return pPrg;
115425}
115426
115427/*
115428** Generate code for the trigger program associated with trigger p on
115429** table pTab. The reg, orconf and ignoreJump parameters passed to this
115430** function are the same as those described in the header function for
115431** sqlite3CodeRowTrigger()
115432*/
115433SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
115434  Parse *pParse,       /* Parse context */
115435  Trigger *p,          /* Trigger to code */
115436  Table *pTab,         /* The table to code triggers from */
115437  int reg,             /* Reg array containing OLD.* and NEW.* values */
115438  int orconf,          /* ON CONFLICT policy */
115439  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
115440){
115441  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
115442  TriggerPrg *pPrg;
115443  pPrg = getRowTrigger(pParse, p, pTab, orconf);
115444  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
115445
115446  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
115447  ** is a pointer to the sub-vdbe containing the trigger program.  */
115448  if( pPrg ){
115449    int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
115450
115451    sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
115452    sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
115453    VdbeComment(
115454        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
115455
115456    /* Set the P5 operand of the OP_Program instruction to non-zero if
115457    ** recursive invocation of this trigger program is disallowed. Recursive
115458    ** invocation is disallowed if (a) the sub-program is really a trigger,
115459    ** not a foreign key action, and (b) the flag to enable recursive triggers
115460    ** is clear.  */
115461    sqlite3VdbeChangeP5(v, (u8)bRecursive);
115462  }
115463}
115464
115465/*
115466** This is called to code the required FOR EACH ROW triggers for an operation
115467** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
115468** is given by the op parameter. The tr_tm parameter determines whether the
115469** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
115470** parameter pChanges is passed the list of columns being modified.
115471**
115472** If there are no triggers that fire at the specified time for the specified
115473** operation on pTab, this function is a no-op.
115474**
115475** The reg argument is the address of the first in an array of registers
115476** that contain the values substituted for the new.* and old.* references
115477** in the trigger program. If N is the number of columns in table pTab
115478** (a copy of pTab->nCol), then registers are populated as follows:
115479**
115480**   Register       Contains
115481**   ------------------------------------------------------
115482**   reg+0          OLD.rowid
115483**   reg+1          OLD.* value of left-most column of pTab
115484**   ...            ...
115485**   reg+N          OLD.* value of right-most column of pTab
115486**   reg+N+1        NEW.rowid
115487**   reg+N+2        OLD.* value of left-most column of pTab
115488**   ...            ...
115489**   reg+N+N+1      NEW.* value of right-most column of pTab
115490**
115491** For ON DELETE triggers, the registers containing the NEW.* values will
115492** never be accessed by the trigger program, so they are not allocated or
115493** populated by the caller (there is no data to populate them with anyway).
115494** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
115495** are never accessed, and so are not allocated by the caller. So, for an
115496** ON INSERT trigger, the value passed to this function as parameter reg
115497** is not a readable register, although registers (reg+N) through
115498** (reg+N+N+1) are.
115499**
115500** Parameter orconf is the default conflict resolution algorithm for the
115501** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
115502** is the instruction that control should jump to if a trigger program
115503** raises an IGNORE exception.
115504*/
115505SQLITE_PRIVATE void sqlite3CodeRowTrigger(
115506  Parse *pParse,       /* Parse context */
115507  Trigger *pTrigger,   /* List of triggers on table pTab */
115508  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
115509  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
115510  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
115511  Table *pTab,         /* The table to code triggers from */
115512  int reg,             /* The first in an array of registers (see above) */
115513  int orconf,          /* ON CONFLICT policy */
115514  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
115515){
115516  Trigger *p;          /* Used to iterate through pTrigger list */
115517
115518  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
115519  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
115520  assert( (op==TK_UPDATE)==(pChanges!=0) );
115521
115522  for(p=pTrigger; p; p=p->pNext){
115523
115524    /* Sanity checking:  The schema for the trigger and for the table are
115525    ** always defined.  The trigger must be in the same schema as the table
115526    ** or else it must be a TEMP trigger. */
115527    assert( p->pSchema!=0 );
115528    assert( p->pTabSchema!=0 );
115529    assert( p->pSchema==p->pTabSchema
115530         || p->pSchema==pParse->db->aDb[1].pSchema );
115531
115532    /* Determine whether we should code this trigger */
115533    if( p->op==op
115534     && p->tr_tm==tr_tm
115535     && checkColumnOverlap(p->pColumns, pChanges)
115536    ){
115537      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
115538    }
115539  }
115540}
115541
115542/*
115543** Triggers may access values stored in the old.* or new.* pseudo-table.
115544** This function returns a 32-bit bitmask indicating which columns of the
115545** old.* or new.* tables actually are used by triggers. This information
115546** may be used by the caller, for example, to avoid having to load the entire
115547** old.* record into memory when executing an UPDATE or DELETE command.
115548**
115549** Bit 0 of the returned mask is set if the left-most column of the
115550** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
115551** the second leftmost column value is required, and so on. If there
115552** are more than 32 columns in the table, and at least one of the columns
115553** with an index greater than 32 may be accessed, 0xffffffff is returned.
115554**
115555** It is not possible to determine if the old.rowid or new.rowid column is
115556** accessed by triggers. The caller must always assume that it is.
115557**
115558** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
115559** applies to the old.* table. If 1, the new.* table.
115560**
115561** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
115562** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
115563** included in the returned mask if the TRIGGER_BEFORE bit is set in the
115564** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
115565** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
115566*/
115567SQLITE_PRIVATE u32 sqlite3TriggerColmask(
115568  Parse *pParse,       /* Parse context */
115569  Trigger *pTrigger,   /* List of triggers on table pTab */
115570  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
115571  int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
115572  int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
115573  Table *pTab,         /* The table to code triggers from */
115574  int orconf           /* Default ON CONFLICT policy for trigger steps */
115575){
115576  const int op = pChanges ? TK_UPDATE : TK_DELETE;
115577  u32 mask = 0;
115578  Trigger *p;
115579
115580  assert( isNew==1 || isNew==0 );
115581  for(p=pTrigger; p; p=p->pNext){
115582    if( p->op==op && (tr_tm&p->tr_tm)
115583     && checkColumnOverlap(p->pColumns,pChanges)
115584    ){
115585      TriggerPrg *pPrg;
115586      pPrg = getRowTrigger(pParse, p, pTab, orconf);
115587      if( pPrg ){
115588        mask |= pPrg->aColmask[isNew];
115589      }
115590    }
115591  }
115592
115593  return mask;
115594}
115595
115596#endif /* !defined(SQLITE_OMIT_TRIGGER) */
115597
115598/************** End of trigger.c *********************************************/
115599/************** Begin file update.c ******************************************/
115600/*
115601** 2001 September 15
115602**
115603** The author disclaims copyright to this source code.  In place of
115604** a legal notice, here is a blessing:
115605**
115606**    May you do good and not evil.
115607**    May you find forgiveness for yourself and forgive others.
115608**    May you share freely, never taking more than you give.
115609**
115610*************************************************************************
115611** This file contains C code routines that are called by the parser
115612** to handle UPDATE statements.
115613*/
115614/* #include "sqliteInt.h" */
115615
115616#ifndef SQLITE_OMIT_VIRTUALTABLE
115617/* Forward declaration */
115618static void updateVirtualTable(
115619  Parse *pParse,       /* The parsing context */
115620  SrcList *pSrc,       /* The virtual table to be modified */
115621  Table *pTab,         /* The virtual table */
115622  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
115623  Expr *pRowidExpr,    /* Expression used to recompute the rowid */
115624  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
115625  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
115626  int onError          /* ON CONFLICT strategy */
115627);
115628#endif /* SQLITE_OMIT_VIRTUALTABLE */
115629
115630/*
115631** The most recently coded instruction was an OP_Column to retrieve the
115632** i-th column of table pTab. This routine sets the P4 parameter of the
115633** OP_Column to the default value, if any.
115634**
115635** The default value of a column is specified by a DEFAULT clause in the
115636** column definition. This was either supplied by the user when the table
115637** was created, or added later to the table definition by an ALTER TABLE
115638** command. If the latter, then the row-records in the table btree on disk
115639** may not contain a value for the column and the default value, taken
115640** from the P4 parameter of the OP_Column instruction, is returned instead.
115641** If the former, then all row-records are guaranteed to include a value
115642** for the column and the P4 value is not required.
115643**
115644** Column definitions created by an ALTER TABLE command may only have
115645** literal default values specified: a number, null or a string. (If a more
115646** complicated default expression value was provided, it is evaluated
115647** when the ALTER TABLE is executed and one of the literal values written
115648** into the sqlite_master table.)
115649**
115650** Therefore, the P4 parameter is only required if the default value for
115651** the column is a literal number, string or null. The sqlite3ValueFromExpr()
115652** function is capable of transforming these types of expressions into
115653** sqlite3_value objects.
115654**
115655** If parameter iReg is not negative, code an OP_RealAffinity instruction
115656** on register iReg. This is used when an equivalent integer value is
115657** stored in place of an 8-byte floating point value in order to save
115658** space.
115659*/
115660SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
115661  assert( pTab!=0 );
115662  if( !pTab->pSelect ){
115663    sqlite3_value *pValue = 0;
115664    u8 enc = ENC(sqlite3VdbeDb(v));
115665    Column *pCol = &pTab->aCol[i];
115666    VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
115667    assert( i<pTab->nCol );
115668    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
115669                         pCol->affinity, &pValue);
115670    if( pValue ){
115671      sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
115672    }
115673#ifndef SQLITE_OMIT_FLOATING_POINT
115674    if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
115675      sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
115676    }
115677#endif
115678  }
115679}
115680
115681/*
115682** Process an UPDATE statement.
115683**
115684**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
115685**          \_______/ \________/     \______/       \________________/
115686*            onError   pTabList      pChanges             pWhere
115687*/
115688SQLITE_PRIVATE void sqlite3Update(
115689  Parse *pParse,         /* The parser context */
115690  SrcList *pTabList,     /* The table in which we should change things */
115691  ExprList *pChanges,    /* Things to be changed */
115692  Expr *pWhere,          /* The WHERE clause.  May be null */
115693  int onError            /* How to handle constraint errors */
115694){
115695  int i, j;              /* Loop counters */
115696  Table *pTab;           /* The table to be updated */
115697  int addrTop = 0;       /* VDBE instruction address of the start of the loop */
115698  WhereInfo *pWInfo;     /* Information about the WHERE clause */
115699  Vdbe *v;               /* The virtual database engine */
115700  Index *pIdx;           /* For looping over indices */
115701  Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
115702  int nIdx;              /* Number of indices that need updating */
115703  int iBaseCur;          /* Base cursor number */
115704  int iDataCur;          /* Cursor for the canonical data btree */
115705  int iIdxCur;           /* Cursor for the first index */
115706  sqlite3 *db;           /* The database structure */
115707  int *aRegIdx = 0;      /* One register assigned to each index to be updated */
115708  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
115709                         ** an expression for the i-th column of the table.
115710                         ** aXRef[i]==-1 if the i-th column is not changed. */
115711  u8 *aToOpen;           /* 1 for tables and indices to be opened */
115712  u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */
115713  u8 chngRowid;          /* Rowid changed in a normal table */
115714  u8 chngKey;            /* Either chngPk or chngRowid */
115715  Expr *pRowidExpr = 0;  /* Expression defining the new record number */
115716  AuthContext sContext;  /* The authorization context */
115717  NameContext sNC;       /* The name-context to resolve expressions in */
115718  int iDb;               /* Database containing the table being updated */
115719  int okOnePass;         /* True for one-pass algorithm without the FIFO */
115720  int hasFK;             /* True if foreign key processing is required */
115721  int labelBreak;        /* Jump here to break out of UPDATE loop */
115722  int labelContinue;     /* Jump here to continue next step of UPDATE loop */
115723
115724#ifndef SQLITE_OMIT_TRIGGER
115725  int isView;            /* True when updating a view (INSTEAD OF trigger) */
115726  Trigger *pTrigger;     /* List of triggers on pTab, if required */
115727  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
115728#endif
115729  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
115730  int iEph = 0;          /* Ephemeral table holding all primary key values */
115731  int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */
115732  int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
115733
115734  /* Register Allocations */
115735  int regRowCount = 0;   /* A count of rows changed */
115736  int regOldRowid = 0;   /* The old rowid */
115737  int regNewRowid = 0;   /* The new rowid */
115738  int regNew = 0;        /* Content of the NEW.* table in triggers */
115739  int regOld = 0;        /* Content of OLD.* table in triggers */
115740  int regRowSet = 0;     /* Rowset of rows to be updated */
115741  int regKey = 0;        /* composite PRIMARY KEY value */
115742
115743  memset(&sContext, 0, sizeof(sContext));
115744  db = pParse->db;
115745  if( pParse->nErr || db->mallocFailed ){
115746    goto update_cleanup;
115747  }
115748  assert( pTabList->nSrc==1 );
115749
115750  /* Locate the table which we want to update.
115751  */
115752  pTab = sqlite3SrcListLookup(pParse, pTabList);
115753  if( pTab==0 ) goto update_cleanup;
115754  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
115755
115756  /* Figure out if we have any triggers and if the table being
115757  ** updated is a view.
115758  */
115759#ifndef SQLITE_OMIT_TRIGGER
115760  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
115761  isView = pTab->pSelect!=0;
115762  assert( pTrigger || tmask==0 );
115763#else
115764# define pTrigger 0
115765# define isView 0
115766# define tmask 0
115767#endif
115768#ifdef SQLITE_OMIT_VIEW
115769# undef isView
115770# define isView 0
115771#endif
115772
115773  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
115774    goto update_cleanup;
115775  }
115776  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
115777    goto update_cleanup;
115778  }
115779
115780  /* Allocate a cursors for the main database table and for all indices.
115781  ** The index cursors might not be used, but if they are used they
115782  ** need to occur right after the database cursor.  So go ahead and
115783  ** allocate enough space, just in case.
115784  */
115785  pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
115786  iIdxCur = iDataCur+1;
115787  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
115788  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
115789    if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
115790      iDataCur = pParse->nTab;
115791      pTabList->a[0].iCursor = iDataCur;
115792    }
115793    pParse->nTab++;
115794  }
115795
115796  /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
115797  ** Initialize aXRef[] and aToOpen[] to their default values.
115798  */
115799  aXRef = sqlite3DbMallocRaw(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
115800  if( aXRef==0 ) goto update_cleanup;
115801  aRegIdx = aXRef+pTab->nCol;
115802  aToOpen = (u8*)(aRegIdx+nIdx);
115803  memset(aToOpen, 1, nIdx+1);
115804  aToOpen[nIdx+1] = 0;
115805  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
115806
115807  /* Initialize the name-context */
115808  memset(&sNC, 0, sizeof(sNC));
115809  sNC.pParse = pParse;
115810  sNC.pSrcList = pTabList;
115811
115812  /* Resolve the column names in all the expressions of the
115813  ** of the UPDATE statement.  Also find the column index
115814  ** for each column to be updated in the pChanges array.  For each
115815  ** column to be updated, make sure we have authorization to change
115816  ** that column.
115817  */
115818  chngRowid = chngPk = 0;
115819  for(i=0; i<pChanges->nExpr; i++){
115820    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
115821      goto update_cleanup;
115822    }
115823    for(j=0; j<pTab->nCol; j++){
115824      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
115825        if( j==pTab->iPKey ){
115826          chngRowid = 1;
115827          pRowidExpr = pChanges->a[i].pExpr;
115828        }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
115829          chngPk = 1;
115830        }
115831        aXRef[j] = i;
115832        break;
115833      }
115834    }
115835    if( j>=pTab->nCol ){
115836      if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
115837        j = -1;
115838        chngRowid = 1;
115839        pRowidExpr = pChanges->a[i].pExpr;
115840      }else{
115841        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
115842        pParse->checkSchema = 1;
115843        goto update_cleanup;
115844      }
115845    }
115846#ifndef SQLITE_OMIT_AUTHORIZATION
115847    {
115848      int rc;
115849      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
115850                            j<0 ? "ROWID" : pTab->aCol[j].zName,
115851                            db->aDb[iDb].zName);
115852      if( rc==SQLITE_DENY ){
115853        goto update_cleanup;
115854      }else if( rc==SQLITE_IGNORE ){
115855        aXRef[j] = -1;
115856      }
115857    }
115858#endif
115859  }
115860  assert( (chngRowid & chngPk)==0 );
115861  assert( chngRowid==0 || chngRowid==1 );
115862  assert( chngPk==0 || chngPk==1 );
115863  chngKey = chngRowid + chngPk;
115864
115865  /* The SET expressions are not actually used inside the WHERE loop.
115866  ** So reset the colUsed mask
115867  */
115868  pTabList->a[0].colUsed = 0;
115869
115870  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
115871
115872  /* There is one entry in the aRegIdx[] array for each index on the table
115873  ** being updated.  Fill in aRegIdx[] with a register number that will hold
115874  ** the key for accessing each index.
115875  **
115876  ** FIXME:  Be smarter about omitting indexes that use expressions.
115877  */
115878  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
115879    int reg;
115880    if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
115881      reg = ++pParse->nMem;
115882    }else{
115883      reg = 0;
115884      for(i=0; i<pIdx->nKeyCol; i++){
115885        i16 iIdxCol = pIdx->aiColumn[i];
115886        if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
115887          reg = ++pParse->nMem;
115888          break;
115889        }
115890      }
115891    }
115892    if( reg==0 ) aToOpen[j+1] = 0;
115893    aRegIdx[j] = reg;
115894  }
115895
115896  /* Begin generating code. */
115897  v = sqlite3GetVdbe(pParse);
115898  if( v==0 ) goto update_cleanup;
115899  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
115900  sqlite3BeginWriteOperation(pParse, 1, iDb);
115901
115902  /* Allocate required registers. */
115903  if( !IsVirtual(pTab) ){
115904    regRowSet = ++pParse->nMem;
115905    regOldRowid = regNewRowid = ++pParse->nMem;
115906    if( chngPk || pTrigger || hasFK ){
115907      regOld = pParse->nMem + 1;
115908      pParse->nMem += pTab->nCol;
115909    }
115910    if( chngKey || pTrigger || hasFK ){
115911      regNewRowid = ++pParse->nMem;
115912    }
115913    regNew = pParse->nMem + 1;
115914    pParse->nMem += pTab->nCol;
115915  }
115916
115917  /* Start the view context. */
115918  if( isView ){
115919    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
115920  }
115921
115922  /* If we are trying to update a view, realize that view into
115923  ** an ephemeral table.
115924  */
115925#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
115926  if( isView ){
115927    sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
115928  }
115929#endif
115930
115931  /* Resolve the column names in all the expressions in the
115932  ** WHERE clause.
115933  */
115934  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
115935    goto update_cleanup;
115936  }
115937
115938#ifndef SQLITE_OMIT_VIRTUALTABLE
115939  /* Virtual tables must be handled separately */
115940  if( IsVirtual(pTab) ){
115941    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
115942                       pWhere, onError);
115943    goto update_cleanup;
115944  }
115945#endif
115946
115947  /* Begin the database scan
115948  */
115949  if( HasRowid(pTab) ){
115950    sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
115951    pWInfo = sqlite3WhereBegin(
115952        pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
115953    );
115954    if( pWInfo==0 ) goto update_cleanup;
115955    okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
115956
115957    /* Remember the rowid of every item to be updated.
115958    */
115959    sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
115960    if( !okOnePass ){
115961      sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
115962    }
115963
115964    /* End the database scan loop.
115965    */
115966    sqlite3WhereEnd(pWInfo);
115967  }else{
115968    int iPk;         /* First of nPk memory cells holding PRIMARY KEY value */
115969    i16 nPk;         /* Number of components of the PRIMARY KEY */
115970    int addrOpen;    /* Address of the OpenEphemeral instruction */
115971
115972    assert( pPk!=0 );
115973    nPk = pPk->nKeyCol;
115974    iPk = pParse->nMem+1;
115975    pParse->nMem += nPk;
115976    regKey = ++pParse->nMem;
115977    iEph = pParse->nTab++;
115978    sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
115979    addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
115980    sqlite3VdbeSetP4KeyInfo(pParse, pPk);
115981    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
115982                               WHERE_ONEPASS_DESIRED, iIdxCur);
115983    if( pWInfo==0 ) goto update_cleanup;
115984    okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
115985    for(i=0; i<nPk; i++){
115986      assert( pPk->aiColumn[i]>=0 );
115987      sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
115988                                      iPk+i);
115989    }
115990    if( okOnePass ){
115991      sqlite3VdbeChangeToNoop(v, addrOpen);
115992      nKey = nPk;
115993      regKey = iPk;
115994    }else{
115995      sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
115996                        sqlite3IndexAffinityStr(db, pPk), nPk);
115997      sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
115998    }
115999    sqlite3WhereEnd(pWInfo);
116000  }
116001
116002  /* Initialize the count of updated rows
116003  */
116004  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
116005    regRowCount = ++pParse->nMem;
116006    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
116007  }
116008
116009  labelBreak = sqlite3VdbeMakeLabel(v);
116010  if( !isView ){
116011    /*
116012    ** Open every index that needs updating.  Note that if any
116013    ** index could potentially invoke a REPLACE conflict resolution
116014    ** action, then we need to open all indices because we might need
116015    ** to be deleting some records.
116016    */
116017    if( onError==OE_Replace ){
116018      memset(aToOpen, 1, nIdx+1);
116019    }else{
116020      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
116021        if( pIdx->onError==OE_Replace ){
116022          memset(aToOpen, 1, nIdx+1);
116023          break;
116024        }
116025      }
116026    }
116027    if( okOnePass ){
116028      if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
116029      if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
116030    }
116031    sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iBaseCur, aToOpen,
116032                               0, 0);
116033  }
116034
116035  /* Top of the update loop */
116036  if( okOnePass ){
116037    if( aToOpen[iDataCur-iBaseCur] && !isView ){
116038      assert( pPk );
116039      sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
116040      VdbeCoverageNeverTaken(v);
116041    }
116042    labelContinue = labelBreak;
116043    sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
116044    VdbeCoverageIf(v, pPk==0);
116045    VdbeCoverageIf(v, pPk!=0);
116046  }else if( pPk ){
116047    labelContinue = sqlite3VdbeMakeLabel(v);
116048    sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
116049    addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
116050    sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
116051    VdbeCoverage(v);
116052  }else{
116053    labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
116054                             regOldRowid);
116055    VdbeCoverage(v);
116056    sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
116057    VdbeCoverage(v);
116058  }
116059
116060  /* If the record number will change, set register regNewRowid to
116061  ** contain the new value. If the record number is not being modified,
116062  ** then regNewRowid is the same register as regOldRowid, which is
116063  ** already populated.  */
116064  assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
116065  if( chngRowid ){
116066    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
116067    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
116068  }
116069
116070  /* Compute the old pre-UPDATE content of the row being changed, if that
116071  ** information is needed */
116072  if( chngPk || hasFK || pTrigger ){
116073    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
116074    oldmask |= sqlite3TriggerColmask(pParse,
116075        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
116076    );
116077    for(i=0; i<pTab->nCol; i++){
116078      if( oldmask==0xffffffff
116079       || (i<32 && (oldmask & MASKBIT32(i))!=0)
116080       || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
116081      ){
116082        testcase(  oldmask!=0xffffffff && i==31 );
116083        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
116084      }else{
116085        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
116086      }
116087    }
116088    if( chngRowid==0 && pPk==0 ){
116089      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
116090    }
116091  }
116092
116093  /* Populate the array of registers beginning at regNew with the new
116094  ** row data. This array is used to check constants, create the new
116095  ** table and index records, and as the values for any new.* references
116096  ** made by triggers.
116097  **
116098  ** If there are one or more BEFORE triggers, then do not populate the
116099  ** registers associated with columns that are (a) not modified by
116100  ** this UPDATE statement and (b) not accessed by new.* references. The
116101  ** values for registers not modified by the UPDATE must be reloaded from
116102  ** the database after the BEFORE triggers are fired anyway (as the trigger
116103  ** may have modified them). So not loading those that are not going to
116104  ** be used eliminates some redundant opcodes.
116105  */
116106  newmask = sqlite3TriggerColmask(
116107      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
116108  );
116109  for(i=0; i<pTab->nCol; i++){
116110    if( i==pTab->iPKey ){
116111      sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
116112    }else{
116113      j = aXRef[i];
116114      if( j>=0 ){
116115        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
116116      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
116117        /* This branch loads the value of a column that will not be changed
116118        ** into a register. This is done if there are no BEFORE triggers, or
116119        ** if there are one or more BEFORE triggers that use this value via
116120        ** a new.* reference in a trigger program.
116121        */
116122        testcase( i==31 );
116123        testcase( i==32 );
116124        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
116125      }else{
116126        sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
116127      }
116128    }
116129  }
116130
116131  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
116132  ** verified. One could argue that this is wrong.
116133  */
116134  if( tmask&TRIGGER_BEFORE ){
116135    sqlite3TableAffinity(v, pTab, regNew);
116136    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
116137        TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
116138
116139    /* The row-trigger may have deleted the row being updated. In this
116140    ** case, jump to the next row. No updates or AFTER triggers are
116141    ** required. This behavior - what happens when the row being updated
116142    ** is deleted or renamed by a BEFORE trigger - is left undefined in the
116143    ** documentation.
116144    */
116145    if( pPk ){
116146      sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
116147      VdbeCoverage(v);
116148    }else{
116149      sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
116150      VdbeCoverage(v);
116151    }
116152
116153    /* If it did not delete it, the row-trigger may still have modified
116154    ** some of the columns of the row being updated. Load the values for
116155    ** all columns not modified by the update statement into their
116156    ** registers in case this has happened.
116157    */
116158    for(i=0; i<pTab->nCol; i++){
116159      if( aXRef[i]<0 && i!=pTab->iPKey ){
116160        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
116161      }
116162    }
116163  }
116164
116165  if( !isView ){
116166    int addr1 = 0;        /* Address of jump instruction */
116167    int bReplace = 0;     /* True if REPLACE conflict resolution might happen */
116168
116169    /* Do constraint checks. */
116170    assert( regOldRowid>0 );
116171    sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
116172        regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace);
116173
116174    /* Do FK constraint checks. */
116175    if( hasFK ){
116176      sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
116177    }
116178
116179    /* Delete the index entries associated with the current record.  */
116180    if( bReplace || chngKey ){
116181      if( pPk ){
116182        addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
116183      }else{
116184        addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
116185      }
116186      VdbeCoverageNeverTaken(v);
116187    }
116188    sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
116189
116190    /* If changing the record number, delete the old record.  */
116191    if( hasFK || chngKey || pPk!=0 ){
116192      sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
116193    }
116194    if( bReplace || chngKey ){
116195      sqlite3VdbeJumpHere(v, addr1);
116196    }
116197
116198    if( hasFK ){
116199      sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
116200    }
116201
116202    /* Insert the new index entries and the new record. */
116203    sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
116204                             regNewRowid, aRegIdx, 1, 0, 0);
116205
116206    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
116207    ** handle rows (possibly in other tables) that refer via a foreign key
116208    ** to the row just updated. */
116209    if( hasFK ){
116210      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
116211    }
116212  }
116213
116214  /* Increment the row counter
116215  */
116216  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
116217    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
116218  }
116219
116220  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
116221      TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
116222
116223  /* Repeat the above with the next record to be updated, until
116224  ** all record selected by the WHERE clause have been updated.
116225  */
116226  if( okOnePass ){
116227    /* Nothing to do at end-of-loop for a single-pass */
116228  }else if( pPk ){
116229    sqlite3VdbeResolveLabel(v, labelContinue);
116230    sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
116231  }else{
116232    sqlite3VdbeGoto(v, labelContinue);
116233  }
116234  sqlite3VdbeResolveLabel(v, labelBreak);
116235
116236  /* Close all tables */
116237  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
116238    assert( aRegIdx );
116239    if( aToOpen[i+1] ){
116240      sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
116241    }
116242  }
116243  if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
116244
116245  /* Update the sqlite_sequence table by storing the content of the
116246  ** maximum rowid counter values recorded while inserting into
116247  ** autoincrement tables.
116248  */
116249  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
116250    sqlite3AutoincrementEnd(pParse);
116251  }
116252
116253  /*
116254  ** Return the number of rows that were changed. If this routine is
116255  ** generating code because of a call to sqlite3NestedParse(), do not
116256  ** invoke the callback function.
116257  */
116258  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
116259    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
116260    sqlite3VdbeSetNumCols(v, 1);
116261    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
116262  }
116263
116264update_cleanup:
116265  sqlite3AuthContextPop(&sContext);
116266  sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
116267  sqlite3SrcListDelete(db, pTabList);
116268  sqlite3ExprListDelete(db, pChanges);
116269  sqlite3ExprDelete(db, pWhere);
116270  return;
116271}
116272/* Make sure "isView" and other macros defined above are undefined. Otherwise
116273** they may interfere with compilation of other functions in this file
116274** (or in another file, if this file becomes part of the amalgamation).  */
116275#ifdef isView
116276 #undef isView
116277#endif
116278#ifdef pTrigger
116279 #undef pTrigger
116280#endif
116281
116282#ifndef SQLITE_OMIT_VIRTUALTABLE
116283/*
116284** Generate code for an UPDATE of a virtual table.
116285**
116286** There are two possible strategies - the default and the special
116287** "onepass" strategy. Onepass is only used if the virtual table
116288** implementation indicates that pWhere may match at most one row.
116289**
116290** The default strategy is to create an ephemeral table that contains
116291** for each row to be changed:
116292**
116293**   (A)  The original rowid of that row.
116294**   (B)  The revised rowid for the row.
116295**   (C)  The content of every column in the row.
116296**
116297** Then loop through the contents of this ephemeral table executing a
116298** VUpdate for each row. When finished, drop the ephemeral table.
116299**
116300** The "onepass" strategy does not use an ephemeral table. Instead, it
116301** stores the same values (A, B and C above) in a register array and
116302** makes a single invocation of VUpdate.
116303*/
116304static void updateVirtualTable(
116305  Parse *pParse,       /* The parsing context */
116306  SrcList *pSrc,       /* The virtual table to be modified */
116307  Table *pTab,         /* The virtual table */
116308  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
116309  Expr *pRowid,        /* Expression used to recompute the rowid */
116310  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
116311  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
116312  int onError          /* ON CONFLICT strategy */
116313){
116314  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
116315  int ephemTab;             /* Table holding the result of the SELECT */
116316  int i;                    /* Loop counter */
116317  sqlite3 *db = pParse->db; /* Database connection */
116318  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
116319  WhereInfo *pWInfo;
116320  int nArg = 2 + pTab->nCol;      /* Number of arguments to VUpdate */
116321  int regArg;                     /* First register in VUpdate arg array */
116322  int regRec;                     /* Register in which to assemble record */
116323  int regRowid;                   /* Register for ephem table rowid */
116324  int iCsr = pSrc->a[0].iCursor;  /* Cursor used for virtual table scan */
116325  int aDummy[2];                  /* Unused arg for sqlite3WhereOkOnePass() */
116326  int bOnePass;                   /* True to use onepass strategy */
116327  int addr;                       /* Address of OP_OpenEphemeral */
116328
116329  /* Allocate nArg registers to martial the arguments to VUpdate. Then
116330  ** create and open the ephemeral table in which the records created from
116331  ** these arguments will be temporarily stored. */
116332  assert( v );
116333  ephemTab = pParse->nTab++;
116334  addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
116335  regArg = pParse->nMem + 1;
116336  pParse->nMem += nArg;
116337  regRec = ++pParse->nMem;
116338  regRowid = ++pParse->nMem;
116339
116340  /* Start scanning the virtual table */
116341  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
116342  if( pWInfo==0 ) return;
116343
116344  /* Populate the argument registers. */
116345  sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
116346  if( pRowid ){
116347    sqlite3ExprCode(pParse, pRowid, regArg+1);
116348  }else{
116349    sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
116350  }
116351  for(i=0; i<pTab->nCol; i++){
116352    if( aXRef[i]>=0 ){
116353      sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
116354    }else{
116355      sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
116356    }
116357  }
116358
116359  bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
116360
116361  if( bOnePass ){
116362    /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
116363    ** above. Also, if this is a top-level parse (not a trigger), clear the
116364    ** multi-write flag so that the VM does not open a statement journal */
116365    sqlite3VdbeChangeToNoop(v, addr);
116366    if( sqlite3IsToplevel(pParse) ){
116367      pParse->isMultiWrite = 0;
116368    }
116369  }else{
116370    /* Create a record from the argument register contents and insert it into
116371    ** the ephemeral table. */
116372    sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
116373    sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
116374    sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
116375  }
116376
116377
116378  if( bOnePass==0 ){
116379    /* End the virtual table scan */
116380    sqlite3WhereEnd(pWInfo);
116381
116382    /* Begin scannning through the ephemeral table. */
116383    addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
116384
116385    /* Extract arguments from the current row of the ephemeral table and
116386    ** invoke the VUpdate method.  */
116387    for(i=0; i<nArg; i++){
116388      sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
116389    }
116390  }
116391  sqlite3VtabMakeWritable(pParse, pTab);
116392  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
116393  sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
116394  sqlite3MayAbort(pParse);
116395
116396  /* End of the ephemeral table scan. Or, if using the onepass strategy,
116397  ** jump to here if the scan visited zero rows. */
116398  if( bOnePass==0 ){
116399    sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
116400    sqlite3VdbeJumpHere(v, addr);
116401    sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
116402  }else{
116403    sqlite3WhereEnd(pWInfo);
116404  }
116405}
116406#endif /* SQLITE_OMIT_VIRTUALTABLE */
116407
116408/************** End of update.c **********************************************/
116409/************** Begin file vacuum.c ******************************************/
116410/*
116411** 2003 April 6
116412**
116413** The author disclaims copyright to this source code.  In place of
116414** a legal notice, here is a blessing:
116415**
116416**    May you do good and not evil.
116417**    May you find forgiveness for yourself and forgive others.
116418**    May you share freely, never taking more than you give.
116419**
116420*************************************************************************
116421** This file contains code used to implement the VACUUM command.
116422**
116423** Most of the code in this file may be omitted by defining the
116424** SQLITE_OMIT_VACUUM macro.
116425*/
116426/* #include "sqliteInt.h" */
116427/* #include "vdbeInt.h" */
116428
116429#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
116430/*
116431** Finalize a prepared statement.  If there was an error, store the
116432** text of the error message in *pzErrMsg.  Return the result code.
116433*/
116434static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
116435  int rc;
116436  rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
116437  if( rc ){
116438    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
116439  }
116440  return rc;
116441}
116442
116443/*
116444** Execute zSql on database db. Return an error code.
116445*/
116446static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
116447  sqlite3_stmt *pStmt;
116448  VVA_ONLY( int rc; )
116449  if( !zSql ){
116450    return SQLITE_NOMEM;
116451  }
116452  if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
116453    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
116454    return sqlite3_errcode(db);
116455  }
116456  VVA_ONLY( rc = ) sqlite3_step(pStmt);
116457  assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
116458  return vacuumFinalize(db, pStmt, pzErrMsg);
116459}
116460
116461/*
116462** Execute zSql on database db. The statement returns exactly
116463** one column. Execute this as SQL on the same database.
116464*/
116465static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
116466  sqlite3_stmt *pStmt;
116467  int rc;
116468
116469  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
116470  if( rc!=SQLITE_OK ) return rc;
116471
116472  while( SQLITE_ROW==sqlite3_step(pStmt) ){
116473    rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
116474    if( rc!=SQLITE_OK ){
116475      vacuumFinalize(db, pStmt, pzErrMsg);
116476      return rc;
116477    }
116478  }
116479
116480  return vacuumFinalize(db, pStmt, pzErrMsg);
116481}
116482
116483/*
116484** The VACUUM command is used to clean up the database,
116485** collapse free space, etc.  It is modelled after the VACUUM command
116486** in PostgreSQL.  The VACUUM command works as follows:
116487**
116488**   (1)  Create a new transient database file
116489**   (2)  Copy all content from the database being vacuumed into
116490**        the new transient database file
116491**   (3)  Copy content from the transient database back into the
116492**        original database.
116493**
116494** The transient database requires temporary disk space approximately
116495** equal to the size of the original database.  The copy operation of
116496** step (3) requires additional temporary disk space approximately equal
116497** to the size of the original database for the rollback journal.
116498** Hence, temporary disk space that is approximately 2x the size of the
116499** original database is required.  Every page of the database is written
116500** approximately 3 times:  Once for step (2) and twice for step (3).
116501** Two writes per page are required in step (3) because the original
116502** database content must be written into the rollback journal prior to
116503** overwriting the database with the vacuumed content.
116504**
116505** Only 1x temporary space and only 1x writes would be required if
116506** the copy of step (3) were replaced by deleting the original database
116507** and renaming the transient database as the original.  But that will
116508** not work if other processes are attached to the original database.
116509** And a power loss in between deleting the original and renaming the
116510** transient would cause the database file to appear to be deleted
116511** following reboot.
116512*/
116513SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
116514  Vdbe *v = sqlite3GetVdbe(pParse);
116515  if( v ){
116516    sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
116517    sqlite3VdbeUsesBtree(v, 0);
116518  }
116519  return;
116520}
116521
116522/*
116523** This routine implements the OP_Vacuum opcode of the VDBE.
116524*/
116525SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
116526  int rc = SQLITE_OK;     /* Return code from service routines */
116527  Btree *pMain;           /* The database being vacuumed */
116528  Btree *pTemp;           /* The temporary database we vacuum into */
116529  char *zSql = 0;         /* SQL statements */
116530  int saved_flags;        /* Saved value of the db->flags */
116531  int saved_nChange;      /* Saved value of db->nChange */
116532  int saved_nTotalChange; /* Saved value of db->nTotalChange */
116533  void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
116534  Db *pDb = 0;            /* Database to detach at end of vacuum */
116535  int isMemDb;            /* True if vacuuming a :memory: database */
116536  int nRes;               /* Bytes of reserved space at the end of each page */
116537  int nDb;                /* Number of attached databases */
116538
116539  if( !db->autoCommit ){
116540    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
116541    return SQLITE_ERROR;
116542  }
116543  if( db->nVdbeActive>1 ){
116544    sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
116545    return SQLITE_ERROR;
116546  }
116547
116548  /* Save the current value of the database flags so that it can be
116549  ** restored before returning. Then set the writable-schema flag, and
116550  ** disable CHECK and foreign key constraints.  */
116551  saved_flags = db->flags;
116552  saved_nChange = db->nChange;
116553  saved_nTotalChange = db->nTotalChange;
116554  saved_xTrace = db->xTrace;
116555  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
116556  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
116557  db->xTrace = 0;
116558
116559  pMain = db->aDb[0].pBt;
116560  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
116561
116562  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
116563  ** can be set to 'off' for this file, as it is not recovered if a crash
116564  ** occurs anyway. The integrity of the database is maintained by a
116565  ** (possibly synchronous) transaction opened on the main database before
116566  ** sqlite3BtreeCopyFile() is called.
116567  **
116568  ** An optimisation would be to use a non-journaled pager.
116569  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
116570  ** that actually made the VACUUM run slower.  Very little journalling
116571  ** actually occurs when doing a vacuum since the vacuum_db is initially
116572  ** empty.  Only the journal header is written.  Apparently it takes more
116573  ** time to parse and run the PRAGMA to turn journalling off than it does
116574  ** to write the journal header file.
116575  */
116576  nDb = db->nDb;
116577  if( sqlite3TempInMemory(db) ){
116578    zSql = "ATTACH ':memory:' AS vacuum_db;";
116579  }else{
116580    zSql = "ATTACH '' AS vacuum_db;";
116581  }
116582  rc = execSql(db, pzErrMsg, zSql);
116583  if( db->nDb>nDb ){
116584    pDb = &db->aDb[db->nDb-1];
116585    assert( strcmp(pDb->zName,"vacuum_db")==0 );
116586  }
116587  if( rc!=SQLITE_OK ) goto end_of_vacuum;
116588  pTemp = db->aDb[db->nDb-1].pBt;
116589
116590  /* The call to execSql() to attach the temp database has left the file
116591  ** locked (as there was more than one active statement when the transaction
116592  ** to read the schema was concluded. Unlock it here so that this doesn't
116593  ** cause problems for the call to BtreeSetPageSize() below.  */
116594  sqlite3BtreeCommit(pTemp);
116595
116596  nRes = sqlite3BtreeGetOptimalReserve(pMain);
116597
116598  /* A VACUUM cannot change the pagesize of an encrypted database. */
116599#ifdef SQLITE_HAS_CODEC
116600  if( db->nextPagesize ){
116601    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
116602    int nKey;
116603    char *zKey;
116604    sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
116605    if( nKey ) db->nextPagesize = 0;
116606  }
116607#endif
116608
116609  rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
116610  if( rc!=SQLITE_OK ) goto end_of_vacuum;
116611
116612  /* Begin a transaction and take an exclusive lock on the main database
116613  ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
116614  ** to ensure that we do not try to change the page-size on a WAL database.
116615  */
116616  rc = execSql(db, pzErrMsg, "BEGIN;");
116617  if( rc!=SQLITE_OK ) goto end_of_vacuum;
116618  rc = sqlite3BtreeBeginTrans(pMain, 2);
116619  if( rc!=SQLITE_OK ) goto end_of_vacuum;
116620
116621  /* Do not attempt to change the page size for a WAL database */
116622  if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
116623                                               ==PAGER_JOURNALMODE_WAL ){
116624    db->nextPagesize = 0;
116625  }
116626
116627  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
116628   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
116629   || NEVER(db->mallocFailed)
116630  ){
116631    rc = SQLITE_NOMEM;
116632    goto end_of_vacuum;
116633  }
116634
116635#ifndef SQLITE_OMIT_AUTOVACUUM
116636  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
116637                                           sqlite3BtreeGetAutoVacuum(pMain));
116638#endif
116639
116640  /* Query the schema of the main database. Create a mirror schema
116641  ** in the temporary database.
116642  */
116643  rc = execExecSql(db, pzErrMsg,
116644      "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
116645      "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
116646      "   AND coalesce(rootpage,1)>0"
116647  );
116648  if( rc!=SQLITE_OK ) goto end_of_vacuum;
116649  rc = execExecSql(db, pzErrMsg,
116650      "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
116651      "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
116652  if( rc!=SQLITE_OK ) goto end_of_vacuum;
116653  rc = execExecSql(db, pzErrMsg,
116654      "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
116655      "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
116656  if( rc!=SQLITE_OK ) goto end_of_vacuum;
116657
116658  /* Loop through the tables in the main database. For each, do
116659  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
116660  ** the contents to the temporary database.
116661  */
116662  assert( (db->flags & SQLITE_Vacuum)==0 );
116663  db->flags |= SQLITE_Vacuum;
116664  rc = execExecSql(db, pzErrMsg,
116665      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
116666      "|| ' SELECT * FROM main.' || quote(name) || ';'"
116667      "FROM main.sqlite_master "
116668      "WHERE type = 'table' AND name!='sqlite_sequence' "
116669      "  AND coalesce(rootpage,1)>0"
116670  );
116671  assert( (db->flags & SQLITE_Vacuum)!=0 );
116672  db->flags &= ~SQLITE_Vacuum;
116673  if( rc!=SQLITE_OK ) goto end_of_vacuum;
116674
116675  /* Copy over the sequence table
116676  */
116677  rc = execExecSql(db, pzErrMsg,
116678      "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
116679      "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
116680  );
116681  if( rc!=SQLITE_OK ) goto end_of_vacuum;
116682  rc = execExecSql(db, pzErrMsg,
116683      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
116684      "|| ' SELECT * FROM main.' || quote(name) || ';' "
116685      "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
116686  );
116687  if( rc!=SQLITE_OK ) goto end_of_vacuum;
116688
116689
116690  /* Copy the triggers, views, and virtual tables from the main database
116691  ** over to the temporary database.  None of these objects has any
116692  ** associated storage, so all we have to do is copy their entries
116693  ** from the SQLITE_MASTER table.
116694  */
116695  rc = execSql(db, pzErrMsg,
116696      "INSERT INTO vacuum_db.sqlite_master "
116697      "  SELECT type, name, tbl_name, rootpage, sql"
116698      "    FROM main.sqlite_master"
116699      "   WHERE type='view' OR type='trigger'"
116700      "      OR (type='table' AND rootpage=0)"
116701  );
116702  if( rc ) goto end_of_vacuum;
116703
116704  /* At this point, there is a write transaction open on both the
116705  ** vacuum database and the main database. Assuming no error occurs,
116706  ** both transactions are closed by this block - the main database
116707  ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
116708  ** call to sqlite3BtreeCommit().
116709  */
116710  {
116711    u32 meta;
116712    int i;
116713
116714    /* This array determines which meta meta values are preserved in the
116715    ** vacuum.  Even entries are the meta value number and odd entries
116716    ** are an increment to apply to the meta value after the vacuum.
116717    ** The increment is used to increase the schema cookie so that other
116718    ** connections to the same database will know to reread the schema.
116719    */
116720    static const unsigned char aCopy[] = {
116721       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
116722       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
116723       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
116724       BTREE_USER_VERSION,       0,  /* Preserve the user version */
116725       BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
116726    };
116727
116728    assert( 1==sqlite3BtreeIsInTrans(pTemp) );
116729    assert( 1==sqlite3BtreeIsInTrans(pMain) );
116730
116731    /* Copy Btree meta values */
116732    for(i=0; i<ArraySize(aCopy); i+=2){
116733      /* GetMeta() and UpdateMeta() cannot fail in this context because
116734      ** we already have page 1 loaded into cache and marked dirty. */
116735      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
116736      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
116737      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
116738    }
116739
116740    rc = sqlite3BtreeCopyFile(pMain, pTemp);
116741    if( rc!=SQLITE_OK ) goto end_of_vacuum;
116742    rc = sqlite3BtreeCommit(pTemp);
116743    if( rc!=SQLITE_OK ) goto end_of_vacuum;
116744#ifndef SQLITE_OMIT_AUTOVACUUM
116745    sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
116746#endif
116747  }
116748
116749  assert( rc==SQLITE_OK );
116750  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
116751
116752end_of_vacuum:
116753  /* Restore the original value of db->flags */
116754  db->flags = saved_flags;
116755  db->nChange = saved_nChange;
116756  db->nTotalChange = saved_nTotalChange;
116757  db->xTrace = saved_xTrace;
116758  sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
116759
116760  /* Currently there is an SQL level transaction open on the vacuum
116761  ** database. No locks are held on any other files (since the main file
116762  ** was committed at the btree level). So it safe to end the transaction
116763  ** by manually setting the autoCommit flag to true and detaching the
116764  ** vacuum database. The vacuum_db journal file is deleted when the pager
116765  ** is closed by the DETACH.
116766  */
116767  db->autoCommit = 1;
116768
116769  if( pDb ){
116770    sqlite3BtreeClose(pDb->pBt);
116771    pDb->pBt = 0;
116772    pDb->pSchema = 0;
116773  }
116774
116775  /* This both clears the schemas and reduces the size of the db->aDb[]
116776  ** array. */
116777  sqlite3ResetAllSchemasOfConnection(db);
116778
116779  return rc;
116780}
116781
116782#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
116783
116784/************** End of vacuum.c **********************************************/
116785/************** Begin file vtab.c ********************************************/
116786/*
116787** 2006 June 10
116788**
116789** The author disclaims copyright to this source code.  In place of
116790** a legal notice, here is a blessing:
116791**
116792**    May you do good and not evil.
116793**    May you find forgiveness for yourself and forgive others.
116794**    May you share freely, never taking more than you give.
116795**
116796*************************************************************************
116797** This file contains code used to help implement virtual tables.
116798*/
116799#ifndef SQLITE_OMIT_VIRTUALTABLE
116800/* #include "sqliteInt.h" */
116801
116802/*
116803** Before a virtual table xCreate() or xConnect() method is invoked, the
116804** sqlite3.pVtabCtx member variable is set to point to an instance of
116805** this struct allocated on the stack. It is used by the implementation of
116806** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
116807** are invoked only from within xCreate and xConnect methods.
116808*/
116809struct VtabCtx {
116810  VTable *pVTable;    /* The virtual table being constructed */
116811  Table *pTab;        /* The Table object to which the virtual table belongs */
116812  VtabCtx *pPrior;    /* Parent context (if any) */
116813  int bDeclared;      /* True after sqlite3_declare_vtab() is called */
116814};
116815
116816/*
116817** The actual function that does the work of creating a new module.
116818** This function implements the sqlite3_create_module() and
116819** sqlite3_create_module_v2() interfaces.
116820*/
116821static int createModule(
116822  sqlite3 *db,                    /* Database in which module is registered */
116823  const char *zName,              /* Name assigned to this module */
116824  const sqlite3_module *pModule,  /* The definition of the module */
116825  void *pAux,                     /* Context pointer for xCreate/xConnect */
116826  void (*xDestroy)(void *)        /* Module destructor function */
116827){
116828  int rc = SQLITE_OK;
116829  int nName;
116830
116831  sqlite3_mutex_enter(db->mutex);
116832  nName = sqlite3Strlen30(zName);
116833  if( sqlite3HashFind(&db->aModule, zName) ){
116834    rc = SQLITE_MISUSE_BKPT;
116835  }else{
116836    Module *pMod;
116837    pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
116838    if( pMod ){
116839      Module *pDel;
116840      char *zCopy = (char *)(&pMod[1]);
116841      memcpy(zCopy, zName, nName+1);
116842      pMod->zName = zCopy;
116843      pMod->pModule = pModule;
116844      pMod->pAux = pAux;
116845      pMod->xDestroy = xDestroy;
116846      pMod->pEpoTab = 0;
116847      pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
116848      assert( pDel==0 || pDel==pMod );
116849      if( pDel ){
116850        db->mallocFailed = 1;
116851        sqlite3DbFree(db, pDel);
116852      }
116853    }
116854  }
116855  rc = sqlite3ApiExit(db, rc);
116856  if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
116857
116858  sqlite3_mutex_leave(db->mutex);
116859  return rc;
116860}
116861
116862
116863/*
116864** External API function used to create a new virtual-table module.
116865*/
116866SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
116867  sqlite3 *db,                    /* Database in which module is registered */
116868  const char *zName,              /* Name assigned to this module */
116869  const sqlite3_module *pModule,  /* The definition of the module */
116870  void *pAux                      /* Context pointer for xCreate/xConnect */
116871){
116872#ifdef SQLITE_ENABLE_API_ARMOR
116873  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
116874#endif
116875  return createModule(db, zName, pModule, pAux, 0);
116876}
116877
116878/*
116879** External API function used to create a new virtual-table module.
116880*/
116881SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
116882  sqlite3 *db,                    /* Database in which module is registered */
116883  const char *zName,              /* Name assigned to this module */
116884  const sqlite3_module *pModule,  /* The definition of the module */
116885  void *pAux,                     /* Context pointer for xCreate/xConnect */
116886  void (*xDestroy)(void *)        /* Module destructor function */
116887){
116888#ifdef SQLITE_ENABLE_API_ARMOR
116889  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
116890#endif
116891  return createModule(db, zName, pModule, pAux, xDestroy);
116892}
116893
116894/*
116895** Lock the virtual table so that it cannot be disconnected.
116896** Locks nest.  Every lock should have a corresponding unlock.
116897** If an unlock is omitted, resources leaks will occur.
116898**
116899** If a disconnect is attempted while a virtual table is locked,
116900** the disconnect is deferred until all locks have been removed.
116901*/
116902SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
116903  pVTab->nRef++;
116904}
116905
116906
116907/*
116908** pTab is a pointer to a Table structure representing a virtual-table.
116909** Return a pointer to the VTable object used by connection db to access
116910** this virtual-table, if one has been created, or NULL otherwise.
116911*/
116912SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
116913  VTable *pVtab;
116914  assert( IsVirtual(pTab) );
116915  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
116916  return pVtab;
116917}
116918
116919/*
116920** Decrement the ref-count on a virtual table object. When the ref-count
116921** reaches zero, call the xDisconnect() method to delete the object.
116922*/
116923SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
116924  sqlite3 *db = pVTab->db;
116925
116926  assert( db );
116927  assert( pVTab->nRef>0 );
116928  assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
116929
116930  pVTab->nRef--;
116931  if( pVTab->nRef==0 ){
116932    sqlite3_vtab *p = pVTab->pVtab;
116933    if( p ){
116934      p->pModule->xDisconnect(p);
116935    }
116936    sqlite3DbFree(db, pVTab);
116937  }
116938}
116939
116940/*
116941** Table p is a virtual table. This function moves all elements in the
116942** p->pVTable list to the sqlite3.pDisconnect lists of their associated
116943** database connections to be disconnected at the next opportunity.
116944** Except, if argument db is not NULL, then the entry associated with
116945** connection db is left in the p->pVTable list.
116946*/
116947static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
116948  VTable *pRet = 0;
116949  VTable *pVTable = p->pVTable;
116950  p->pVTable = 0;
116951
116952  /* Assert that the mutex (if any) associated with the BtShared database
116953  ** that contains table p is held by the caller. See header comments
116954  ** above function sqlite3VtabUnlockList() for an explanation of why
116955  ** this makes it safe to access the sqlite3.pDisconnect list of any
116956  ** database connection that may have an entry in the p->pVTable list.
116957  */
116958  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
116959
116960  while( pVTable ){
116961    sqlite3 *db2 = pVTable->db;
116962    VTable *pNext = pVTable->pNext;
116963    assert( db2 );
116964    if( db2==db ){
116965      pRet = pVTable;
116966      p->pVTable = pRet;
116967      pRet->pNext = 0;
116968    }else{
116969      pVTable->pNext = db2->pDisconnect;
116970      db2->pDisconnect = pVTable;
116971    }
116972    pVTable = pNext;
116973  }
116974
116975  assert( !db || pRet );
116976  return pRet;
116977}
116978
116979/*
116980** Table *p is a virtual table. This function removes the VTable object
116981** for table *p associated with database connection db from the linked
116982** list in p->pVTab. It also decrements the VTable ref count. This is
116983** used when closing database connection db to free all of its VTable
116984** objects without disturbing the rest of the Schema object (which may
116985** be being used by other shared-cache connections).
116986*/
116987SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
116988  VTable **ppVTab;
116989
116990  assert( IsVirtual(p) );
116991  assert( sqlite3BtreeHoldsAllMutexes(db) );
116992  assert( sqlite3_mutex_held(db->mutex) );
116993
116994  for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
116995    if( (*ppVTab)->db==db  ){
116996      VTable *pVTab = *ppVTab;
116997      *ppVTab = pVTab->pNext;
116998      sqlite3VtabUnlock(pVTab);
116999      break;
117000    }
117001  }
117002}
117003
117004
117005/*
117006** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
117007**
117008** This function may only be called when the mutexes associated with all
117009** shared b-tree databases opened using connection db are held by the
117010** caller. This is done to protect the sqlite3.pDisconnect list. The
117011** sqlite3.pDisconnect list is accessed only as follows:
117012**
117013**   1) By this function. In this case, all BtShared mutexes and the mutex
117014**      associated with the database handle itself must be held.
117015**
117016**   2) By function vtabDisconnectAll(), when it adds a VTable entry to
117017**      the sqlite3.pDisconnect list. In this case either the BtShared mutex
117018**      associated with the database the virtual table is stored in is held
117019**      or, if the virtual table is stored in a non-sharable database, then
117020**      the database handle mutex is held.
117021**
117022** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
117023** by multiple threads. It is thread-safe.
117024*/
117025SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
117026  VTable *p = db->pDisconnect;
117027  db->pDisconnect = 0;
117028
117029  assert( sqlite3BtreeHoldsAllMutexes(db) );
117030  assert( sqlite3_mutex_held(db->mutex) );
117031
117032  if( p ){
117033    sqlite3ExpirePreparedStatements(db);
117034    do {
117035      VTable *pNext = p->pNext;
117036      sqlite3VtabUnlock(p);
117037      p = pNext;
117038    }while( p );
117039  }
117040}
117041
117042/*
117043** Clear any and all virtual-table information from the Table record.
117044** This routine is called, for example, just before deleting the Table
117045** record.
117046**
117047** Since it is a virtual-table, the Table structure contains a pointer
117048** to the head of a linked list of VTable structures. Each VTable
117049** structure is associated with a single sqlite3* user of the schema.
117050** The reference count of the VTable structure associated with database
117051** connection db is decremented immediately (which may lead to the
117052** structure being xDisconnected and free). Any other VTable structures
117053** in the list are moved to the sqlite3.pDisconnect list of the associated
117054** database connection.
117055*/
117056SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
117057  if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
117058  if( p->azModuleArg ){
117059    int i;
117060    for(i=0; i<p->nModuleArg; i++){
117061      if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
117062    }
117063    sqlite3DbFree(db, p->azModuleArg);
117064  }
117065}
117066
117067/*
117068** Add a new module argument to pTable->azModuleArg[].
117069** The string is not copied - the pointer is stored.  The
117070** string will be freed automatically when the table is
117071** deleted.
117072*/
117073static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
117074  int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
117075  char **azModuleArg;
117076  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
117077  if( azModuleArg==0 ){
117078    sqlite3DbFree(db, zArg);
117079  }else{
117080    int i = pTable->nModuleArg++;
117081    azModuleArg[i] = zArg;
117082    azModuleArg[i+1] = 0;
117083    pTable->azModuleArg = azModuleArg;
117084  }
117085}
117086
117087/*
117088** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
117089** statement.  The module name has been parsed, but the optional list
117090** of parameters that follow the module name are still pending.
117091*/
117092SQLITE_PRIVATE void sqlite3VtabBeginParse(
117093  Parse *pParse,        /* Parsing context */
117094  Token *pName1,        /* Name of new table, or database name */
117095  Token *pName2,        /* Name of new table or NULL */
117096  Token *pModuleName,   /* Name of the module for the virtual table */
117097  int ifNotExists       /* No error if the table already exists */
117098){
117099  int iDb;              /* The database the table is being created in */
117100  Table *pTable;        /* The new virtual table */
117101  sqlite3 *db;          /* Database connection */
117102
117103  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
117104  pTable = pParse->pNewTable;
117105  if( pTable==0 ) return;
117106  assert( 0==pTable->pIndex );
117107
117108  db = pParse->db;
117109  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
117110  assert( iDb>=0 );
117111
117112  pTable->tabFlags |= TF_Virtual;
117113  pTable->nModuleArg = 0;
117114  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
117115  addModuleArgument(db, pTable, 0);
117116  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
117117  assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
117118       || (pParse->sNameToken.z==pName1->z && pName2->z==0)
117119  );
117120  pParse->sNameToken.n = (int)(
117121      &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
117122  );
117123
117124#ifndef SQLITE_OMIT_AUTHORIZATION
117125  /* Creating a virtual table invokes the authorization callback twice.
117126  ** The first invocation, to obtain permission to INSERT a row into the
117127  ** sqlite_master table, has already been made by sqlite3StartTable().
117128  ** The second call, to obtain permission to create the table, is made now.
117129  */
117130  if( pTable->azModuleArg ){
117131    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
117132            pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
117133  }
117134#endif
117135}
117136
117137/*
117138** This routine takes the module argument that has been accumulating
117139** in pParse->zArg[] and appends it to the list of arguments on the
117140** virtual table currently under construction in pParse->pTable.
117141*/
117142static void addArgumentToVtab(Parse *pParse){
117143  if( pParse->sArg.z && pParse->pNewTable ){
117144    const char *z = (const char*)pParse->sArg.z;
117145    int n = pParse->sArg.n;
117146    sqlite3 *db = pParse->db;
117147    addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
117148  }
117149}
117150
117151/*
117152** The parser calls this routine after the CREATE VIRTUAL TABLE statement
117153** has been completely parsed.
117154*/
117155SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
117156  Table *pTab = pParse->pNewTable;  /* The table being constructed */
117157  sqlite3 *db = pParse->db;         /* The database connection */
117158
117159  if( pTab==0 ) return;
117160  addArgumentToVtab(pParse);
117161  pParse->sArg.z = 0;
117162  if( pTab->nModuleArg<1 ) return;
117163
117164  /* If the CREATE VIRTUAL TABLE statement is being entered for the
117165  ** first time (in other words if the virtual table is actually being
117166  ** created now instead of just being read out of sqlite_master) then
117167  ** do additional initialization work and store the statement text
117168  ** in the sqlite_master table.
117169  */
117170  if( !db->init.busy ){
117171    char *zStmt;
117172    char *zWhere;
117173    int iDb;
117174    int iReg;
117175    Vdbe *v;
117176
117177    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
117178    if( pEnd ){
117179      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
117180    }
117181    zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
117182
117183    /* A slot for the record has already been allocated in the
117184    ** SQLITE_MASTER table.  We just need to update that slot with all
117185    ** the information we've collected.
117186    **
117187    ** The VM register number pParse->regRowid holds the rowid of an
117188    ** entry in the sqlite_master table tht was created for this vtab
117189    ** by sqlite3StartTable().
117190    */
117191    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
117192    sqlite3NestedParse(pParse,
117193      "UPDATE %Q.%s "
117194         "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
117195       "WHERE rowid=#%d",
117196      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
117197      pTab->zName,
117198      pTab->zName,
117199      zStmt,
117200      pParse->regRowid
117201    );
117202    sqlite3DbFree(db, zStmt);
117203    v = sqlite3GetVdbe(pParse);
117204    sqlite3ChangeCookie(pParse, iDb);
117205
117206    sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
117207    zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
117208    sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
117209
117210    iReg = ++pParse->nMem;
117211    sqlite3VdbeLoadString(v, iReg, pTab->zName);
117212    sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
117213  }
117214
117215  /* If we are rereading the sqlite_master table create the in-memory
117216  ** record of the table. The xConnect() method is not called until
117217  ** the first time the virtual table is used in an SQL statement. This
117218  ** allows a schema that contains virtual tables to be loaded before
117219  ** the required virtual table implementations are registered.  */
117220  else {
117221    Table *pOld;
117222    Schema *pSchema = pTab->pSchema;
117223    const char *zName = pTab->zName;
117224    assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
117225    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
117226    if( pOld ){
117227      db->mallocFailed = 1;
117228      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
117229      return;
117230    }
117231    pParse->pNewTable = 0;
117232  }
117233}
117234
117235/*
117236** The parser calls this routine when it sees the first token
117237** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
117238*/
117239SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
117240  addArgumentToVtab(pParse);
117241  pParse->sArg.z = 0;
117242  pParse->sArg.n = 0;
117243}
117244
117245/*
117246** The parser calls this routine for each token after the first token
117247** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
117248*/
117249SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
117250  Token *pArg = &pParse->sArg;
117251  if( pArg->z==0 ){
117252    pArg->z = p->z;
117253    pArg->n = p->n;
117254  }else{
117255    assert(pArg->z <= p->z);
117256    pArg->n = (int)(&p->z[p->n] - pArg->z);
117257  }
117258}
117259
117260/*
117261** Invoke a virtual table constructor (either xCreate or xConnect). The
117262** pointer to the function to invoke is passed as the fourth parameter
117263** to this procedure.
117264*/
117265static int vtabCallConstructor(
117266  sqlite3 *db,
117267  Table *pTab,
117268  Module *pMod,
117269  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
117270  char **pzErr
117271){
117272  VtabCtx sCtx;
117273  VTable *pVTable;
117274  int rc;
117275  const char *const*azArg = (const char *const*)pTab->azModuleArg;
117276  int nArg = pTab->nModuleArg;
117277  char *zErr = 0;
117278  char *zModuleName;
117279  int iDb;
117280  VtabCtx *pCtx;
117281
117282  /* Check that the virtual-table is not already being initialized */
117283  for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
117284    if( pCtx->pTab==pTab ){
117285      *pzErr = sqlite3MPrintf(db,
117286          "vtable constructor called recursively: %s", pTab->zName
117287      );
117288      return SQLITE_LOCKED;
117289    }
117290  }
117291
117292  zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
117293  if( !zModuleName ){
117294    return SQLITE_NOMEM;
117295  }
117296
117297  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
117298  if( !pVTable ){
117299    sqlite3DbFree(db, zModuleName);
117300    return SQLITE_NOMEM;
117301  }
117302  pVTable->db = db;
117303  pVTable->pMod = pMod;
117304
117305  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
117306  pTab->azModuleArg[1] = db->aDb[iDb].zName;
117307
117308  /* Invoke the virtual table constructor */
117309  assert( &db->pVtabCtx );
117310  assert( xConstruct );
117311  sCtx.pTab = pTab;
117312  sCtx.pVTable = pVTable;
117313  sCtx.pPrior = db->pVtabCtx;
117314  sCtx.bDeclared = 0;
117315  db->pVtabCtx = &sCtx;
117316  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
117317  db->pVtabCtx = sCtx.pPrior;
117318  if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
117319  assert( sCtx.pTab==pTab );
117320
117321  if( SQLITE_OK!=rc ){
117322    if( zErr==0 ){
117323      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
117324    }else {
117325      *pzErr = sqlite3MPrintf(db, "%s", zErr);
117326      sqlite3_free(zErr);
117327    }
117328    sqlite3DbFree(db, pVTable);
117329  }else if( ALWAYS(pVTable->pVtab) ){
117330    /* Justification of ALWAYS():  A correct vtab constructor must allocate
117331    ** the sqlite3_vtab object if successful.  */
117332    memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
117333    pVTable->pVtab->pModule = pMod->pModule;
117334    pVTable->nRef = 1;
117335    if( sCtx.bDeclared==0 ){
117336      const char *zFormat = "vtable constructor did not declare schema: %s";
117337      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
117338      sqlite3VtabUnlock(pVTable);
117339      rc = SQLITE_ERROR;
117340    }else{
117341      int iCol;
117342      u8 oooHidden = 0;
117343      /* If everything went according to plan, link the new VTable structure
117344      ** into the linked list headed by pTab->pVTable. Then loop through the
117345      ** columns of the table to see if any of them contain the token "hidden".
117346      ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
117347      ** the type string.  */
117348      pVTable->pNext = pTab->pVTable;
117349      pTab->pVTable = pVTable;
117350
117351      for(iCol=0; iCol<pTab->nCol; iCol++){
117352        char *zType = pTab->aCol[iCol].zType;
117353        int nType;
117354        int i = 0;
117355        if( !zType ){
117356          pTab->tabFlags |= oooHidden;
117357          continue;
117358        }
117359        nType = sqlite3Strlen30(zType);
117360        if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
117361          for(i=0; i<nType; i++){
117362            if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
117363             && (zType[i+7]=='\0' || zType[i+7]==' ')
117364            ){
117365              i++;
117366              break;
117367            }
117368          }
117369        }
117370        if( i<nType ){
117371          int j;
117372          int nDel = 6 + (zType[i+6] ? 1 : 0);
117373          for(j=i; (j+nDel)<=nType; j++){
117374            zType[j] = zType[j+nDel];
117375          }
117376          if( zType[i]=='\0' && i>0 ){
117377            assert(zType[i-1]==' ');
117378            zType[i-1] = '\0';
117379          }
117380          pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
117381          oooHidden = TF_OOOHidden;
117382        }else{
117383          pTab->tabFlags |= oooHidden;
117384        }
117385      }
117386    }
117387  }
117388
117389  sqlite3DbFree(db, zModuleName);
117390  return rc;
117391}
117392
117393/*
117394** This function is invoked by the parser to call the xConnect() method
117395** of the virtual table pTab. If an error occurs, an error code is returned
117396** and an error left in pParse.
117397**
117398** This call is a no-op if table pTab is not a virtual table.
117399*/
117400SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
117401  sqlite3 *db = pParse->db;
117402  const char *zMod;
117403  Module *pMod;
117404  int rc;
117405
117406  assert( pTab );
117407  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
117408    return SQLITE_OK;
117409  }
117410
117411  /* Locate the required virtual table module */
117412  zMod = pTab->azModuleArg[0];
117413  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
117414
117415  if( !pMod ){
117416    const char *zModule = pTab->azModuleArg[0];
117417    sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
117418    rc = SQLITE_ERROR;
117419  }else{
117420    char *zErr = 0;
117421    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
117422    if( rc!=SQLITE_OK ){
117423      sqlite3ErrorMsg(pParse, "%s", zErr);
117424    }
117425    sqlite3DbFree(db, zErr);
117426  }
117427
117428  return rc;
117429}
117430/*
117431** Grow the db->aVTrans[] array so that there is room for at least one
117432** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
117433*/
117434static int growVTrans(sqlite3 *db){
117435  const int ARRAY_INCR = 5;
117436
117437  /* Grow the sqlite3.aVTrans array if required */
117438  if( (db->nVTrans%ARRAY_INCR)==0 ){
117439    VTable **aVTrans;
117440    int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
117441    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
117442    if( !aVTrans ){
117443      return SQLITE_NOMEM;
117444    }
117445    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
117446    db->aVTrans = aVTrans;
117447  }
117448
117449  return SQLITE_OK;
117450}
117451
117452/*
117453** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
117454** have already been reserved using growVTrans().
117455*/
117456static void addToVTrans(sqlite3 *db, VTable *pVTab){
117457  /* Add pVtab to the end of sqlite3.aVTrans */
117458  db->aVTrans[db->nVTrans++] = pVTab;
117459  sqlite3VtabLock(pVTab);
117460}
117461
117462/*
117463** This function is invoked by the vdbe to call the xCreate method
117464** of the virtual table named zTab in database iDb.
117465**
117466** If an error occurs, *pzErr is set to point an an English language
117467** description of the error and an SQLITE_XXX error code is returned.
117468** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
117469*/
117470SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
117471  int rc = SQLITE_OK;
117472  Table *pTab;
117473  Module *pMod;
117474  const char *zMod;
117475
117476  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
117477  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
117478
117479  /* Locate the required virtual table module */
117480  zMod = pTab->azModuleArg[0];
117481  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
117482
117483  /* If the module has been registered and includes a Create method,
117484  ** invoke it now. If the module has not been registered, return an
117485  ** error. Otherwise, do nothing.
117486  */
117487  if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
117488    *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
117489    rc = SQLITE_ERROR;
117490  }else{
117491    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
117492  }
117493
117494  /* Justification of ALWAYS():  The xConstructor method is required to
117495  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
117496  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
117497    rc = growVTrans(db);
117498    if( rc==SQLITE_OK ){
117499      addToVTrans(db, sqlite3GetVTable(db, pTab));
117500    }
117501  }
117502
117503  return rc;
117504}
117505
117506/*
117507** This function is used to set the schema of a virtual table.  It is only
117508** valid to call this function from within the xCreate() or xConnect() of a
117509** virtual table module.
117510*/
117511SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
117512  VtabCtx *pCtx;
117513  Parse *pParse;
117514  int rc = SQLITE_OK;
117515  Table *pTab;
117516  char *zErr = 0;
117517
117518#ifdef SQLITE_ENABLE_API_ARMOR
117519  if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
117520    return SQLITE_MISUSE_BKPT;
117521  }
117522#endif
117523  sqlite3_mutex_enter(db->mutex);
117524  pCtx = db->pVtabCtx;
117525  if( !pCtx || pCtx->bDeclared ){
117526    sqlite3Error(db, SQLITE_MISUSE);
117527    sqlite3_mutex_leave(db->mutex);
117528    return SQLITE_MISUSE_BKPT;
117529  }
117530  pTab = pCtx->pTab;
117531  assert( (pTab->tabFlags & TF_Virtual)!=0 );
117532
117533  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
117534  if( pParse==0 ){
117535    rc = SQLITE_NOMEM;
117536  }else{
117537    pParse->declareVtab = 1;
117538    pParse->db = db;
117539    pParse->nQueryLoop = 1;
117540
117541    if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
117542     && pParse->pNewTable
117543     && !db->mallocFailed
117544     && !pParse->pNewTable->pSelect
117545     && (pParse->pNewTable->tabFlags & TF_Virtual)==0
117546    ){
117547      if( !pTab->aCol ){
117548        pTab->aCol = pParse->pNewTable->aCol;
117549        pTab->nCol = pParse->pNewTable->nCol;
117550        pParse->pNewTable->nCol = 0;
117551        pParse->pNewTable->aCol = 0;
117552      }
117553      pCtx->bDeclared = 1;
117554    }else{
117555      sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
117556      sqlite3DbFree(db, zErr);
117557      rc = SQLITE_ERROR;
117558    }
117559    pParse->declareVtab = 0;
117560
117561    if( pParse->pVdbe ){
117562      sqlite3VdbeFinalize(pParse->pVdbe);
117563    }
117564    sqlite3DeleteTable(db, pParse->pNewTable);
117565    sqlite3ParserReset(pParse);
117566    sqlite3StackFree(db, pParse);
117567  }
117568
117569  assert( (rc&0xff)==rc );
117570  rc = sqlite3ApiExit(db, rc);
117571  sqlite3_mutex_leave(db->mutex);
117572  return rc;
117573}
117574
117575/*
117576** This function is invoked by the vdbe to call the xDestroy method
117577** of the virtual table named zTab in database iDb. This occurs
117578** when a DROP TABLE is mentioned.
117579**
117580** This call is a no-op if zTab is not a virtual table.
117581*/
117582SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
117583  int rc = SQLITE_OK;
117584  Table *pTab;
117585
117586  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
117587  if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
117588    VTable *p;
117589    int (*xDestroy)(sqlite3_vtab *);
117590    for(p=pTab->pVTable; p; p=p->pNext){
117591      assert( p->pVtab );
117592      if( p->pVtab->nRef>0 ){
117593        return SQLITE_LOCKED;
117594      }
117595    }
117596    p = vtabDisconnectAll(db, pTab);
117597    xDestroy = p->pMod->pModule->xDestroy;
117598    assert( xDestroy!=0 );  /* Checked before the virtual table is created */
117599    rc = xDestroy(p->pVtab);
117600    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
117601    if( rc==SQLITE_OK ){
117602      assert( pTab->pVTable==p && p->pNext==0 );
117603      p->pVtab = 0;
117604      pTab->pVTable = 0;
117605      sqlite3VtabUnlock(p);
117606    }
117607  }
117608
117609  return rc;
117610}
117611
117612/*
117613** This function invokes either the xRollback or xCommit method
117614** of each of the virtual tables in the sqlite3.aVTrans array. The method
117615** called is identified by the second argument, "offset", which is
117616** the offset of the method to call in the sqlite3_module structure.
117617**
117618** The array is cleared after invoking the callbacks.
117619*/
117620static void callFinaliser(sqlite3 *db, int offset){
117621  int i;
117622  if( db->aVTrans ){
117623    VTable **aVTrans = db->aVTrans;
117624    db->aVTrans = 0;
117625    for(i=0; i<db->nVTrans; i++){
117626      VTable *pVTab = aVTrans[i];
117627      sqlite3_vtab *p = pVTab->pVtab;
117628      if( p ){
117629        int (*x)(sqlite3_vtab *);
117630        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
117631        if( x ) x(p);
117632      }
117633      pVTab->iSavepoint = 0;
117634      sqlite3VtabUnlock(pVTab);
117635    }
117636    sqlite3DbFree(db, aVTrans);
117637    db->nVTrans = 0;
117638  }
117639}
117640
117641/*
117642** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
117643** array. Return the error code for the first error that occurs, or
117644** SQLITE_OK if all xSync operations are successful.
117645**
117646** If an error message is available, leave it in p->zErrMsg.
117647*/
117648SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
117649  int i;
117650  int rc = SQLITE_OK;
117651  VTable **aVTrans = db->aVTrans;
117652
117653  db->aVTrans = 0;
117654  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
117655    int (*x)(sqlite3_vtab *);
117656    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
117657    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
117658      rc = x(pVtab);
117659      sqlite3VtabImportErrmsg(p, pVtab);
117660    }
117661  }
117662  db->aVTrans = aVTrans;
117663  return rc;
117664}
117665
117666/*
117667** Invoke the xRollback method of all virtual tables in the
117668** sqlite3.aVTrans array. Then clear the array itself.
117669*/
117670SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
117671  callFinaliser(db, offsetof(sqlite3_module,xRollback));
117672  return SQLITE_OK;
117673}
117674
117675/*
117676** Invoke the xCommit method of all virtual tables in the
117677** sqlite3.aVTrans array. Then clear the array itself.
117678*/
117679SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
117680  callFinaliser(db, offsetof(sqlite3_module,xCommit));
117681  return SQLITE_OK;
117682}
117683
117684/*
117685** If the virtual table pVtab supports the transaction interface
117686** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
117687** not currently open, invoke the xBegin method now.
117688**
117689** If the xBegin call is successful, place the sqlite3_vtab pointer
117690** in the sqlite3.aVTrans array.
117691*/
117692SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
117693  int rc = SQLITE_OK;
117694  const sqlite3_module *pModule;
117695
117696  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
117697  ** than zero, then this function is being called from within a
117698  ** virtual module xSync() callback. It is illegal to write to
117699  ** virtual module tables in this case, so return SQLITE_LOCKED.
117700  */
117701  if( sqlite3VtabInSync(db) ){
117702    return SQLITE_LOCKED;
117703  }
117704  if( !pVTab ){
117705    return SQLITE_OK;
117706  }
117707  pModule = pVTab->pVtab->pModule;
117708
117709  if( pModule->xBegin ){
117710    int i;
117711
117712    /* If pVtab is already in the aVTrans array, return early */
117713    for(i=0; i<db->nVTrans; i++){
117714      if( db->aVTrans[i]==pVTab ){
117715        return SQLITE_OK;
117716      }
117717    }
117718
117719    /* Invoke the xBegin method. If successful, add the vtab to the
117720    ** sqlite3.aVTrans[] array. */
117721    rc = growVTrans(db);
117722    if( rc==SQLITE_OK ){
117723      rc = pModule->xBegin(pVTab->pVtab);
117724      if( rc==SQLITE_OK ){
117725        int iSvpt = db->nStatement + db->nSavepoint;
117726        addToVTrans(db, pVTab);
117727        if( iSvpt ) rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, iSvpt-1);
117728      }
117729    }
117730  }
117731  return rc;
117732}
117733
117734/*
117735** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
117736** virtual tables that currently have an open transaction. Pass iSavepoint
117737** as the second argument to the virtual table method invoked.
117738**
117739** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
117740** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
117741** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
117742** an open transaction is invoked.
117743**
117744** If any virtual table method returns an error code other than SQLITE_OK,
117745** processing is abandoned and the error returned to the caller of this
117746** function immediately. If all calls to virtual table methods are successful,
117747** SQLITE_OK is returned.
117748*/
117749SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
117750  int rc = SQLITE_OK;
117751
117752  assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
117753  assert( iSavepoint>=-1 );
117754  if( db->aVTrans ){
117755    int i;
117756    for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
117757      VTable *pVTab = db->aVTrans[i];
117758      const sqlite3_module *pMod = pVTab->pMod->pModule;
117759      if( pVTab->pVtab && pMod->iVersion>=2 ){
117760        int (*xMethod)(sqlite3_vtab *, int);
117761        switch( op ){
117762          case SAVEPOINT_BEGIN:
117763            xMethod = pMod->xSavepoint;
117764            pVTab->iSavepoint = iSavepoint+1;
117765            break;
117766          case SAVEPOINT_ROLLBACK:
117767            xMethod = pMod->xRollbackTo;
117768            break;
117769          default:
117770            xMethod = pMod->xRelease;
117771            break;
117772        }
117773        if( xMethod && pVTab->iSavepoint>iSavepoint ){
117774          rc = xMethod(pVTab->pVtab, iSavepoint);
117775        }
117776      }
117777    }
117778  }
117779  return rc;
117780}
117781
117782/*
117783** The first parameter (pDef) is a function implementation.  The
117784** second parameter (pExpr) is the first argument to this function.
117785** If pExpr is a column in a virtual table, then let the virtual
117786** table implementation have an opportunity to overload the function.
117787**
117788** This routine is used to allow virtual table implementations to
117789** overload MATCH, LIKE, GLOB, and REGEXP operators.
117790**
117791** Return either the pDef argument (indicating no change) or a
117792** new FuncDef structure that is marked as ephemeral using the
117793** SQLITE_FUNC_EPHEM flag.
117794*/
117795SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
117796  sqlite3 *db,    /* Database connection for reporting malloc problems */
117797  FuncDef *pDef,  /* Function to possibly overload */
117798  int nArg,       /* Number of arguments to the function */
117799  Expr *pExpr     /* First argument to the function */
117800){
117801  Table *pTab;
117802  sqlite3_vtab *pVtab;
117803  sqlite3_module *pMod;
117804  void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
117805  void *pArg = 0;
117806  FuncDef *pNew;
117807  int rc = 0;
117808  char *zLowerName;
117809  unsigned char *z;
117810
117811
117812  /* Check to see the left operand is a column in a virtual table */
117813  if( NEVER(pExpr==0) ) return pDef;
117814  if( pExpr->op!=TK_COLUMN ) return pDef;
117815  pTab = pExpr->pTab;
117816  if( NEVER(pTab==0) ) return pDef;
117817  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
117818  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
117819  assert( pVtab!=0 );
117820  assert( pVtab->pModule!=0 );
117821  pMod = (sqlite3_module *)pVtab->pModule;
117822  if( pMod->xFindFunction==0 ) return pDef;
117823
117824  /* Call the xFindFunction method on the virtual table implementation
117825  ** to see if the implementation wants to overload this function
117826  */
117827  zLowerName = sqlite3DbStrDup(db, pDef->zName);
117828  if( zLowerName ){
117829    for(z=(unsigned char*)zLowerName; *z; z++){
117830      *z = sqlite3UpperToLower[*z];
117831    }
117832    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
117833    sqlite3DbFree(db, zLowerName);
117834  }
117835  if( rc==0 ){
117836    return pDef;
117837  }
117838
117839  /* Create a new ephemeral function definition for the overloaded
117840  ** function */
117841  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
117842                             + sqlite3Strlen30(pDef->zName) + 1);
117843  if( pNew==0 ){
117844    return pDef;
117845  }
117846  *pNew = *pDef;
117847  pNew->zName = (char *)&pNew[1];
117848  memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
117849  pNew->xFunc = xFunc;
117850  pNew->pUserData = pArg;
117851  pNew->funcFlags |= SQLITE_FUNC_EPHEM;
117852  return pNew;
117853}
117854
117855/*
117856** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
117857** array so that an OP_VBegin will get generated for it.  Add pTab to the
117858** array if it is missing.  If pTab is already in the array, this routine
117859** is a no-op.
117860*/
117861SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
117862  Parse *pToplevel = sqlite3ParseToplevel(pParse);
117863  int i, n;
117864  Table **apVtabLock;
117865
117866  assert( IsVirtual(pTab) );
117867  for(i=0; i<pToplevel->nVtabLock; i++){
117868    if( pTab==pToplevel->apVtabLock[i] ) return;
117869  }
117870  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
117871  apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
117872  if( apVtabLock ){
117873    pToplevel->apVtabLock = apVtabLock;
117874    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
117875  }else{
117876    pToplevel->db->mallocFailed = 1;
117877  }
117878}
117879
117880/*
117881** Check to see if virtual tale module pMod can be have an eponymous
117882** virtual table instance.  If it can, create one if one does not already
117883** exist. Return non-zero if the eponymous virtual table instance exists
117884** when this routine returns, and return zero if it does not exist.
117885**
117886** An eponymous virtual table instance is one that is named after its
117887** module, and more importantly, does not require a CREATE VIRTUAL TABLE
117888** statement in order to come into existance.  Eponymous virtual table
117889** instances always exist.  They cannot be DROP-ed.
117890**
117891** Any virtual table module for which xConnect and xCreate are the same
117892** method can have an eponymous virtual table instance.
117893*/
117894SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
117895  const sqlite3_module *pModule = pMod->pModule;
117896  Table *pTab;
117897  char *zErr = 0;
117898  int nName;
117899  int rc;
117900  sqlite3 *db = pParse->db;
117901  if( pMod->pEpoTab ) return 1;
117902  if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
117903  nName = sqlite3Strlen30(pMod->zName) + 1;
117904  pTab = sqlite3DbMallocZero(db, sizeof(Table) + nName);
117905  if( pTab==0 ) return 0;
117906  pMod->pEpoTab = pTab;
117907  pTab->zName = (char*)&pTab[1];
117908  memcpy(pTab->zName, pMod->zName, nName);
117909  pTab->nRef = 1;
117910  pTab->pSchema = db->aDb[0].pSchema;
117911  pTab->tabFlags |= TF_Virtual;
117912  pTab->nModuleArg = 0;
117913  pTab->iPKey = -1;
117914  addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
117915  addModuleArgument(db, pTab, 0);
117916  addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
117917  rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
117918  if( rc ){
117919    sqlite3ErrorMsg(pParse, "%s", zErr);
117920    sqlite3DbFree(db, zErr);
117921    sqlite3VtabEponymousTableClear(db, pMod);
117922    return 0;
117923  }
117924  return 1;
117925}
117926
117927/*
117928** Erase the eponymous virtual table instance associated with
117929** virtual table module pMod, if it exists.
117930*/
117931SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
117932  Table *pTab = pMod->pEpoTab;
117933  if( pTab!=0 ){
117934    sqlite3DeleteColumnNames(db, pTab);
117935    sqlite3VtabClear(db, pTab);
117936    sqlite3DbFree(db, pTab);
117937    pMod->pEpoTab = 0;
117938  }
117939}
117940
117941/*
117942** Return the ON CONFLICT resolution mode in effect for the virtual
117943** table update operation currently in progress.
117944**
117945** The results of this routine are undefined unless it is called from
117946** within an xUpdate method.
117947*/
117948SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *db){
117949  static const unsigned char aMap[] = {
117950    SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
117951  };
117952#ifdef SQLITE_ENABLE_API_ARMOR
117953  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
117954#endif
117955  assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
117956  assert( OE_Ignore==4 && OE_Replace==5 );
117957  assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
117958  return (int)aMap[db->vtabOnConflict-1];
117959}
117960
117961/*
117962** Call from within the xCreate() or xConnect() methods to provide
117963** the SQLite core with additional information about the behavior
117964** of the virtual table being implemented.
117965*/
117966SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3 *db, int op, ...){
117967  va_list ap;
117968  int rc = SQLITE_OK;
117969
117970#ifdef SQLITE_ENABLE_API_ARMOR
117971  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
117972#endif
117973  sqlite3_mutex_enter(db->mutex);
117974  va_start(ap, op);
117975  switch( op ){
117976    case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
117977      VtabCtx *p = db->pVtabCtx;
117978      if( !p ){
117979        rc = SQLITE_MISUSE_BKPT;
117980      }else{
117981        assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
117982        p->pVTable->bConstraint = (u8)va_arg(ap, int);
117983      }
117984      break;
117985    }
117986    default:
117987      rc = SQLITE_MISUSE_BKPT;
117988      break;
117989  }
117990  va_end(ap);
117991
117992  if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
117993  sqlite3_mutex_leave(db->mutex);
117994  return rc;
117995}
117996
117997#endif /* SQLITE_OMIT_VIRTUALTABLE */
117998
117999/************** End of vtab.c ************************************************/
118000/************** Begin file wherecode.c ***************************************/
118001/*
118002** 2015-06-06
118003**
118004** The author disclaims copyright to this source code.  In place of
118005** a legal notice, here is a blessing:
118006**
118007**    May you do good and not evil.
118008**    May you find forgiveness for yourself and forgive others.
118009**    May you share freely, never taking more than you give.
118010**
118011*************************************************************************
118012** This module contains C code that generates VDBE code used to process
118013** the WHERE clause of SQL statements.
118014**
118015** This file was split off from where.c on 2015-06-06 in order to reduce the
118016** size of where.c and make it easier to edit.  This file contains the routines
118017** that actually generate the bulk of the WHERE loop code.  The original where.c
118018** file retains the code that does query planning and analysis.
118019*/
118020/* #include "sqliteInt.h" */
118021/************** Include whereInt.h in the middle of wherecode.c **************/
118022/************** Begin file whereInt.h ****************************************/
118023/*
118024** 2013-11-12
118025**
118026** The author disclaims copyright to this source code.  In place of
118027** a legal notice, here is a blessing:
118028**
118029**    May you do good and not evil.
118030**    May you find forgiveness for yourself and forgive others.
118031**    May you share freely, never taking more than you give.
118032**
118033*************************************************************************
118034**
118035** This file contains structure and macro definitions for the query
118036** planner logic in "where.c".  These definitions are broken out into
118037** a separate source file for easier editing.
118038*/
118039
118040/*
118041** Trace output macros
118042*/
118043#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
118044/***/ int sqlite3WhereTrace;
118045#endif
118046#if defined(SQLITE_DEBUG) \
118047    && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
118048# define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
118049# define WHERETRACE_ENABLED 1
118050#else
118051# define WHERETRACE(K,X)
118052#endif
118053
118054/* Forward references
118055*/
118056typedef struct WhereClause WhereClause;
118057typedef struct WhereMaskSet WhereMaskSet;
118058typedef struct WhereOrInfo WhereOrInfo;
118059typedef struct WhereAndInfo WhereAndInfo;
118060typedef struct WhereLevel WhereLevel;
118061typedef struct WhereLoop WhereLoop;
118062typedef struct WherePath WherePath;
118063typedef struct WhereTerm WhereTerm;
118064typedef struct WhereLoopBuilder WhereLoopBuilder;
118065typedef struct WhereScan WhereScan;
118066typedef struct WhereOrCost WhereOrCost;
118067typedef struct WhereOrSet WhereOrSet;
118068
118069/*
118070** This object contains information needed to implement a single nested
118071** loop in WHERE clause.
118072**
118073** Contrast this object with WhereLoop.  This object describes the
118074** implementation of the loop.  WhereLoop describes the algorithm.
118075** This object contains a pointer to the WhereLoop algorithm as one of
118076** its elements.
118077**
118078** The WhereInfo object contains a single instance of this object for
118079** each term in the FROM clause (which is to say, for each of the
118080** nested loops as implemented).  The order of WhereLevel objects determines
118081** the loop nested order, with WhereInfo.a[0] being the outer loop and
118082** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
118083*/
118084struct WhereLevel {
118085  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
118086  int iTabCur;          /* The VDBE cursor used to access the table */
118087  int iIdxCur;          /* The VDBE cursor used to access pIdx */
118088  int addrBrk;          /* Jump here to break out of the loop */
118089  int addrNxt;          /* Jump here to start the next IN combination */
118090  int addrSkip;         /* Jump here for next iteration of skip-scan */
118091  int addrCont;         /* Jump here to continue with the next loop cycle */
118092  int addrFirst;        /* First instruction of interior of the loop */
118093  int addrBody;         /* Beginning of the body of this loop */
118094  int iLikeRepCntr;     /* LIKE range processing counter register */
118095  int addrLikeRep;      /* LIKE range processing address */
118096  u8 iFrom;             /* Which entry in the FROM clause */
118097  u8 op, p3, p5;        /* Opcode, P3 & P5 of the opcode that ends the loop */
118098  int p1, p2;           /* Operands of the opcode used to ends the loop */
118099  union {               /* Information that depends on pWLoop->wsFlags */
118100    struct {
118101      int nIn;              /* Number of entries in aInLoop[] */
118102      struct InLoop {
118103        int iCur;              /* The VDBE cursor used by this IN operator */
118104        int addrInTop;         /* Top of the IN loop */
118105        u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
118106      } *aInLoop;           /* Information about each nested IN operator */
118107    } in;                 /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
118108    Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
118109  } u;
118110  struct WhereLoop *pWLoop;  /* The selected WhereLoop object */
118111  Bitmask notReady;          /* FROM entries not usable at this level */
118112#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
118113  int addrVisit;        /* Address at which row is visited */
118114#endif
118115};
118116
118117/*
118118** Each instance of this object represents an algorithm for evaluating one
118119** term of a join.  Every term of the FROM clause will have at least
118120** one corresponding WhereLoop object (unless INDEXED BY constraints
118121** prevent a query solution - which is an error) and many terms of the
118122** FROM clause will have multiple WhereLoop objects, each describing a
118123** potential way of implementing that FROM-clause term, together with
118124** dependencies and cost estimates for using the chosen algorithm.
118125**
118126** Query planning consists of building up a collection of these WhereLoop
118127** objects, then computing a particular sequence of WhereLoop objects, with
118128** one WhereLoop object per FROM clause term, that satisfy all dependencies
118129** and that minimize the overall cost.
118130*/
118131struct WhereLoop {
118132  Bitmask prereq;       /* Bitmask of other loops that must run first */
118133  Bitmask maskSelf;     /* Bitmask identifying table iTab */
118134#ifdef SQLITE_DEBUG
118135  char cId;             /* Symbolic ID of this loop for debugging use */
118136#endif
118137  u8 iTab;              /* Position in FROM clause of table for this loop */
118138  u8 iSortIdx;          /* Sorting index number.  0==None */
118139  LogEst rSetup;        /* One-time setup cost (ex: create transient index) */
118140  LogEst rRun;          /* Cost of running each loop */
118141  LogEst nOut;          /* Estimated number of output rows */
118142  union {
118143    struct {               /* Information for internal btree tables */
118144      u16 nEq;               /* Number of equality constraints */
118145      Index *pIndex;         /* Index used, or NULL */
118146    } btree;
118147    struct {               /* Information for virtual tables */
118148      int idxNum;            /* Index number */
118149      u8 needFree;           /* True if sqlite3_free(idxStr) is needed */
118150      i8 isOrdered;          /* True if satisfies ORDER BY */
118151      u16 omitMask;          /* Terms that may be omitted */
118152      char *idxStr;          /* Index identifier string */
118153    } vtab;
118154  } u;
118155  u32 wsFlags;          /* WHERE_* flags describing the plan */
118156  u16 nLTerm;           /* Number of entries in aLTerm[] */
118157  u16 nSkip;            /* Number of NULL aLTerm[] entries */
118158  /**** whereLoopXfer() copies fields above ***********************/
118159# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
118160  u16 nLSlot;           /* Number of slots allocated for aLTerm[] */
118161  WhereTerm **aLTerm;   /* WhereTerms used */
118162  WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
118163  WhereTerm *aLTermSpace[3];  /* Initial aLTerm[] space */
118164};
118165
118166/* This object holds the prerequisites and the cost of running a
118167** subquery on one operand of an OR operator in the WHERE clause.
118168** See WhereOrSet for additional information
118169*/
118170struct WhereOrCost {
118171  Bitmask prereq;     /* Prerequisites */
118172  LogEst rRun;        /* Cost of running this subquery */
118173  LogEst nOut;        /* Number of outputs for this subquery */
118174};
118175
118176/* The WhereOrSet object holds a set of possible WhereOrCosts that
118177** correspond to the subquery(s) of OR-clause processing.  Only the
118178** best N_OR_COST elements are retained.
118179*/
118180#define N_OR_COST 3
118181struct WhereOrSet {
118182  u16 n;                      /* Number of valid a[] entries */
118183  WhereOrCost a[N_OR_COST];   /* Set of best costs */
118184};
118185
118186/*
118187** Each instance of this object holds a sequence of WhereLoop objects
118188** that implement some or all of a query plan.
118189**
118190** Think of each WhereLoop object as a node in a graph with arcs
118191** showing dependencies and costs for travelling between nodes.  (That is
118192** not a completely accurate description because WhereLoop costs are a
118193** vector, not a scalar, and because dependencies are many-to-one, not
118194** one-to-one as are graph nodes.  But it is a useful visualization aid.)
118195** Then a WherePath object is a path through the graph that visits some
118196** or all of the WhereLoop objects once.
118197**
118198** The "solver" works by creating the N best WherePath objects of length
118199** 1.  Then using those as a basis to compute the N best WherePath objects
118200** of length 2.  And so forth until the length of WherePaths equals the
118201** number of nodes in the FROM clause.  The best (lowest cost) WherePath
118202** at the end is the chosen query plan.
118203*/
118204struct WherePath {
118205  Bitmask maskLoop;     /* Bitmask of all WhereLoop objects in this path */
118206  Bitmask revLoop;      /* aLoop[]s that should be reversed for ORDER BY */
118207  LogEst nRow;          /* Estimated number of rows generated by this path */
118208  LogEst rCost;         /* Total cost of this path */
118209  LogEst rUnsorted;     /* Total cost of this path ignoring sorting costs */
118210  i8 isOrdered;         /* No. of ORDER BY terms satisfied. -1 for unknown */
118211  WhereLoop **aLoop;    /* Array of WhereLoop objects implementing this path */
118212};
118213
118214/*
118215** The query generator uses an array of instances of this structure to
118216** help it analyze the subexpressions of the WHERE clause.  Each WHERE
118217** clause subexpression is separated from the others by AND operators,
118218** usually, or sometimes subexpressions separated by OR.
118219**
118220** All WhereTerms are collected into a single WhereClause structure.
118221** The following identity holds:
118222**
118223**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
118224**
118225** When a term is of the form:
118226**
118227**              X <op> <expr>
118228**
118229** where X is a column name and <op> is one of certain operators,
118230** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
118231** cursor number and column number for X.  WhereTerm.eOperator records
118232** the <op> using a bitmask encoding defined by WO_xxx below.  The
118233** use of a bitmask encoding for the operator allows us to search
118234** quickly for terms that match any of several different operators.
118235**
118236** A WhereTerm might also be two or more subterms connected by OR:
118237**
118238**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
118239**
118240** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
118241** and the WhereTerm.u.pOrInfo field points to auxiliary information that
118242** is collected about the OR clause.
118243**
118244** If a term in the WHERE clause does not match either of the two previous
118245** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
118246** to the original subexpression content and wtFlags is set up appropriately
118247** but no other fields in the WhereTerm object are meaningful.
118248**
118249** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
118250** but they do so indirectly.  A single WhereMaskSet structure translates
118251** cursor number into bits and the translated bit is stored in the prereq
118252** fields.  The translation is used in order to maximize the number of
118253** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
118254** spread out over the non-negative integers.  For example, the cursor
118255** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
118256** translates these sparse cursor numbers into consecutive integers
118257** beginning with 0 in order to make the best possible use of the available
118258** bits in the Bitmask.  So, in the example above, the cursor numbers
118259** would be mapped into integers 0 through 7.
118260**
118261** The number of terms in a join is limited by the number of bits
118262** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
118263** is only able to process joins with 64 or fewer tables.
118264*/
118265struct WhereTerm {
118266  Expr *pExpr;            /* Pointer to the subexpression that is this term */
118267  int iParent;            /* Disable pWC->a[iParent] when this term disabled */
118268  int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
118269  union {
118270    int leftColumn;         /* Column number of X in "X <op> <expr>" */
118271    WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
118272    WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
118273  } u;
118274  LogEst truthProb;       /* Probability of truth for this expression */
118275  u16 eOperator;          /* A WO_xx value describing <op> */
118276  u16 wtFlags;            /* TERM_xxx bit flags.  See below */
118277  u8 nChild;              /* Number of children that must disable us */
118278  WhereClause *pWC;       /* The clause this term is part of */
118279  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
118280  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
118281};
118282
118283/*
118284** Allowed values of WhereTerm.wtFlags
118285*/
118286#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
118287#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
118288#define TERM_CODED      0x04   /* This term is already coded */
118289#define TERM_COPIED     0x08   /* Has a child */
118290#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
118291#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
118292#define TERM_OR_OK      0x40   /* Used during OR-clause processing */
118293#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118294#  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
118295#else
118296#  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
118297#endif
118298#define TERM_LIKEOPT    0x100  /* Virtual terms from the LIKE optimization */
118299#define TERM_LIKECOND   0x200  /* Conditionally this LIKE operator term */
118300#define TERM_LIKE       0x400  /* The original LIKE operator */
118301#define TERM_IS         0x800  /* Term.pExpr is an IS operator */
118302
118303/*
118304** An instance of the WhereScan object is used as an iterator for locating
118305** terms in the WHERE clause that are useful to the query planner.
118306*/
118307struct WhereScan {
118308  WhereClause *pOrigWC;      /* Original, innermost WhereClause */
118309  WhereClause *pWC;          /* WhereClause currently being scanned */
118310  char *zCollName;           /* Required collating sequence, if not NULL */
118311  Expr *pIdxExpr;            /* Search for this index expression */
118312  char idxaff;               /* Must match this affinity, if zCollName!=NULL */
118313  unsigned char nEquiv;      /* Number of entries in aEquiv[] */
118314  unsigned char iEquiv;      /* Next unused slot in aEquiv[] */
118315  u32 opMask;                /* Acceptable operators */
118316  int k;                     /* Resume scanning at this->pWC->a[this->k] */
118317  int aiCur[11];             /* Cursors in the equivalence class */
118318  i16 aiColumn[11];          /* Corresponding column number in the eq-class */
118319};
118320
118321/*
118322** An instance of the following structure holds all information about a
118323** WHERE clause.  Mostly this is a container for one or more WhereTerms.
118324**
118325** Explanation of pOuter:  For a WHERE clause of the form
118326**
118327**           a AND ((b AND c) OR (d AND e)) AND f
118328**
118329** There are separate WhereClause objects for the whole clause and for
118330** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
118331** subclauses points to the WhereClause object for the whole clause.
118332*/
118333struct WhereClause {
118334  WhereInfo *pWInfo;       /* WHERE clause processing context */
118335  WhereClause *pOuter;     /* Outer conjunction */
118336  u8 op;                   /* Split operator.  TK_AND or TK_OR */
118337  int nTerm;               /* Number of terms */
118338  int nSlot;               /* Number of entries in a[] */
118339  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
118340#if defined(SQLITE_SMALL_STACK)
118341  WhereTerm aStatic[1];    /* Initial static space for a[] */
118342#else
118343  WhereTerm aStatic[8];    /* Initial static space for a[] */
118344#endif
118345};
118346
118347/*
118348** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
118349** a dynamically allocated instance of the following structure.
118350*/
118351struct WhereOrInfo {
118352  WhereClause wc;          /* Decomposition into subterms */
118353  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
118354};
118355
118356/*
118357** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
118358** a dynamically allocated instance of the following structure.
118359*/
118360struct WhereAndInfo {
118361  WhereClause wc;          /* The subexpression broken out */
118362};
118363
118364/*
118365** An instance of the following structure keeps track of a mapping
118366** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
118367**
118368** The VDBE cursor numbers are small integers contained in
118369** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
118370** clause, the cursor numbers might not begin with 0 and they might
118371** contain gaps in the numbering sequence.  But we want to make maximum
118372** use of the bits in our bitmasks.  This structure provides a mapping
118373** from the sparse cursor numbers into consecutive integers beginning
118374** with 0.
118375**
118376** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
118377** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
118378**
118379** For example, if the WHERE clause expression used these VDBE
118380** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
118381** would map those cursor numbers into bits 0 through 5.
118382**
118383** Note that the mapping is not necessarily ordered.  In the example
118384** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
118385** 57->5, 73->4.  Or one of 719 other combinations might be used. It
118386** does not really matter.  What is important is that sparse cursor
118387** numbers all get mapped into bit numbers that begin with 0 and contain
118388** no gaps.
118389*/
118390struct WhereMaskSet {
118391  int n;                        /* Number of assigned cursor values */
118392  int ix[BMS];                  /* Cursor assigned to each bit */
118393};
118394
118395/*
118396** Initialize a WhereMaskSet object
118397*/
118398#define initMaskSet(P)  (P)->n=0
118399
118400/*
118401** This object is a convenience wrapper holding all information needed
118402** to construct WhereLoop objects for a particular query.
118403*/
118404struct WhereLoopBuilder {
118405  WhereInfo *pWInfo;        /* Information about this WHERE */
118406  WhereClause *pWC;         /* WHERE clause terms */
118407  ExprList *pOrderBy;       /* ORDER BY clause */
118408  WhereLoop *pNew;          /* Template WhereLoop */
118409  WhereOrSet *pOrSet;       /* Record best loops here, if not NULL */
118410#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118411  UnpackedRecord *pRec;     /* Probe for stat4 (if required) */
118412  int nRecValid;            /* Number of valid fields currently in pRec */
118413#endif
118414};
118415
118416/*
118417** The WHERE clause processing routine has two halves.  The
118418** first part does the start of the WHERE loop and the second
118419** half does the tail of the WHERE loop.  An instance of
118420** this structure is returned by the first half and passed
118421** into the second half to give some continuity.
118422**
118423** An instance of this object holds the complete state of the query
118424** planner.
118425*/
118426struct WhereInfo {
118427  Parse *pParse;            /* Parsing and code generating context */
118428  SrcList *pTabList;        /* List of tables in the join */
118429  ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
118430  ExprList *pResultSet;     /* Result set. DISTINCT operates on these */
118431  WhereLoop *pLoops;        /* List of all WhereLoop objects */
118432  Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
118433  LogEst nRowOut;           /* Estimated number of output rows */
118434  u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
118435  i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */
118436  u8 sorted;                /* True if really sorted (not just grouped) */
118437  u8 eOnePass;              /* ONEPASS_OFF, or _SINGLE, or _MULTI */
118438  u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
118439  u8 eDistinct;             /* One of the WHERE_DISTINCT_* values below */
118440  u8 nLevel;                /* Number of nested loop */
118441  int iTop;                 /* The very beginning of the WHERE loop */
118442  int iContinue;            /* Jump here to continue with next record */
118443  int iBreak;               /* Jump here to break out of the loop */
118444  int savedNQueryLoop;      /* pParse->nQueryLoop outside the WHERE loop */
118445  int aiCurOnePass[2];      /* OP_OpenWrite cursors for the ONEPASS opt */
118446  WhereMaskSet sMaskSet;    /* Map cursor numbers to bitmasks */
118447  WhereClause sWC;          /* Decomposition of the WHERE clause */
118448  WhereLevel a[1];          /* Information about each nest loop in WHERE */
118449};
118450
118451/*
118452** Private interfaces - callable only by other where.c routines.
118453**
118454** where.c:
118455*/
118456SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
118457SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
118458  WhereClause *pWC,     /* The WHERE clause to be searched */
118459  int iCur,             /* Cursor number of LHS */
118460  int iColumn,          /* Column number of LHS */
118461  Bitmask notReady,     /* RHS must not overlap with this mask */
118462  u32 op,               /* Mask of WO_xx values describing operator */
118463  Index *pIdx           /* Must be compatible with this index, if not NULL */
118464);
118465
118466/* wherecode.c: */
118467#ifndef SQLITE_OMIT_EXPLAIN
118468SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
118469  Parse *pParse,                  /* Parse context */
118470  SrcList *pTabList,              /* Table list this loop refers to */
118471  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
118472  int iLevel,                     /* Value for "level" column of output */
118473  int iFrom,                      /* Value for "from" column of output */
118474  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
118475);
118476#else
118477# define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
118478#endif /* SQLITE_OMIT_EXPLAIN */
118479#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
118480SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
118481  Vdbe *v,                        /* Vdbe to add scanstatus entry to */
118482  SrcList *pSrclist,              /* FROM clause pLvl reads data from */
118483  WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
118484  int addrExplain                 /* Address of OP_Explain (or 0) */
118485);
118486#else
118487# define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
118488#endif
118489SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
118490  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
118491  int iLevel,          /* Which level of pWInfo->a[] should be coded */
118492  Bitmask notReady     /* Which tables are currently available */
118493);
118494
118495/* whereexpr.c: */
118496SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
118497SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
118498SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
118499SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
118500SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
118501SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
118502SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
118503
118504
118505
118506
118507
118508/*
118509** Bitmasks for the operators on WhereTerm objects.  These are all
118510** operators that are of interest to the query planner.  An
118511** OR-ed combination of these values can be used when searching for
118512** particular WhereTerms within a WhereClause.
118513*/
118514#define WO_IN     0x0001
118515#define WO_EQ     0x0002
118516#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
118517#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
118518#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
118519#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
118520#define WO_MATCH  0x0040
118521#define WO_IS     0x0080
118522#define WO_ISNULL 0x0100
118523#define WO_OR     0x0200       /* Two or more OR-connected terms */
118524#define WO_AND    0x0400       /* Two or more AND-connected terms */
118525#define WO_EQUIV  0x0800       /* Of the form A==B, both columns */
118526#define WO_NOOP   0x1000       /* This term does not restrict search space */
118527
118528#define WO_ALL    0x1fff       /* Mask of all possible WO_* values */
118529#define WO_SINGLE 0x01ff       /* Mask of all non-compound WO_* values */
118530
118531/*
118532** These are definitions of bits in the WhereLoop.wsFlags field.
118533** The particular combination of bits in each WhereLoop help to
118534** determine the algorithm that WhereLoop represents.
118535*/
118536#define WHERE_COLUMN_EQ    0x00000001  /* x=EXPR */
118537#define WHERE_COLUMN_RANGE 0x00000002  /* x<EXPR and/or x>EXPR */
118538#define WHERE_COLUMN_IN    0x00000004  /* x IN (...) */
118539#define WHERE_COLUMN_NULL  0x00000008  /* x IS NULL */
118540#define WHERE_CONSTRAINT   0x0000000f  /* Any of the WHERE_COLUMN_xxx values */
118541#define WHERE_TOP_LIMIT    0x00000010  /* x<EXPR or x<=EXPR constraint */
118542#define WHERE_BTM_LIMIT    0x00000020  /* x>EXPR or x>=EXPR constraint */
118543#define WHERE_BOTH_LIMIT   0x00000030  /* Both x>EXPR and x<EXPR */
118544#define WHERE_IDX_ONLY     0x00000040  /* Use index only - omit table */
118545#define WHERE_IPK          0x00000100  /* x is the INTEGER PRIMARY KEY */
118546#define WHERE_INDEXED      0x00000200  /* WhereLoop.u.btree.pIndex is valid */
118547#define WHERE_VIRTUALTABLE 0x00000400  /* WhereLoop.u.vtab is valid */
118548#define WHERE_IN_ABLE      0x00000800  /* Able to support an IN operator */
118549#define WHERE_ONEROW       0x00001000  /* Selects no more than one row */
118550#define WHERE_MULTI_OR     0x00002000  /* OR using multiple indices */
118551#define WHERE_AUTO_INDEX   0x00004000  /* Uses an ephemeral index */
118552#define WHERE_SKIPSCAN     0x00008000  /* Uses the skip-scan algorithm */
118553#define WHERE_UNQ_WANTED   0x00010000  /* WHERE_ONEROW would have been helpful*/
118554#define WHERE_PARTIALIDX   0x00020000  /* The automatic index is partial */
118555
118556/************** End of whereInt.h ********************************************/
118557/************** Continuing where we left off in wherecode.c ******************/
118558
118559#ifndef SQLITE_OMIT_EXPLAIN
118560/*
118561** This routine is a helper for explainIndexRange() below
118562**
118563** pStr holds the text of an expression that we are building up one term
118564** at a time.  This routine adds a new term to the end of the expression.
118565** Terms are separated by AND so add the "AND" text for second and subsequent
118566** terms only.
118567*/
118568static void explainAppendTerm(
118569  StrAccum *pStr,             /* The text expression being built */
118570  int iTerm,                  /* Index of this term.  First is zero */
118571  const char *zColumn,        /* Name of the column */
118572  const char *zOp             /* Name of the operator */
118573){
118574  if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
118575  sqlite3StrAccumAppendAll(pStr, zColumn);
118576  sqlite3StrAccumAppend(pStr, zOp, 1);
118577  sqlite3StrAccumAppend(pStr, "?", 1);
118578}
118579
118580/*
118581** Return the name of the i-th column of the pIdx index.
118582*/
118583static const char *explainIndexColumnName(Index *pIdx, int i){
118584  i = pIdx->aiColumn[i];
118585  if( i==XN_EXPR ) return "<expr>";
118586  if( i==XN_ROWID ) return "rowid";
118587  return pIdx->pTable->aCol[i].zName;
118588}
118589
118590/*
118591** Argument pLevel describes a strategy for scanning table pTab. This
118592** function appends text to pStr that describes the subset of table
118593** rows scanned by the strategy in the form of an SQL expression.
118594**
118595** For example, if the query:
118596**
118597**   SELECT * FROM t1 WHERE a=1 AND b>2;
118598**
118599** is run and there is an index on (a, b), then this function returns a
118600** string similar to:
118601**
118602**   "a=? AND b>?"
118603*/
118604static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
118605  Index *pIndex = pLoop->u.btree.pIndex;
118606  u16 nEq = pLoop->u.btree.nEq;
118607  u16 nSkip = pLoop->nSkip;
118608  int i, j;
118609
118610  if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
118611  sqlite3StrAccumAppend(pStr, " (", 2);
118612  for(i=0; i<nEq; i++){
118613    const char *z = explainIndexColumnName(pIndex, i);
118614    if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
118615    sqlite3XPrintf(pStr, 0, i>=nSkip ? "%s=?" : "ANY(%s)", z);
118616  }
118617
118618  j = i;
118619  if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
118620    const char *z = explainIndexColumnName(pIndex, i);
118621    explainAppendTerm(pStr, i++, z, ">");
118622  }
118623  if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
118624    const char *z = explainIndexColumnName(pIndex, j);
118625    explainAppendTerm(pStr, i, z, "<");
118626  }
118627  sqlite3StrAccumAppend(pStr, ")", 1);
118628}
118629
118630/*
118631** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
118632** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
118633** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
118634** is added to the output to describe the table scan strategy in pLevel.
118635**
118636** If an OP_Explain opcode is added to the VM, its address is returned.
118637** Otherwise, if no OP_Explain is coded, zero is returned.
118638*/
118639SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
118640  Parse *pParse,                  /* Parse context */
118641  SrcList *pTabList,              /* Table list this loop refers to */
118642  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
118643  int iLevel,                     /* Value for "level" column of output */
118644  int iFrom,                      /* Value for "from" column of output */
118645  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
118646){
118647  int ret = 0;
118648#if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
118649  if( pParse->explain==2 )
118650#endif
118651  {
118652    struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
118653    Vdbe *v = pParse->pVdbe;      /* VM being constructed */
118654    sqlite3 *db = pParse->db;     /* Database handle */
118655    int iId = pParse->iSelectId;  /* Select id (left-most output column) */
118656    int isSearch;                 /* True for a SEARCH. False for SCAN. */
118657    WhereLoop *pLoop;             /* The controlling WhereLoop object */
118658    u32 flags;                    /* Flags that describe this loop */
118659    char *zMsg;                   /* Text to add to EQP output */
118660    StrAccum str;                 /* EQP output string */
118661    char zBuf[100];               /* Initial space for EQP output string */
118662
118663    pLoop = pLevel->pWLoop;
118664    flags = pLoop->wsFlags;
118665    if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return 0;
118666
118667    isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
118668            || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
118669            || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
118670
118671    sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
118672    sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
118673    if( pItem->pSelect ){
118674      sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
118675    }else{
118676      sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
118677    }
118678
118679    if( pItem->zAlias ){
118680      sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
118681    }
118682    if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
118683      const char *zFmt = 0;
118684      Index *pIdx;
118685
118686      assert( pLoop->u.btree.pIndex!=0 );
118687      pIdx = pLoop->u.btree.pIndex;
118688      assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
118689      if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
118690        if( isSearch ){
118691          zFmt = "PRIMARY KEY";
118692        }
118693      }else if( flags & WHERE_PARTIALIDX ){
118694        zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
118695      }else if( flags & WHERE_AUTO_INDEX ){
118696        zFmt = "AUTOMATIC COVERING INDEX";
118697      }else if( flags & WHERE_IDX_ONLY ){
118698        zFmt = "COVERING INDEX %s";
118699      }else{
118700        zFmt = "INDEX %s";
118701      }
118702      if( zFmt ){
118703        sqlite3StrAccumAppend(&str, " USING ", 7);
118704        sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
118705        explainIndexRange(&str, pLoop);
118706      }
118707    }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
118708      const char *zRangeOp;
118709      if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
118710        zRangeOp = "=";
118711      }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
118712        zRangeOp = ">? AND rowid<";
118713      }else if( flags&WHERE_BTM_LIMIT ){
118714        zRangeOp = ">";
118715      }else{
118716        assert( flags&WHERE_TOP_LIMIT);
118717        zRangeOp = "<";
118718      }
118719      sqlite3XPrintf(&str, 0, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
118720    }
118721#ifndef SQLITE_OMIT_VIRTUALTABLE
118722    else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
118723      sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
118724                  pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
118725    }
118726#endif
118727#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
118728    if( pLoop->nOut>=10 ){
118729      sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
118730    }else{
118731      sqlite3StrAccumAppend(&str, " (~1 row)", 9);
118732    }
118733#endif
118734    zMsg = sqlite3StrAccumFinish(&str);
118735    ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
118736  }
118737  return ret;
118738}
118739#endif /* SQLITE_OMIT_EXPLAIN */
118740
118741#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
118742/*
118743** Configure the VM passed as the first argument with an
118744** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
118745** implement level pLvl. Argument pSrclist is a pointer to the FROM
118746** clause that the scan reads data from.
118747**
118748** If argument addrExplain is not 0, it must be the address of an
118749** OP_Explain instruction that describes the same loop.
118750*/
118751SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
118752  Vdbe *v,                        /* Vdbe to add scanstatus entry to */
118753  SrcList *pSrclist,              /* FROM clause pLvl reads data from */
118754  WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
118755  int addrExplain                 /* Address of OP_Explain (or 0) */
118756){
118757  const char *zObj = 0;
118758  WhereLoop *pLoop = pLvl->pWLoop;
118759  if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0  &&  pLoop->u.btree.pIndex!=0 ){
118760    zObj = pLoop->u.btree.pIndex->zName;
118761  }else{
118762    zObj = pSrclist->a[pLvl->iFrom].zName;
118763  }
118764  sqlite3VdbeScanStatus(
118765      v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
118766  );
118767}
118768#endif
118769
118770
118771/*
118772** Disable a term in the WHERE clause.  Except, do not disable the term
118773** if it controls a LEFT OUTER JOIN and it did not originate in the ON
118774** or USING clause of that join.
118775**
118776** Consider the term t2.z='ok' in the following queries:
118777**
118778**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
118779**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
118780**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
118781**
118782** The t2.z='ok' is disabled in the in (2) because it originates
118783** in the ON clause.  The term is disabled in (3) because it is not part
118784** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
118785**
118786** Disabling a term causes that term to not be tested in the inner loop
118787** of the join.  Disabling is an optimization.  When terms are satisfied
118788** by indices, we disable them to prevent redundant tests in the inner
118789** loop.  We would get the correct results if nothing were ever disabled,
118790** but joins might run a little slower.  The trick is to disable as much
118791** as we can without disabling too much.  If we disabled in (1), we'd get
118792** the wrong answer.  See ticket #813.
118793**
118794** If all the children of a term are disabled, then that term is also
118795** automatically disabled.  In this way, terms get disabled if derived
118796** virtual terms are tested first.  For example:
118797**
118798**      x GLOB 'abc*' AND x>='abc' AND x<'acd'
118799**      \___________/     \______/     \_____/
118800**         parent          child1       child2
118801**
118802** Only the parent term was in the original WHERE clause.  The child1
118803** and child2 terms were added by the LIKE optimization.  If both of
118804** the virtual child terms are valid, then testing of the parent can be
118805** skipped.
118806**
118807** Usually the parent term is marked as TERM_CODED.  But if the parent
118808** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
118809** The TERM_LIKECOND marking indicates that the term should be coded inside
118810** a conditional such that is only evaluated on the second pass of a
118811** LIKE-optimization loop, when scanning BLOBs instead of strings.
118812*/
118813static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
118814  int nLoop = 0;
118815  while( pTerm
118816      && (pTerm->wtFlags & TERM_CODED)==0
118817      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
118818      && (pLevel->notReady & pTerm->prereqAll)==0
118819  ){
118820    if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
118821      pTerm->wtFlags |= TERM_LIKECOND;
118822    }else{
118823      pTerm->wtFlags |= TERM_CODED;
118824    }
118825    if( pTerm->iParent<0 ) break;
118826    pTerm = &pTerm->pWC->a[pTerm->iParent];
118827    pTerm->nChild--;
118828    if( pTerm->nChild!=0 ) break;
118829    nLoop++;
118830  }
118831}
118832
118833/*
118834** Code an OP_Affinity opcode to apply the column affinity string zAff
118835** to the n registers starting at base.
118836**
118837** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
118838** beginning and end of zAff are ignored.  If all entries in zAff are
118839** SQLITE_AFF_BLOB, then no code gets generated.
118840**
118841** This routine makes its own copy of zAff so that the caller is free
118842** to modify zAff after this routine returns.
118843*/
118844static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
118845  Vdbe *v = pParse->pVdbe;
118846  if( zAff==0 ){
118847    assert( pParse->db->mallocFailed );
118848    return;
118849  }
118850  assert( v!=0 );
118851
118852  /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
118853  ** and end of the affinity string.
118854  */
118855  while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
118856    n--;
118857    base++;
118858    zAff++;
118859  }
118860  while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
118861    n--;
118862  }
118863
118864  /* Code the OP_Affinity opcode if there is anything left to do. */
118865  if( n>0 ){
118866    sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
118867    sqlite3VdbeChangeP4(v, -1, zAff, n);
118868    sqlite3ExprCacheAffinityChange(pParse, base, n);
118869  }
118870}
118871
118872
118873/*
118874** Generate code for a single equality term of the WHERE clause.  An equality
118875** term can be either X=expr or X IN (...).   pTerm is the term to be
118876** coded.
118877**
118878** The current value for the constraint is left in register iReg.
118879**
118880** For a constraint of the form X=expr, the expression is evaluated and its
118881** result is left on the stack.  For constraints of the form X IN (...)
118882** this routine sets up a loop that will iterate over all values of X.
118883*/
118884static int codeEqualityTerm(
118885  Parse *pParse,      /* The parsing context */
118886  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
118887  WhereLevel *pLevel, /* The level of the FROM clause we are working on */
118888  int iEq,            /* Index of the equality term within this level */
118889  int bRev,           /* True for reverse-order IN operations */
118890  int iTarget         /* Attempt to leave results in this register */
118891){
118892  Expr *pX = pTerm->pExpr;
118893  Vdbe *v = pParse->pVdbe;
118894  int iReg;                  /* Register holding results */
118895
118896  assert( iTarget>0 );
118897  if( pX->op==TK_EQ || pX->op==TK_IS ){
118898    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
118899  }else if( pX->op==TK_ISNULL ){
118900    iReg = iTarget;
118901    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
118902#ifndef SQLITE_OMIT_SUBQUERY
118903  }else{
118904    int eType;
118905    int iTab;
118906    struct InLoop *pIn;
118907    WhereLoop *pLoop = pLevel->pWLoop;
118908
118909    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
118910      && pLoop->u.btree.pIndex!=0
118911      && pLoop->u.btree.pIndex->aSortOrder[iEq]
118912    ){
118913      testcase( iEq==0 );
118914      testcase( bRev );
118915      bRev = !bRev;
118916    }
118917    assert( pX->op==TK_IN );
118918    iReg = iTarget;
118919    eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
118920    if( eType==IN_INDEX_INDEX_DESC ){
118921      testcase( bRev );
118922      bRev = !bRev;
118923    }
118924    iTab = pX->iTable;
118925    sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
118926    VdbeCoverageIf(v, bRev);
118927    VdbeCoverageIf(v, !bRev);
118928    assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
118929    pLoop->wsFlags |= WHERE_IN_ABLE;
118930    if( pLevel->u.in.nIn==0 ){
118931      pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
118932    }
118933    pLevel->u.in.nIn++;
118934    pLevel->u.in.aInLoop =
118935       sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
118936                              sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
118937    pIn = pLevel->u.in.aInLoop;
118938    if( pIn ){
118939      pIn += pLevel->u.in.nIn - 1;
118940      pIn->iCur = iTab;
118941      if( eType==IN_INDEX_ROWID ){
118942        pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
118943      }else{
118944        pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
118945      }
118946      pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
118947      sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
118948    }else{
118949      pLevel->u.in.nIn = 0;
118950    }
118951#endif
118952  }
118953  disableTerm(pLevel, pTerm);
118954  return iReg;
118955}
118956
118957/*
118958** Generate code that will evaluate all == and IN constraints for an
118959** index scan.
118960**
118961** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
118962** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
118963** The index has as many as three equality constraints, but in this
118964** example, the third "c" value is an inequality.  So only two
118965** constraints are coded.  This routine will generate code to evaluate
118966** a==5 and b IN (1,2,3).  The current values for a and b will be stored
118967** in consecutive registers and the index of the first register is returned.
118968**
118969** In the example above nEq==2.  But this subroutine works for any value
118970** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
118971** The only thing it does is allocate the pLevel->iMem memory cell and
118972** compute the affinity string.
118973**
118974** The nExtraReg parameter is 0 or 1.  It is 0 if all WHERE clause constraints
118975** are == or IN and are covered by the nEq.  nExtraReg is 1 if there is
118976** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
118977** occurs after the nEq quality constraints.
118978**
118979** This routine allocates a range of nEq+nExtraReg memory cells and returns
118980** the index of the first memory cell in that range. The code that
118981** calls this routine will use that memory range to store keys for
118982** start and termination conditions of the loop.
118983** key value of the loop.  If one or more IN operators appear, then
118984** this routine allocates an additional nEq memory cells for internal
118985** use.
118986**
118987** Before returning, *pzAff is set to point to a buffer containing a
118988** copy of the column affinity string of the index allocated using
118989** sqlite3DbMalloc(). Except, entries in the copy of the string associated
118990** with equality constraints that use BLOB or NONE affinity are set to
118991** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
118992**
118993**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
118994**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
118995**
118996** In the example above, the index on t1(a) has TEXT affinity. But since
118997** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
118998** no conversion should be attempted before using a t2.b value as part of
118999** a key to search the index. Hence the first byte in the returned affinity
119000** string in this example would be set to SQLITE_AFF_BLOB.
119001*/
119002static int codeAllEqualityTerms(
119003  Parse *pParse,        /* Parsing context */
119004  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
119005  int bRev,             /* Reverse the order of IN operators */
119006  int nExtraReg,        /* Number of extra registers to allocate */
119007  char **pzAff          /* OUT: Set to point to affinity string */
119008){
119009  u16 nEq;                      /* The number of == or IN constraints to code */
119010  u16 nSkip;                    /* Number of left-most columns to skip */
119011  Vdbe *v = pParse->pVdbe;      /* The vm under construction */
119012  Index *pIdx;                  /* The index being used for this loop */
119013  WhereTerm *pTerm;             /* A single constraint term */
119014  WhereLoop *pLoop;             /* The WhereLoop object */
119015  int j;                        /* Loop counter */
119016  int regBase;                  /* Base register */
119017  int nReg;                     /* Number of registers to allocate */
119018  char *zAff;                   /* Affinity string to return */
119019
119020  /* This module is only called on query plans that use an index. */
119021  pLoop = pLevel->pWLoop;
119022  assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
119023  nEq = pLoop->u.btree.nEq;
119024  nSkip = pLoop->nSkip;
119025  pIdx = pLoop->u.btree.pIndex;
119026  assert( pIdx!=0 );
119027
119028  /* Figure out how many memory cells we will need then allocate them.
119029  */
119030  regBase = pParse->nMem + 1;
119031  nReg = pLoop->u.btree.nEq + nExtraReg;
119032  pParse->nMem += nReg;
119033
119034  zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
119035  if( !zAff ){
119036    pParse->db->mallocFailed = 1;
119037  }
119038
119039  if( nSkip ){
119040    int iIdxCur = pLevel->iIdxCur;
119041    sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
119042    VdbeCoverageIf(v, bRev==0);
119043    VdbeCoverageIf(v, bRev!=0);
119044    VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
119045    j = sqlite3VdbeAddOp0(v, OP_Goto);
119046    pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
119047                            iIdxCur, 0, regBase, nSkip);
119048    VdbeCoverageIf(v, bRev==0);
119049    VdbeCoverageIf(v, bRev!=0);
119050    sqlite3VdbeJumpHere(v, j);
119051    for(j=0; j<nSkip; j++){
119052      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
119053      testcase( pIdx->aiColumn[j]==XN_EXPR );
119054      VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
119055    }
119056  }
119057
119058  /* Evaluate the equality constraints
119059  */
119060  assert( zAff==0 || (int)strlen(zAff)>=nEq );
119061  for(j=nSkip; j<nEq; j++){
119062    int r1;
119063    pTerm = pLoop->aLTerm[j];
119064    assert( pTerm!=0 );
119065    /* The following testcase is true for indices with redundant columns.
119066    ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
119067    testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
119068    testcase( pTerm->wtFlags & TERM_VIRTUAL );
119069    r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
119070    if( r1!=regBase+j ){
119071      if( nReg==1 ){
119072        sqlite3ReleaseTempReg(pParse, regBase);
119073        regBase = r1;
119074      }else{
119075        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
119076      }
119077    }
119078    testcase( pTerm->eOperator & WO_ISNULL );
119079    testcase( pTerm->eOperator & WO_IN );
119080    if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
119081      Expr *pRight = pTerm->pExpr->pRight;
119082      if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
119083        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
119084        VdbeCoverage(v);
119085      }
119086      if( zAff ){
119087        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
119088          zAff[j] = SQLITE_AFF_BLOB;
119089        }
119090        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
119091          zAff[j] = SQLITE_AFF_BLOB;
119092        }
119093      }
119094    }
119095  }
119096  *pzAff = zAff;
119097  return regBase;
119098}
119099
119100/*
119101** If the most recently coded instruction is a constant range contraint
119102** that originated from the LIKE optimization, then change the P3 to be
119103** pLoop->iLikeRepCntr and set P5.
119104**
119105** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
119106** expression: "x>='ABC' AND x<'abd'".  But this requires that the range
119107** scan loop run twice, once for strings and a second time for BLOBs.
119108** The OP_String opcodes on the second pass convert the upper and lower
119109** bound string contants to blobs.  This routine makes the necessary changes
119110** to the OP_String opcodes for that to happen.
119111*/
119112static void whereLikeOptimizationStringFixup(
119113  Vdbe *v,                /* prepared statement under construction */
119114  WhereLevel *pLevel,     /* The loop that contains the LIKE operator */
119115  WhereTerm *pTerm        /* The upper or lower bound just coded */
119116){
119117  if( pTerm->wtFlags & TERM_LIKEOPT ){
119118    VdbeOp *pOp;
119119    assert( pLevel->iLikeRepCntr>0 );
119120    pOp = sqlite3VdbeGetOp(v, -1);
119121    assert( pOp!=0 );
119122    assert( pOp->opcode==OP_String8
119123            || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
119124    pOp->p3 = pLevel->iLikeRepCntr;
119125    pOp->p5 = 1;
119126  }
119127}
119128
119129
119130/*
119131** Generate code for the start of the iLevel-th loop in the WHERE clause
119132** implementation described by pWInfo.
119133*/
119134SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
119135  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
119136  int iLevel,          /* Which level of pWInfo->a[] should be coded */
119137  Bitmask notReady     /* Which tables are currently available */
119138){
119139  int j, k;            /* Loop counters */
119140  int iCur;            /* The VDBE cursor for the table */
119141  int addrNxt;         /* Where to jump to continue with the next IN case */
119142  int omitTable;       /* True if we use the index only */
119143  int bRev;            /* True if we need to scan in reverse order */
119144  WhereLevel *pLevel;  /* The where level to be coded */
119145  WhereLoop *pLoop;    /* The WhereLoop object being coded */
119146  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
119147  WhereTerm *pTerm;               /* A WHERE clause term */
119148  Parse *pParse;                  /* Parsing context */
119149  sqlite3 *db;                    /* Database connection */
119150  Vdbe *v;                        /* The prepared stmt under constructions */
119151  struct SrcList_item *pTabItem;  /* FROM clause term being coded */
119152  int addrBrk;                    /* Jump here to break out of the loop */
119153  int addrCont;                   /* Jump here to continue with next cycle */
119154  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
119155  int iReleaseReg = 0;      /* Temp register to free before returning */
119156
119157  pParse = pWInfo->pParse;
119158  v = pParse->pVdbe;
119159  pWC = &pWInfo->sWC;
119160  db = pParse->db;
119161  pLevel = &pWInfo->a[iLevel];
119162  pLoop = pLevel->pWLoop;
119163  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
119164  iCur = pTabItem->iCursor;
119165  pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
119166  bRev = (pWInfo->revMask>>iLevel)&1;
119167  omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
119168           && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
119169  VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
119170
119171  /* Create labels for the "break" and "continue" instructions
119172  ** for the current loop.  Jump to addrBrk to break out of a loop.
119173  ** Jump to cont to go immediately to the next iteration of the
119174  ** loop.
119175  **
119176  ** When there is an IN operator, we also have a "addrNxt" label that
119177  ** means to continue with the next IN value combination.  When
119178  ** there are no IN operators in the constraints, the "addrNxt" label
119179  ** is the same as "addrBrk".
119180  */
119181  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
119182  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
119183
119184  /* If this is the right table of a LEFT OUTER JOIN, allocate and
119185  ** initialize a memory cell that records if this table matches any
119186  ** row of the left table of the join.
119187  */
119188  if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
119189    pLevel->iLeftJoin = ++pParse->nMem;
119190    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
119191    VdbeComment((v, "init LEFT JOIN no-match flag"));
119192  }
119193
119194  /* Special case of a FROM clause subquery implemented as a co-routine */
119195  if( pTabItem->fg.viaCoroutine ){
119196    int regYield = pTabItem->regReturn;
119197    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
119198    pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
119199    VdbeCoverage(v);
119200    VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
119201    pLevel->op = OP_Goto;
119202  }else
119203
119204#ifndef SQLITE_OMIT_VIRTUALTABLE
119205  if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
119206    /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
119207    **          to access the data.
119208    */
119209    int iReg;   /* P3 Value for OP_VFilter */
119210    int addrNotFound;
119211    int nConstraint = pLoop->nLTerm;
119212
119213    sqlite3ExprCachePush(pParse);
119214    iReg = sqlite3GetTempRange(pParse, nConstraint+2);
119215    addrNotFound = pLevel->addrBrk;
119216    for(j=0; j<nConstraint; j++){
119217      int iTarget = iReg+j+2;
119218      pTerm = pLoop->aLTerm[j];
119219      if( pTerm==0 ) continue;
119220      if( pTerm->eOperator & WO_IN ){
119221        codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
119222        addrNotFound = pLevel->addrNxt;
119223      }else{
119224        sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
119225      }
119226    }
119227    sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
119228    sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
119229    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
119230                      pLoop->u.vtab.idxStr,
119231                      pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
119232    VdbeCoverage(v);
119233    pLoop->u.vtab.needFree = 0;
119234    for(j=0; j<nConstraint && j<16; j++){
119235      if( (pLoop->u.vtab.omitMask>>j)&1 ){
119236        disableTerm(pLevel, pLoop->aLTerm[j]);
119237      }
119238    }
119239    pLevel->p1 = iCur;
119240    pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
119241    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
119242    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
119243    sqlite3ExprCachePop(pParse);
119244  }else
119245#endif /* SQLITE_OMIT_VIRTUALTABLE */
119246
119247  if( (pLoop->wsFlags & WHERE_IPK)!=0
119248   && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
119249  ){
119250    /* Case 2:  We can directly reference a single row using an
119251    **          equality comparison against the ROWID field.  Or
119252    **          we reference multiple rows using a "rowid IN (...)"
119253    **          construct.
119254    */
119255    assert( pLoop->u.btree.nEq==1 );
119256    pTerm = pLoop->aLTerm[0];
119257    assert( pTerm!=0 );
119258    assert( pTerm->pExpr!=0 );
119259    assert( omitTable==0 );
119260    testcase( pTerm->wtFlags & TERM_VIRTUAL );
119261    iReleaseReg = ++pParse->nMem;
119262    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
119263    if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
119264    addrNxt = pLevel->addrNxt;
119265    sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
119266    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
119267    VdbeCoverage(v);
119268    sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
119269    sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
119270    VdbeComment((v, "pk"));
119271    pLevel->op = OP_Noop;
119272  }else if( (pLoop->wsFlags & WHERE_IPK)!=0
119273         && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
119274  ){
119275    /* Case 3:  We have an inequality comparison against the ROWID field.
119276    */
119277    int testOp = OP_Noop;
119278    int start;
119279    int memEndValue = 0;
119280    WhereTerm *pStart, *pEnd;
119281
119282    assert( omitTable==0 );
119283    j = 0;
119284    pStart = pEnd = 0;
119285    if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
119286    if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
119287    assert( pStart!=0 || pEnd!=0 );
119288    if( bRev ){
119289      pTerm = pStart;
119290      pStart = pEnd;
119291      pEnd = pTerm;
119292    }
119293    if( pStart ){
119294      Expr *pX;             /* The expression that defines the start bound */
119295      int r1, rTemp;        /* Registers for holding the start boundary */
119296
119297      /* The following constant maps TK_xx codes into corresponding
119298      ** seek opcodes.  It depends on a particular ordering of TK_xx
119299      */
119300      const u8 aMoveOp[] = {
119301           /* TK_GT */  OP_SeekGT,
119302           /* TK_LE */  OP_SeekLE,
119303           /* TK_LT */  OP_SeekLT,
119304           /* TK_GE */  OP_SeekGE
119305      };
119306      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
119307      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
119308      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
119309
119310      assert( (pStart->wtFlags & TERM_VNULL)==0 );
119311      testcase( pStart->wtFlags & TERM_VIRTUAL );
119312      pX = pStart->pExpr;
119313      assert( pX!=0 );
119314      testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
119315      r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
119316      sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
119317      VdbeComment((v, "pk"));
119318      VdbeCoverageIf(v, pX->op==TK_GT);
119319      VdbeCoverageIf(v, pX->op==TK_LE);
119320      VdbeCoverageIf(v, pX->op==TK_LT);
119321      VdbeCoverageIf(v, pX->op==TK_GE);
119322      sqlite3ExprCacheAffinityChange(pParse, r1, 1);
119323      sqlite3ReleaseTempReg(pParse, rTemp);
119324      disableTerm(pLevel, pStart);
119325    }else{
119326      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
119327      VdbeCoverageIf(v, bRev==0);
119328      VdbeCoverageIf(v, bRev!=0);
119329    }
119330    if( pEnd ){
119331      Expr *pX;
119332      pX = pEnd->pExpr;
119333      assert( pX!=0 );
119334      assert( (pEnd->wtFlags & TERM_VNULL)==0 );
119335      testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
119336      testcase( pEnd->wtFlags & TERM_VIRTUAL );
119337      memEndValue = ++pParse->nMem;
119338      sqlite3ExprCode(pParse, pX->pRight, memEndValue);
119339      if( pX->op==TK_LT || pX->op==TK_GT ){
119340        testOp = bRev ? OP_Le : OP_Ge;
119341      }else{
119342        testOp = bRev ? OP_Lt : OP_Gt;
119343      }
119344      disableTerm(pLevel, pEnd);
119345    }
119346    start = sqlite3VdbeCurrentAddr(v);
119347    pLevel->op = bRev ? OP_Prev : OP_Next;
119348    pLevel->p1 = iCur;
119349    pLevel->p2 = start;
119350    assert( pLevel->p5==0 );
119351    if( testOp!=OP_Noop ){
119352      iRowidReg = ++pParse->nMem;
119353      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
119354      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
119355      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
119356      VdbeCoverageIf(v, testOp==OP_Le);
119357      VdbeCoverageIf(v, testOp==OP_Lt);
119358      VdbeCoverageIf(v, testOp==OP_Ge);
119359      VdbeCoverageIf(v, testOp==OP_Gt);
119360      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
119361    }
119362  }else if( pLoop->wsFlags & WHERE_INDEXED ){
119363    /* Case 4: A scan using an index.
119364    **
119365    **         The WHERE clause may contain zero or more equality
119366    **         terms ("==" or "IN" operators) that refer to the N
119367    **         left-most columns of the index. It may also contain
119368    **         inequality constraints (>, <, >= or <=) on the indexed
119369    **         column that immediately follows the N equalities. Only
119370    **         the right-most column can be an inequality - the rest must
119371    **         use the "==" and "IN" operators. For example, if the
119372    **         index is on (x,y,z), then the following clauses are all
119373    **         optimized:
119374    **
119375    **            x=5
119376    **            x=5 AND y=10
119377    **            x=5 AND y<10
119378    **            x=5 AND y>5 AND y<10
119379    **            x=5 AND y=5 AND z<=10
119380    **
119381    **         The z<10 term of the following cannot be used, only
119382    **         the x=5 term:
119383    **
119384    **            x=5 AND z<10
119385    **
119386    **         N may be zero if there are inequality constraints.
119387    **         If there are no inequality constraints, then N is at
119388    **         least one.
119389    **
119390    **         This case is also used when there are no WHERE clause
119391    **         constraints but an index is selected anyway, in order
119392    **         to force the output order to conform to an ORDER BY.
119393    */
119394    static const u8 aStartOp[] = {
119395      0,
119396      0,
119397      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
119398      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
119399      OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */
119400      OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */
119401      OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */
119402      OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */
119403    };
119404    static const u8 aEndOp[] = {
119405      OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */
119406      OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */
119407      OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */
119408      OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */
119409    };
119410    u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
119411    int regBase;                 /* Base register holding constraint values */
119412    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
119413    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
119414    int startEq;                 /* True if range start uses ==, >= or <= */
119415    int endEq;                   /* True if range end uses ==, >= or <= */
119416    int start_constraints;       /* Start of range is constrained */
119417    int nConstraint;             /* Number of constraint terms */
119418    Index *pIdx;                 /* The index we will be using */
119419    int iIdxCur;                 /* The VDBE cursor for the index */
119420    int nExtraReg = 0;           /* Number of extra registers needed */
119421    int op;                      /* Instruction opcode */
119422    char *zStartAff;             /* Affinity for start of range constraint */
119423    char cEndAff = 0;            /* Affinity for end of range constraint */
119424    u8 bSeekPastNull = 0;        /* True to seek past initial nulls */
119425    u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
119426
119427    pIdx = pLoop->u.btree.pIndex;
119428    iIdxCur = pLevel->iIdxCur;
119429    assert( nEq>=pLoop->nSkip );
119430
119431    /* If this loop satisfies a sort order (pOrderBy) request that
119432    ** was passed to this function to implement a "SELECT min(x) ..."
119433    ** query, then the caller will only allow the loop to run for
119434    ** a single iteration. This means that the first row returned
119435    ** should not have a NULL value stored in 'x'. If column 'x' is
119436    ** the first one after the nEq equality constraints in the index,
119437    ** this requires some special handling.
119438    */
119439    assert( pWInfo->pOrderBy==0
119440         || pWInfo->pOrderBy->nExpr==1
119441         || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
119442    if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
119443     && pWInfo->nOBSat>0
119444     && (pIdx->nKeyCol>nEq)
119445    ){
119446      assert( pLoop->nSkip==0 );
119447      bSeekPastNull = 1;
119448      nExtraReg = 1;
119449    }
119450
119451    /* Find any inequality constraint terms for the start and end
119452    ** of the range.
119453    */
119454    j = nEq;
119455    if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
119456      pRangeStart = pLoop->aLTerm[j++];
119457      nExtraReg = 1;
119458      /* Like optimization range constraints always occur in pairs */
119459      assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
119460              (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
119461    }
119462    if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
119463      pRangeEnd = pLoop->aLTerm[j++];
119464      nExtraReg = 1;
119465      if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
119466        assert( pRangeStart!=0 );                     /* LIKE opt constraints */
119467        assert( pRangeStart->wtFlags & TERM_LIKEOPT );   /* occur in pairs */
119468        pLevel->iLikeRepCntr = ++pParse->nMem;
119469        testcase( bRev );
119470        testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
119471        sqlite3VdbeAddOp2(v, OP_Integer,
119472                          bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC),
119473                          pLevel->iLikeRepCntr);
119474        VdbeComment((v, "LIKE loop counter"));
119475        pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
119476      }
119477      if( pRangeStart==0
119478       && (j = pIdx->aiColumn[nEq])>=0
119479       && pIdx->pTable->aCol[j].notNull==0
119480      ){
119481        bSeekPastNull = 1;
119482      }
119483    }
119484    assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
119485
119486    /* Generate code to evaluate all constraint terms using == or IN
119487    ** and store the values of those terms in an array of registers
119488    ** starting at regBase.
119489    */
119490    regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
119491    assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
119492    if( zStartAff ) cEndAff = zStartAff[nEq];
119493    addrNxt = pLevel->addrNxt;
119494
119495    /* If we are doing a reverse order scan on an ascending index, or
119496    ** a forward order scan on a descending index, interchange the
119497    ** start and end terms (pRangeStart and pRangeEnd).
119498    */
119499    if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
119500     || (bRev && pIdx->nKeyCol==nEq)
119501    ){
119502      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
119503      SWAP(u8, bSeekPastNull, bStopAtNull);
119504    }
119505
119506    testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
119507    testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
119508    testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
119509    testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
119510    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
119511    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
119512    start_constraints = pRangeStart || nEq>0;
119513
119514    /* Seek the index cursor to the start of the range. */
119515    nConstraint = nEq;
119516    if( pRangeStart ){
119517      Expr *pRight = pRangeStart->pExpr->pRight;
119518      sqlite3ExprCode(pParse, pRight, regBase+nEq);
119519      whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
119520      if( (pRangeStart->wtFlags & TERM_VNULL)==0
119521       && sqlite3ExprCanBeNull(pRight)
119522      ){
119523        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
119524        VdbeCoverage(v);
119525      }
119526      if( zStartAff ){
119527        if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_BLOB){
119528          /* Since the comparison is to be performed with no conversions
119529          ** applied to the operands, set the affinity to apply to pRight to
119530          ** SQLITE_AFF_BLOB.  */
119531          zStartAff[nEq] = SQLITE_AFF_BLOB;
119532        }
119533        if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
119534          zStartAff[nEq] = SQLITE_AFF_BLOB;
119535        }
119536      }
119537      nConstraint++;
119538      testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
119539    }else if( bSeekPastNull ){
119540      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
119541      nConstraint++;
119542      startEq = 0;
119543      start_constraints = 1;
119544    }
119545    codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
119546    op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
119547    assert( op!=0 );
119548    sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
119549    VdbeCoverage(v);
119550    VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
119551    VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
119552    VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
119553    VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
119554    VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
119555    VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
119556
119557    /* Load the value for the inequality constraint at the end of the
119558    ** range (if any).
119559    */
119560    nConstraint = nEq;
119561    if( pRangeEnd ){
119562      Expr *pRight = pRangeEnd->pExpr->pRight;
119563      sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
119564      sqlite3ExprCode(pParse, pRight, regBase+nEq);
119565      whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
119566      if( (pRangeEnd->wtFlags & TERM_VNULL)==0
119567       && sqlite3ExprCanBeNull(pRight)
119568      ){
119569        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
119570        VdbeCoverage(v);
119571      }
119572      if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_BLOB
119573       && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
119574      ){
119575        codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
119576      }
119577      nConstraint++;
119578      testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
119579    }else if( bStopAtNull ){
119580      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
119581      endEq = 0;
119582      nConstraint++;
119583    }
119584    sqlite3DbFree(db, zStartAff);
119585
119586    /* Top of the loop body */
119587    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
119588
119589    /* Check if the index cursor is past the end of the range. */
119590    if( nConstraint ){
119591      op = aEndOp[bRev*2 + endEq];
119592      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
119593      testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
119594      testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
119595      testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
119596      testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
119597    }
119598
119599    /* Seek the table cursor, if required */
119600    disableTerm(pLevel, pRangeStart);
119601    disableTerm(pLevel, pRangeEnd);
119602    if( omitTable ){
119603      /* pIdx is a covering index.  No need to access the main table. */
119604    }else if( HasRowid(pIdx->pTable) ){
119605      iRowidReg = ++pParse->nMem;
119606      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
119607      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
119608      if( pWInfo->eOnePass!=ONEPASS_OFF ){
119609        sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
119610        VdbeCoverage(v);
119611      }else{
119612        sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
119613      }
119614    }else if( iCur!=iIdxCur ){
119615      Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
119616      iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
119617      for(j=0; j<pPk->nKeyCol; j++){
119618        k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
119619        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
119620      }
119621      sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
119622                           iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
119623    }
119624
119625    /* Record the instruction used to terminate the loop. Disable
119626    ** WHERE clause terms made redundant by the index range scan.
119627    */
119628    if( pLoop->wsFlags & WHERE_ONEROW ){
119629      pLevel->op = OP_Noop;
119630    }else if( bRev ){
119631      pLevel->op = OP_Prev;
119632    }else{
119633      pLevel->op = OP_Next;
119634    }
119635    pLevel->p1 = iIdxCur;
119636    pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
119637    if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
119638      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
119639    }else{
119640      assert( pLevel->p5==0 );
119641    }
119642  }else
119643
119644#ifndef SQLITE_OMIT_OR_OPTIMIZATION
119645  if( pLoop->wsFlags & WHERE_MULTI_OR ){
119646    /* Case 5:  Two or more separately indexed terms connected by OR
119647    **
119648    ** Example:
119649    **
119650    **   CREATE TABLE t1(a,b,c,d);
119651    **   CREATE INDEX i1 ON t1(a);
119652    **   CREATE INDEX i2 ON t1(b);
119653    **   CREATE INDEX i3 ON t1(c);
119654    **
119655    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
119656    **
119657    ** In the example, there are three indexed terms connected by OR.
119658    ** The top of the loop looks like this:
119659    **
119660    **          Null       1                # Zero the rowset in reg 1
119661    **
119662    ** Then, for each indexed term, the following. The arguments to
119663    ** RowSetTest are such that the rowid of the current row is inserted
119664    ** into the RowSet. If it is already present, control skips the
119665    ** Gosub opcode and jumps straight to the code generated by WhereEnd().
119666    **
119667    **        sqlite3WhereBegin(<term>)
119668    **          RowSetTest                  # Insert rowid into rowset
119669    **          Gosub      2 A
119670    **        sqlite3WhereEnd()
119671    **
119672    ** Following the above, code to terminate the loop. Label A, the target
119673    ** of the Gosub above, jumps to the instruction right after the Goto.
119674    **
119675    **          Null       1                # Zero the rowset in reg 1
119676    **          Goto       B                # The loop is finished.
119677    **
119678    **       A: <loop body>                 # Return data, whatever.
119679    **
119680    **          Return     2                # Jump back to the Gosub
119681    **
119682    **       B: <after the loop>
119683    **
119684    ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
119685    ** use an ephemeral index instead of a RowSet to record the primary
119686    ** keys of the rows we have already seen.
119687    **
119688    */
119689    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
119690    SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
119691    Index *pCov = 0;             /* Potential covering index (or NULL) */
119692    int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
119693
119694    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
119695    int regRowset = 0;                        /* Register for RowSet object */
119696    int regRowid = 0;                         /* Register holding rowid */
119697    int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
119698    int iRetInit;                             /* Address of regReturn init */
119699    int untestedTerms = 0;             /* Some terms not completely tested */
119700    int ii;                            /* Loop counter */
119701    u16 wctrlFlags;                    /* Flags for sub-WHERE clause */
119702    Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
119703    Table *pTab = pTabItem->pTab;
119704
119705    pTerm = pLoop->aLTerm[0];
119706    assert( pTerm!=0 );
119707    assert( pTerm->eOperator & WO_OR );
119708    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
119709    pOrWc = &pTerm->u.pOrInfo->wc;
119710    pLevel->op = OP_Return;
119711    pLevel->p1 = regReturn;
119712
119713    /* Set up a new SrcList in pOrTab containing the table being scanned
119714    ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
119715    ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
119716    */
119717    if( pWInfo->nLevel>1 ){
119718      int nNotReady;                 /* The number of notReady tables */
119719      struct SrcList_item *origSrc;     /* Original list of tables */
119720      nNotReady = pWInfo->nLevel - iLevel - 1;
119721      pOrTab = sqlite3StackAllocRaw(db,
119722                            sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
119723      if( pOrTab==0 ) return notReady;
119724      pOrTab->nAlloc = (u8)(nNotReady + 1);
119725      pOrTab->nSrc = pOrTab->nAlloc;
119726      memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
119727      origSrc = pWInfo->pTabList->a;
119728      for(k=1; k<=nNotReady; k++){
119729        memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
119730      }
119731    }else{
119732      pOrTab = pWInfo->pTabList;
119733    }
119734
119735    /* Initialize the rowset register to contain NULL. An SQL NULL is
119736    ** equivalent to an empty rowset.  Or, create an ephemeral index
119737    ** capable of holding primary keys in the case of a WITHOUT ROWID.
119738    **
119739    ** Also initialize regReturn to contain the address of the instruction
119740    ** immediately following the OP_Return at the bottom of the loop. This
119741    ** is required in a few obscure LEFT JOIN cases where control jumps
119742    ** over the top of the loop into the body of it. In this case the
119743    ** correct response for the end-of-loop code (the OP_Return) is to
119744    ** fall through to the next instruction, just as an OP_Next does if
119745    ** called on an uninitialized cursor.
119746    */
119747    if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
119748      if( HasRowid(pTab) ){
119749        regRowset = ++pParse->nMem;
119750        sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
119751      }else{
119752        Index *pPk = sqlite3PrimaryKeyIndex(pTab);
119753        regRowset = pParse->nTab++;
119754        sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
119755        sqlite3VdbeSetP4KeyInfo(pParse, pPk);
119756      }
119757      regRowid = ++pParse->nMem;
119758    }
119759    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
119760
119761    /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
119762    ** Then for every term xN, evaluate as the subexpression: xN AND z
119763    ** That way, terms in y that are factored into the disjunction will
119764    ** be picked up by the recursive calls to sqlite3WhereBegin() below.
119765    **
119766    ** Actually, each subexpression is converted to "xN AND w" where w is
119767    ** the "interesting" terms of z - terms that did not originate in the
119768    ** ON or USING clause of a LEFT JOIN, and terms that are usable as
119769    ** indices.
119770    **
119771    ** This optimization also only applies if the (x1 OR x2 OR ...) term
119772    ** is not contained in the ON clause of a LEFT JOIN.
119773    ** See ticket http://www.sqlite.org/src/info/f2369304e4
119774    */
119775    if( pWC->nTerm>1 ){
119776      int iTerm;
119777      for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
119778        Expr *pExpr = pWC->a[iTerm].pExpr;
119779        if( &pWC->a[iTerm] == pTerm ) continue;
119780        if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
119781        if( (pWC->a[iTerm].wtFlags & TERM_VIRTUAL)!=0 ) continue;
119782        if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
119783        testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
119784        pExpr = sqlite3ExprDup(db, pExpr, 0);
119785        pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
119786      }
119787      if( pAndExpr ){
119788        pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
119789      }
119790    }
119791
119792    /* Run a separate WHERE clause for each term of the OR clause.  After
119793    ** eliminating duplicates from other WHERE clauses, the action for each
119794    ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
119795    */
119796    wctrlFlags =  WHERE_OMIT_OPEN_CLOSE
119797                | WHERE_FORCE_TABLE
119798                | WHERE_ONETABLE_ONLY
119799                | WHERE_NO_AUTOINDEX;
119800    for(ii=0; ii<pOrWc->nTerm; ii++){
119801      WhereTerm *pOrTerm = &pOrWc->a[ii];
119802      if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
119803        WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
119804        Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
119805        int jmp1 = 0;                   /* Address of jump operation */
119806        if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
119807          pAndExpr->pLeft = pOrExpr;
119808          pOrExpr = pAndExpr;
119809        }
119810        /* Loop through table entries that match term pOrTerm. */
119811        WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
119812        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
119813                                      wctrlFlags, iCovCur);
119814        assert( pSubWInfo || pParse->nErr || db->mallocFailed );
119815        if( pSubWInfo ){
119816          WhereLoop *pSubLoop;
119817          int addrExplain = sqlite3WhereExplainOneScan(
119818              pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
119819          );
119820          sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
119821
119822          /* This is the sub-WHERE clause body.  First skip over
119823          ** duplicate rows from prior sub-WHERE clauses, and record the
119824          ** rowid (or PRIMARY KEY) for the current row so that the same
119825          ** row will be skipped in subsequent sub-WHERE clauses.
119826          */
119827          if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
119828            int r;
119829            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
119830            if( HasRowid(pTab) ){
119831              r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
119832              jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
119833                                           r,iSet);
119834              VdbeCoverage(v);
119835            }else{
119836              Index *pPk = sqlite3PrimaryKeyIndex(pTab);
119837              int nPk = pPk->nKeyCol;
119838              int iPk;
119839
119840              /* Read the PK into an array of temp registers. */
119841              r = sqlite3GetTempRange(pParse, nPk);
119842              for(iPk=0; iPk<nPk; iPk++){
119843                int iCol = pPk->aiColumn[iPk];
119844                int rx;
119845                rx = sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur,r+iPk,0);
119846                if( rx!=r+iPk ){
119847                  sqlite3VdbeAddOp2(v, OP_SCopy, rx, r+iPk);
119848                }
119849              }
119850
119851              /* Check if the temp table already contains this key. If so,
119852              ** the row has already been included in the result set and
119853              ** can be ignored (by jumping past the Gosub below). Otherwise,
119854              ** insert the key into the temp table and proceed with processing
119855              ** the row.
119856              **
119857              ** Use some of the same optimizations as OP_RowSetTest: If iSet
119858              ** is zero, assume that the key cannot already be present in
119859              ** the temp table. And if iSet is -1, assume that there is no
119860              ** need to insert the key into the temp table, as it will never
119861              ** be tested for.  */
119862              if( iSet ){
119863                jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
119864                VdbeCoverage(v);
119865              }
119866              if( iSet>=0 ){
119867                sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
119868                sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
119869                if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
119870              }
119871
119872              /* Release the array of temp registers */
119873              sqlite3ReleaseTempRange(pParse, r, nPk);
119874            }
119875          }
119876
119877          /* Invoke the main loop body as a subroutine */
119878          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
119879
119880          /* Jump here (skipping the main loop body subroutine) if the
119881          ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
119882          if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
119883
119884          /* The pSubWInfo->untestedTerms flag means that this OR term
119885          ** contained one or more AND term from a notReady table.  The
119886          ** terms from the notReady table could not be tested and will
119887          ** need to be tested later.
119888          */
119889          if( pSubWInfo->untestedTerms ) untestedTerms = 1;
119890
119891          /* If all of the OR-connected terms are optimized using the same
119892          ** index, and the index is opened using the same cursor number
119893          ** by each call to sqlite3WhereBegin() made by this loop, it may
119894          ** be possible to use that index as a covering index.
119895          **
119896          ** If the call to sqlite3WhereBegin() above resulted in a scan that
119897          ** uses an index, and this is either the first OR-connected term
119898          ** processed or the index is the same as that used by all previous
119899          ** terms, set pCov to the candidate covering index. Otherwise, set
119900          ** pCov to NULL to indicate that no candidate covering index will
119901          ** be available.
119902          */
119903          pSubLoop = pSubWInfo->a[0].pWLoop;
119904          assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
119905          if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
119906           && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
119907           && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
119908          ){
119909            assert( pSubWInfo->a[0].iIdxCur==iCovCur );
119910            pCov = pSubLoop->u.btree.pIndex;
119911            wctrlFlags |= WHERE_REOPEN_IDX;
119912          }else{
119913            pCov = 0;
119914          }
119915
119916          /* Finish the loop through table entries that match term pOrTerm. */
119917          sqlite3WhereEnd(pSubWInfo);
119918        }
119919      }
119920    }
119921    pLevel->u.pCovidx = pCov;
119922    if( pCov ) pLevel->iIdxCur = iCovCur;
119923    if( pAndExpr ){
119924      pAndExpr->pLeft = 0;
119925      sqlite3ExprDelete(db, pAndExpr);
119926    }
119927    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
119928    sqlite3VdbeGoto(v, pLevel->addrBrk);
119929    sqlite3VdbeResolveLabel(v, iLoopBody);
119930
119931    if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
119932    if( !untestedTerms ) disableTerm(pLevel, pTerm);
119933  }else
119934#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
119935
119936  {
119937    /* Case 6:  There is no usable index.  We must do a complete
119938    **          scan of the entire table.
119939    */
119940    static const u8 aStep[] = { OP_Next, OP_Prev };
119941    static const u8 aStart[] = { OP_Rewind, OP_Last };
119942    assert( bRev==0 || bRev==1 );
119943    if( pTabItem->fg.isRecursive ){
119944      /* Tables marked isRecursive have only a single row that is stored in
119945      ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
119946      pLevel->op = OP_Noop;
119947    }else{
119948      pLevel->op = aStep[bRev];
119949      pLevel->p1 = iCur;
119950      pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
119951      VdbeCoverageIf(v, bRev==0);
119952      VdbeCoverageIf(v, bRev!=0);
119953      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
119954    }
119955  }
119956
119957#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
119958  pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
119959#endif
119960
119961  /* Insert code to test every subexpression that can be completely
119962  ** computed using the current set of tables.
119963  */
119964  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
119965    Expr *pE;
119966    int skipLikeAddr = 0;
119967    testcase( pTerm->wtFlags & TERM_VIRTUAL );
119968    testcase( pTerm->wtFlags & TERM_CODED );
119969    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
119970    if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
119971      testcase( pWInfo->untestedTerms==0
119972               && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
119973      pWInfo->untestedTerms = 1;
119974      continue;
119975    }
119976    pE = pTerm->pExpr;
119977    assert( pE!=0 );
119978    if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
119979      continue;
119980    }
119981    if( pTerm->wtFlags & TERM_LIKECOND ){
119982      assert( pLevel->iLikeRepCntr>0 );
119983      skipLikeAddr = sqlite3VdbeAddOp1(v, OP_IfNot, pLevel->iLikeRepCntr);
119984      VdbeCoverage(v);
119985    }
119986    sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
119987    if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
119988    pTerm->wtFlags |= TERM_CODED;
119989  }
119990
119991  /* Insert code to test for implied constraints based on transitivity
119992  ** of the "==" operator.
119993  **
119994  ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
119995  ** and we are coding the t1 loop and the t2 loop has not yet coded,
119996  ** then we cannot use the "t1.a=t2.b" constraint, but we can code
119997  ** the implied "t1.a=123" constraint.
119998  */
119999  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
120000    Expr *pE, *pEAlt;
120001    WhereTerm *pAlt;
120002    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
120003    if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
120004    if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
120005    if( pTerm->leftCursor!=iCur ) continue;
120006    if( pLevel->iLeftJoin ) continue;
120007    pE = pTerm->pExpr;
120008    assert( !ExprHasProperty(pE, EP_FromJoin) );
120009    assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
120010    pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
120011                    WO_EQ|WO_IN|WO_IS, 0);
120012    if( pAlt==0 ) continue;
120013    if( pAlt->wtFlags & (TERM_CODED) ) continue;
120014    testcase( pAlt->eOperator & WO_EQ );
120015    testcase( pAlt->eOperator & WO_IS );
120016    testcase( pAlt->eOperator & WO_IN );
120017    VdbeModuleComment((v, "begin transitive constraint"));
120018    pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
120019    if( pEAlt ){
120020      *pEAlt = *pAlt->pExpr;
120021      pEAlt->pLeft = pE->pLeft;
120022      sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
120023      sqlite3StackFree(db, pEAlt);
120024    }
120025  }
120026
120027  /* For a LEFT OUTER JOIN, generate code that will record the fact that
120028  ** at least one row of the right table has matched the left table.
120029  */
120030  if( pLevel->iLeftJoin ){
120031    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
120032    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
120033    VdbeComment((v, "record LEFT JOIN hit"));
120034    sqlite3ExprCacheClear(pParse);
120035    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
120036      testcase( pTerm->wtFlags & TERM_VIRTUAL );
120037      testcase( pTerm->wtFlags & TERM_CODED );
120038      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
120039      if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
120040        assert( pWInfo->untestedTerms );
120041        continue;
120042      }
120043      assert( pTerm->pExpr );
120044      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
120045      pTerm->wtFlags |= TERM_CODED;
120046    }
120047  }
120048
120049  return pLevel->notReady;
120050}
120051
120052/************** End of wherecode.c *******************************************/
120053/************** Begin file whereexpr.c ***************************************/
120054/*
120055** 2015-06-08
120056**
120057** The author disclaims copyright to this source code.  In place of
120058** a legal notice, here is a blessing:
120059**
120060**    May you do good and not evil.
120061**    May you find forgiveness for yourself and forgive others.
120062**    May you share freely, never taking more than you give.
120063**
120064*************************************************************************
120065** This module contains C code that generates VDBE code used to process
120066** the WHERE clause of SQL statements.
120067**
120068** This file was originally part of where.c but was split out to improve
120069** readability and editabiliity.  This file contains utility routines for
120070** analyzing Expr objects in the WHERE clause.
120071*/
120072/* #include "sqliteInt.h" */
120073/* #include "whereInt.h" */
120074
120075/* Forward declarations */
120076static void exprAnalyze(SrcList*, WhereClause*, int);
120077
120078/*
120079** Deallocate all memory associated with a WhereOrInfo object.
120080*/
120081static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
120082  sqlite3WhereClauseClear(&p->wc);
120083  sqlite3DbFree(db, p);
120084}
120085
120086/*
120087** Deallocate all memory associated with a WhereAndInfo object.
120088*/
120089static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
120090  sqlite3WhereClauseClear(&p->wc);
120091  sqlite3DbFree(db, p);
120092}
120093
120094/*
120095** Add a single new WhereTerm entry to the WhereClause object pWC.
120096** The new WhereTerm object is constructed from Expr p and with wtFlags.
120097** The index in pWC->a[] of the new WhereTerm is returned on success.
120098** 0 is returned if the new WhereTerm could not be added due to a memory
120099** allocation error.  The memory allocation failure will be recorded in
120100** the db->mallocFailed flag so that higher-level functions can detect it.
120101**
120102** This routine will increase the size of the pWC->a[] array as necessary.
120103**
120104** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
120105** for freeing the expression p is assumed by the WhereClause object pWC.
120106** This is true even if this routine fails to allocate a new WhereTerm.
120107**
120108** WARNING:  This routine might reallocate the space used to store
120109** WhereTerms.  All pointers to WhereTerms should be invalidated after
120110** calling this routine.  Such pointers may be reinitialized by referencing
120111** the pWC->a[] array.
120112*/
120113static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
120114  WhereTerm *pTerm;
120115  int idx;
120116  testcase( wtFlags & TERM_VIRTUAL );
120117  if( pWC->nTerm>=pWC->nSlot ){
120118    WhereTerm *pOld = pWC->a;
120119    sqlite3 *db = pWC->pWInfo->pParse->db;
120120    pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
120121    if( pWC->a==0 ){
120122      if( wtFlags & TERM_DYNAMIC ){
120123        sqlite3ExprDelete(db, p);
120124      }
120125      pWC->a = pOld;
120126      return 0;
120127    }
120128    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
120129    if( pOld!=pWC->aStatic ){
120130      sqlite3DbFree(db, pOld);
120131    }
120132    pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
120133    memset(&pWC->a[pWC->nTerm], 0, sizeof(pWC->a[0])*(pWC->nSlot-pWC->nTerm));
120134  }
120135  pTerm = &pWC->a[idx = pWC->nTerm++];
120136  if( p && ExprHasProperty(p, EP_Unlikely) ){
120137    pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
120138  }else{
120139    pTerm->truthProb = 1;
120140  }
120141  pTerm->pExpr = sqlite3ExprSkipCollate(p);
120142  pTerm->wtFlags = wtFlags;
120143  pTerm->pWC = pWC;
120144  pTerm->iParent = -1;
120145  return idx;
120146}
120147
120148/*
120149** Return TRUE if the given operator is one of the operators that is
120150** allowed for an indexable WHERE clause term.  The allowed operators are
120151** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
120152*/
120153static int allowedOp(int op){
120154  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
120155  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
120156  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
120157  assert( TK_GE==TK_EQ+4 );
120158  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
120159}
120160
120161/*
120162** Commute a comparison operator.  Expressions of the form "X op Y"
120163** are converted into "Y op X".
120164**
120165** If left/right precedence rules come into play when determining the
120166** collating sequence, then COLLATE operators are adjusted to ensure
120167** that the collating sequence does not change.  For example:
120168** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
120169** the left hand side of a comparison overrides any collation sequence
120170** attached to the right. For the same reason the EP_Collate flag
120171** is not commuted.
120172*/
120173static void exprCommute(Parse *pParse, Expr *pExpr){
120174  u16 expRight = (pExpr->pRight->flags & EP_Collate);
120175  u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
120176  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
120177  if( expRight==expLeft ){
120178    /* Either X and Y both have COLLATE operator or neither do */
120179    if( expRight ){
120180      /* Both X and Y have COLLATE operators.  Make sure X is always
120181      ** used by clearing the EP_Collate flag from Y. */
120182      pExpr->pRight->flags &= ~EP_Collate;
120183    }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
120184      /* Neither X nor Y have COLLATE operators, but X has a non-default
120185      ** collating sequence.  So add the EP_Collate marker on X to cause
120186      ** it to be searched first. */
120187      pExpr->pLeft->flags |= EP_Collate;
120188    }
120189  }
120190  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
120191  if( pExpr->op>=TK_GT ){
120192    assert( TK_LT==TK_GT+2 );
120193    assert( TK_GE==TK_LE+2 );
120194    assert( TK_GT>TK_EQ );
120195    assert( TK_GT<TK_LE );
120196    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
120197    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
120198  }
120199}
120200
120201/*
120202** Translate from TK_xx operator to WO_xx bitmask.
120203*/
120204static u16 operatorMask(int op){
120205  u16 c;
120206  assert( allowedOp(op) );
120207  if( op==TK_IN ){
120208    c = WO_IN;
120209  }else if( op==TK_ISNULL ){
120210    c = WO_ISNULL;
120211  }else if( op==TK_IS ){
120212    c = WO_IS;
120213  }else{
120214    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
120215    c = (u16)(WO_EQ<<(op-TK_EQ));
120216  }
120217  assert( op!=TK_ISNULL || c==WO_ISNULL );
120218  assert( op!=TK_IN || c==WO_IN );
120219  assert( op!=TK_EQ || c==WO_EQ );
120220  assert( op!=TK_LT || c==WO_LT );
120221  assert( op!=TK_LE || c==WO_LE );
120222  assert( op!=TK_GT || c==WO_GT );
120223  assert( op!=TK_GE || c==WO_GE );
120224  assert( op!=TK_IS || c==WO_IS );
120225  return c;
120226}
120227
120228
120229#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
120230/*
120231** Check to see if the given expression is a LIKE or GLOB operator that
120232** can be optimized using inequality constraints.  Return TRUE if it is
120233** so and false if not.
120234**
120235** In order for the operator to be optimizible, the RHS must be a string
120236** literal that does not begin with a wildcard.  The LHS must be a column
120237** that may only be NULL, a string, or a BLOB, never a number. (This means
120238** that virtual tables cannot participate in the LIKE optimization.)  The
120239** collating sequence for the column on the LHS must be appropriate for
120240** the operator.
120241*/
120242static int isLikeOrGlob(
120243  Parse *pParse,    /* Parsing and code generating context */
120244  Expr *pExpr,      /* Test this expression */
120245  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
120246  int *pisComplete, /* True if the only wildcard is % in the last character */
120247  int *pnoCase      /* True if uppercase is equivalent to lowercase */
120248){
120249  const char *z = 0;         /* String on RHS of LIKE operator */
120250  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
120251  ExprList *pList;           /* List of operands to the LIKE operator */
120252  int c;                     /* One character in z[] */
120253  int cnt;                   /* Number of non-wildcard prefix characters */
120254  char wc[3];                /* Wildcard characters */
120255  sqlite3 *db = pParse->db;  /* Database connection */
120256  sqlite3_value *pVal = 0;
120257  int op;                    /* Opcode of pRight */
120258
120259  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
120260    return 0;
120261  }
120262#ifdef SQLITE_EBCDIC
120263  if( *pnoCase ) return 0;
120264#endif
120265  pList = pExpr->x.pList;
120266  pLeft = pList->a[1].pExpr;
120267  if( pLeft->op!=TK_COLUMN
120268   || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
120269   || IsVirtual(pLeft->pTab)  /* Value might be numeric */
120270  ){
120271    /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
120272    ** be the name of an indexed column with TEXT affinity. */
120273    return 0;
120274  }
120275  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
120276
120277  pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
120278  op = pRight->op;
120279  if( op==TK_VARIABLE ){
120280    Vdbe *pReprepare = pParse->pReprepare;
120281    int iCol = pRight->iColumn;
120282    pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
120283    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
120284      z = (char *)sqlite3_value_text(pVal);
120285    }
120286    sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
120287    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
120288  }else if( op==TK_STRING ){
120289    z = pRight->u.zToken;
120290  }
120291  if( z ){
120292    cnt = 0;
120293    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
120294      cnt++;
120295    }
120296    if( cnt!=0 && 255!=(u8)z[cnt-1] ){
120297      Expr *pPrefix;
120298      *pisComplete = c==wc[0] && z[cnt+1]==0;
120299      pPrefix = sqlite3Expr(db, TK_STRING, z);
120300      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
120301      *ppPrefix = pPrefix;
120302      if( op==TK_VARIABLE ){
120303        Vdbe *v = pParse->pVdbe;
120304        sqlite3VdbeSetVarmask(v, pRight->iColumn);
120305        if( *pisComplete && pRight->u.zToken[1] ){
120306          /* If the rhs of the LIKE expression is a variable, and the current
120307          ** value of the variable means there is no need to invoke the LIKE
120308          ** function, then no OP_Variable will be added to the program.
120309          ** This causes problems for the sqlite3_bind_parameter_name()
120310          ** API. To work around them, add a dummy OP_Variable here.
120311          */
120312          int r1 = sqlite3GetTempReg(pParse);
120313          sqlite3ExprCodeTarget(pParse, pRight, r1);
120314          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
120315          sqlite3ReleaseTempReg(pParse, r1);
120316        }
120317      }
120318    }else{
120319      z = 0;
120320    }
120321  }
120322
120323  sqlite3ValueFree(pVal);
120324  return (z!=0);
120325}
120326#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
120327
120328
120329#ifndef SQLITE_OMIT_VIRTUALTABLE
120330/*
120331** Check to see if the given expression is of the form
120332**
120333**         column MATCH expr
120334**
120335** If it is then return TRUE.  If not, return FALSE.
120336*/
120337static int isMatchOfColumn(
120338  Expr *pExpr      /* Test this expression */
120339){
120340  ExprList *pList;
120341
120342  if( pExpr->op!=TK_FUNCTION ){
120343    return 0;
120344  }
120345  if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
120346    return 0;
120347  }
120348  pList = pExpr->x.pList;
120349  if( pList->nExpr!=2 ){
120350    return 0;
120351  }
120352  if( pList->a[1].pExpr->op != TK_COLUMN ){
120353    return 0;
120354  }
120355  return 1;
120356}
120357#endif /* SQLITE_OMIT_VIRTUALTABLE */
120358
120359/*
120360** If the pBase expression originated in the ON or USING clause of
120361** a join, then transfer the appropriate markings over to derived.
120362*/
120363static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
120364  if( pDerived ){
120365    pDerived->flags |= pBase->flags & EP_FromJoin;
120366    pDerived->iRightJoinTable = pBase->iRightJoinTable;
120367  }
120368}
120369
120370/*
120371** Mark term iChild as being a child of term iParent
120372*/
120373static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
120374  pWC->a[iChild].iParent = iParent;
120375  pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
120376  pWC->a[iParent].nChild++;
120377}
120378
120379/*
120380** Return the N-th AND-connected subterm of pTerm.  Or if pTerm is not
120381** a conjunction, then return just pTerm when N==0.  If N is exceeds
120382** the number of available subterms, return NULL.
120383*/
120384static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
120385  if( pTerm->eOperator!=WO_AND ){
120386    return N==0 ? pTerm : 0;
120387  }
120388  if( N<pTerm->u.pAndInfo->wc.nTerm ){
120389    return &pTerm->u.pAndInfo->wc.a[N];
120390  }
120391  return 0;
120392}
120393
120394/*
120395** Subterms pOne and pTwo are contained within WHERE clause pWC.  The
120396** two subterms are in disjunction - they are OR-ed together.
120397**
120398** If these two terms are both of the form:  "A op B" with the same
120399** A and B values but different operators and if the operators are
120400** compatible (if one is = and the other is <, for example) then
120401** add a new virtual AND term to pWC that is the combination of the
120402** two.
120403**
120404** Some examples:
120405**
120406**    x<y OR x=y    -->     x<=y
120407**    x=y OR x=y    -->     x=y
120408**    x<=y OR x<y   -->     x<=y
120409**
120410** The following is NOT generated:
120411**
120412**    x<y OR x>y    -->     x!=y
120413*/
120414static void whereCombineDisjuncts(
120415  SrcList *pSrc,         /* the FROM clause */
120416  WhereClause *pWC,      /* The complete WHERE clause */
120417  WhereTerm *pOne,       /* First disjunct */
120418  WhereTerm *pTwo        /* Second disjunct */
120419){
120420  u16 eOp = pOne->eOperator | pTwo->eOperator;
120421  sqlite3 *db;           /* Database connection (for malloc) */
120422  Expr *pNew;            /* New virtual expression */
120423  int op;                /* Operator for the combined expression */
120424  int idxNew;            /* Index in pWC of the next virtual term */
120425
120426  if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
120427  if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
120428  if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
120429   && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
120430  assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
120431  assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
120432  if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
120433  if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
120434  /* If we reach this point, it means the two subterms can be combined */
120435  if( (eOp & (eOp-1))!=0 ){
120436    if( eOp & (WO_LT|WO_LE) ){
120437      eOp = WO_LE;
120438    }else{
120439      assert( eOp & (WO_GT|WO_GE) );
120440      eOp = WO_GE;
120441    }
120442  }
120443  db = pWC->pWInfo->pParse->db;
120444  pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
120445  if( pNew==0 ) return;
120446  for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
120447  pNew->op = op;
120448  idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
120449  exprAnalyze(pSrc, pWC, idxNew);
120450}
120451
120452#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
120453/*
120454** Analyze a term that consists of two or more OR-connected
120455** subterms.  So in:
120456**
120457**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
120458**                          ^^^^^^^^^^^^^^^^^^^^
120459**
120460** This routine analyzes terms such as the middle term in the above example.
120461** A WhereOrTerm object is computed and attached to the term under
120462** analysis, regardless of the outcome of the analysis.  Hence:
120463**
120464**     WhereTerm.wtFlags   |=  TERM_ORINFO
120465**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
120466**
120467** The term being analyzed must have two or more of OR-connected subterms.
120468** A single subterm might be a set of AND-connected sub-subterms.
120469** Examples of terms under analysis:
120470**
120471**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
120472**     (B)     x=expr1 OR expr2=x OR x=expr3
120473**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
120474**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
120475**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
120476**     (F)     x>A OR (x=A AND y>=B)
120477**
120478** CASE 1:
120479**
120480** If all subterms are of the form T.C=expr for some single column of C and
120481** a single table T (as shown in example B above) then create a new virtual
120482** term that is an equivalent IN expression.  In other words, if the term
120483** being analyzed is:
120484**
120485**      x = expr1  OR  expr2 = x  OR  x = expr3
120486**
120487** then create a new virtual term like this:
120488**
120489**      x IN (expr1,expr2,expr3)
120490**
120491** CASE 2:
120492**
120493** If there are exactly two disjuncts and one side has x>A and the other side
120494** has x=A (for the same x and A) then add a new virtual conjunct term to the
120495** WHERE clause of the form "x>=A".  Example:
120496**
120497**      x>A OR (x=A AND y>B)    adds:    x>=A
120498**
120499** The added conjunct can sometimes be helpful in query planning.
120500**
120501** CASE 3:
120502**
120503** If all subterms are indexable by a single table T, then set
120504**
120505**     WhereTerm.eOperator              =  WO_OR
120506**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
120507**
120508** A subterm is "indexable" if it is of the form
120509** "T.C <op> <expr>" where C is any column of table T and
120510** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
120511** A subterm is also indexable if it is an AND of two or more
120512** subsubterms at least one of which is indexable.  Indexable AND
120513** subterms have their eOperator set to WO_AND and they have
120514** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
120515**
120516** From another point of view, "indexable" means that the subterm could
120517** potentially be used with an index if an appropriate index exists.
120518** This analysis does not consider whether or not the index exists; that
120519** is decided elsewhere.  This analysis only looks at whether subterms
120520** appropriate for indexing exist.
120521**
120522** All examples A through E above satisfy case 3.  But if a term
120523** also satisfies case 1 (such as B) we know that the optimizer will
120524** always prefer case 1, so in that case we pretend that case 3 is not
120525** satisfied.
120526**
120527** It might be the case that multiple tables are indexable.  For example,
120528** (E) above is indexable on tables P, Q, and R.
120529**
120530** Terms that satisfy case 3 are candidates for lookup by using
120531** separate indices to find rowids for each subterm and composing
120532** the union of all rowids using a RowSet object.  This is similar
120533** to "bitmap indices" in other database engines.
120534**
120535** OTHERWISE:
120536**
120537** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
120538** zero.  This term is not useful for search.
120539*/
120540static void exprAnalyzeOrTerm(
120541  SrcList *pSrc,            /* the FROM clause */
120542  WhereClause *pWC,         /* the complete WHERE clause */
120543  int idxTerm               /* Index of the OR-term to be analyzed */
120544){
120545  WhereInfo *pWInfo = pWC->pWInfo;        /* WHERE clause processing context */
120546  Parse *pParse = pWInfo->pParse;         /* Parser context */
120547  sqlite3 *db = pParse->db;               /* Database connection */
120548  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
120549  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
120550  int i;                                  /* Loop counters */
120551  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
120552  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
120553  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
120554  Bitmask chngToIN;         /* Tables that might satisfy case 1 */
120555  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
120556
120557  /*
120558  ** Break the OR clause into its separate subterms.  The subterms are
120559  ** stored in a WhereClause structure containing within the WhereOrInfo
120560  ** object that is attached to the original OR clause term.
120561  */
120562  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
120563  assert( pExpr->op==TK_OR );
120564  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
120565  if( pOrInfo==0 ) return;
120566  pTerm->wtFlags |= TERM_ORINFO;
120567  pOrWc = &pOrInfo->wc;
120568  sqlite3WhereClauseInit(pOrWc, pWInfo);
120569  sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
120570  sqlite3WhereExprAnalyze(pSrc, pOrWc);
120571  if( db->mallocFailed ) return;
120572  assert( pOrWc->nTerm>=2 );
120573
120574  /*
120575  ** Compute the set of tables that might satisfy cases 1 or 3.
120576  */
120577  indexable = ~(Bitmask)0;
120578  chngToIN = ~(Bitmask)0;
120579  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
120580    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
120581      WhereAndInfo *pAndInfo;
120582      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
120583      chngToIN = 0;
120584      pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
120585      if( pAndInfo ){
120586        WhereClause *pAndWC;
120587        WhereTerm *pAndTerm;
120588        int j;
120589        Bitmask b = 0;
120590        pOrTerm->u.pAndInfo = pAndInfo;
120591        pOrTerm->wtFlags |= TERM_ANDINFO;
120592        pOrTerm->eOperator = WO_AND;
120593        pAndWC = &pAndInfo->wc;
120594        sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
120595        sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
120596        sqlite3WhereExprAnalyze(pSrc, pAndWC);
120597        pAndWC->pOuter = pWC;
120598        testcase( db->mallocFailed );
120599        if( !db->mallocFailed ){
120600          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
120601            assert( pAndTerm->pExpr );
120602            if( allowedOp(pAndTerm->pExpr->op) ){
120603              b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
120604            }
120605          }
120606        }
120607        indexable &= b;
120608      }
120609    }else if( pOrTerm->wtFlags & TERM_COPIED ){
120610      /* Skip this term for now.  We revisit it when we process the
120611      ** corresponding TERM_VIRTUAL term */
120612    }else{
120613      Bitmask b;
120614      b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
120615      if( pOrTerm->wtFlags & TERM_VIRTUAL ){
120616        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
120617        b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
120618      }
120619      indexable &= b;
120620      if( (pOrTerm->eOperator & WO_EQ)==0 ){
120621        chngToIN = 0;
120622      }else{
120623        chngToIN &= b;
120624      }
120625    }
120626  }
120627
120628  /*
120629  ** Record the set of tables that satisfy case 3.  The set might be
120630  ** empty.
120631  */
120632  pOrInfo->indexable = indexable;
120633  pTerm->eOperator = indexable==0 ? 0 : WO_OR;
120634
120635  /* For a two-way OR, attempt to implementation case 2.
120636  */
120637  if( indexable && pOrWc->nTerm==2 ){
120638    int iOne = 0;
120639    WhereTerm *pOne;
120640    while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
120641      int iTwo = 0;
120642      WhereTerm *pTwo;
120643      while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
120644        whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
120645      }
120646    }
120647  }
120648
120649  /*
120650  ** chngToIN holds a set of tables that *might* satisfy case 1.  But
120651  ** we have to do some additional checking to see if case 1 really
120652  ** is satisfied.
120653  **
120654  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
120655  ** that there is no possibility of transforming the OR clause into an
120656  ** IN operator because one or more terms in the OR clause contain
120657  ** something other than == on a column in the single table.  The 1-bit
120658  ** case means that every term of the OR clause is of the form
120659  ** "table.column=expr" for some single table.  The one bit that is set
120660  ** will correspond to the common table.  We still need to check to make
120661  ** sure the same column is used on all terms.  The 2-bit case is when
120662  ** the all terms are of the form "table1.column=table2.column".  It
120663  ** might be possible to form an IN operator with either table1.column
120664  ** or table2.column as the LHS if either is common to every term of
120665  ** the OR clause.
120666  **
120667  ** Note that terms of the form "table.column1=table.column2" (the
120668  ** same table on both sizes of the ==) cannot be optimized.
120669  */
120670  if( chngToIN ){
120671    int okToChngToIN = 0;     /* True if the conversion to IN is valid */
120672    int iColumn = -1;         /* Column index on lhs of IN operator */
120673    int iCursor = -1;         /* Table cursor common to all terms */
120674    int j = 0;                /* Loop counter */
120675
120676    /* Search for a table and column that appears on one side or the
120677    ** other of the == operator in every subterm.  That table and column
120678    ** will be recorded in iCursor and iColumn.  There might not be any
120679    ** such table and column.  Set okToChngToIN if an appropriate table
120680    ** and column is found but leave okToChngToIN false if not found.
120681    */
120682    for(j=0; j<2 && !okToChngToIN; j++){
120683      pOrTerm = pOrWc->a;
120684      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
120685        assert( pOrTerm->eOperator & WO_EQ );
120686        pOrTerm->wtFlags &= ~TERM_OR_OK;
120687        if( pOrTerm->leftCursor==iCursor ){
120688          /* This is the 2-bit case and we are on the second iteration and
120689          ** current term is from the first iteration.  So skip this term. */
120690          assert( j==1 );
120691          continue;
120692        }
120693        if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
120694                                            pOrTerm->leftCursor))==0 ){
120695          /* This term must be of the form t1.a==t2.b where t2 is in the
120696          ** chngToIN set but t1 is not.  This term will be either preceded
120697          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
120698          ** and use its inversion. */
120699          testcase( pOrTerm->wtFlags & TERM_COPIED );
120700          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
120701          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
120702          continue;
120703        }
120704        iColumn = pOrTerm->u.leftColumn;
120705        iCursor = pOrTerm->leftCursor;
120706        break;
120707      }
120708      if( i<0 ){
120709        /* No candidate table+column was found.  This can only occur
120710        ** on the second iteration */
120711        assert( j==1 );
120712        assert( IsPowerOfTwo(chngToIN) );
120713        assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
120714        break;
120715      }
120716      testcase( j==1 );
120717
120718      /* We have found a candidate table and column.  Check to see if that
120719      ** table and column is common to every term in the OR clause */
120720      okToChngToIN = 1;
120721      for(; i>=0 && okToChngToIN; i--, pOrTerm++){
120722        assert( pOrTerm->eOperator & WO_EQ );
120723        if( pOrTerm->leftCursor!=iCursor ){
120724          pOrTerm->wtFlags &= ~TERM_OR_OK;
120725        }else if( pOrTerm->u.leftColumn!=iColumn ){
120726          okToChngToIN = 0;
120727        }else{
120728          int affLeft, affRight;
120729          /* If the right-hand side is also a column, then the affinities
120730          ** of both right and left sides must be such that no type
120731          ** conversions are required on the right.  (Ticket #2249)
120732          */
120733          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
120734          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
120735          if( affRight!=0 && affRight!=affLeft ){
120736            okToChngToIN = 0;
120737          }else{
120738            pOrTerm->wtFlags |= TERM_OR_OK;
120739          }
120740        }
120741      }
120742    }
120743
120744    /* At this point, okToChngToIN is true if original pTerm satisfies
120745    ** case 1.  In that case, construct a new virtual term that is
120746    ** pTerm converted into an IN operator.
120747    */
120748    if( okToChngToIN ){
120749      Expr *pDup;            /* A transient duplicate expression */
120750      ExprList *pList = 0;   /* The RHS of the IN operator */
120751      Expr *pLeft = 0;       /* The LHS of the IN operator */
120752      Expr *pNew;            /* The complete IN operator */
120753
120754      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
120755        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
120756        assert( pOrTerm->eOperator & WO_EQ );
120757        assert( pOrTerm->leftCursor==iCursor );
120758        assert( pOrTerm->u.leftColumn==iColumn );
120759        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
120760        pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
120761        pLeft = pOrTerm->pExpr->pLeft;
120762      }
120763      assert( pLeft!=0 );
120764      pDup = sqlite3ExprDup(db, pLeft, 0);
120765      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
120766      if( pNew ){
120767        int idxNew;
120768        transferJoinMarkings(pNew, pExpr);
120769        assert( !ExprHasProperty(pNew, EP_xIsSelect) );
120770        pNew->x.pList = pList;
120771        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
120772        testcase( idxNew==0 );
120773        exprAnalyze(pSrc, pWC, idxNew);
120774        pTerm = &pWC->a[idxTerm];
120775        markTermAsChild(pWC, idxNew, idxTerm);
120776      }else{
120777        sqlite3ExprListDelete(db, pList);
120778      }
120779      pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 3 */
120780    }
120781  }
120782}
120783#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
120784
120785/*
120786** We already know that pExpr is a binary operator where both operands are
120787** column references.  This routine checks to see if pExpr is an equivalence
120788** relation:
120789**   1.  The SQLITE_Transitive optimization must be enabled
120790**   2.  Must be either an == or an IS operator
120791**   3.  Not originating in the ON clause of an OUTER JOIN
120792**   4.  The affinities of A and B must be compatible
120793**   5a. Both operands use the same collating sequence OR
120794**   5b. The overall collating sequence is BINARY
120795** If this routine returns TRUE, that means that the RHS can be substituted
120796** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
120797** This is an optimization.  No harm comes from returning 0.  But if 1 is
120798** returned when it should not be, then incorrect answers might result.
120799*/
120800static int termIsEquivalence(Parse *pParse, Expr *pExpr){
120801  char aff1, aff2;
120802  CollSeq *pColl;
120803  const char *zColl1, *zColl2;
120804  if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
120805  if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
120806  if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
120807  aff1 = sqlite3ExprAffinity(pExpr->pLeft);
120808  aff2 = sqlite3ExprAffinity(pExpr->pRight);
120809  if( aff1!=aff2
120810   && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
120811  ){
120812    return 0;
120813  }
120814  pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
120815  if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
120816  pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
120817  /* Since pLeft and pRight are both a column references, their collating
120818  ** sequence should always be defined. */
120819  zColl1 = ALWAYS(pColl) ? pColl->zName : 0;
120820  pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
120821  zColl2 = ALWAYS(pColl) ? pColl->zName : 0;
120822  return sqlite3StrICmp(zColl1, zColl2)==0;
120823}
120824
120825/*
120826** Recursively walk the expressions of a SELECT statement and generate
120827** a bitmask indicating which tables are used in that expression
120828** tree.
120829*/
120830static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
120831  Bitmask mask = 0;
120832  while( pS ){
120833    SrcList *pSrc = pS->pSrc;
120834    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
120835    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
120836    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
120837    mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
120838    mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
120839    if( ALWAYS(pSrc!=0) ){
120840      int i;
120841      for(i=0; i<pSrc->nSrc; i++){
120842        mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
120843        mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
120844      }
120845    }
120846    pS = pS->pPrior;
120847  }
120848  return mask;
120849}
120850
120851/*
120852** Expression pExpr is one operand of a comparison operator that might
120853** be useful for indexing.  This routine checks to see if pExpr appears
120854** in any index.  Return TRUE (1) if pExpr is an indexed term and return
120855** FALSE (0) if not.  If TRUE is returned, also set *piCur to the cursor
120856** number of the table that is indexed and *piColumn to the column number
120857** of the column that is indexed, or -2 if an expression is being indexed.
120858**
120859** If pExpr is a TK_COLUMN column reference, then this routine always returns
120860** true even if that particular column is not indexed, because the column
120861** might be added to an automatic index later.
120862*/
120863static int exprMightBeIndexed(
120864  SrcList *pFrom,        /* The FROM clause */
120865  Bitmask mPrereq,       /* Bitmask of FROM clause terms referenced by pExpr */
120866  Expr *pExpr,           /* An operand of a comparison operator */
120867  int *piCur,            /* Write the referenced table cursor number here */
120868  int *piColumn          /* Write the referenced table column number here */
120869){
120870  Index *pIdx;
120871  int i;
120872  int iCur;
120873  if( pExpr->op==TK_COLUMN ){
120874    *piCur = pExpr->iTable;
120875    *piColumn = pExpr->iColumn;
120876    return 1;
120877  }
120878  if( mPrereq==0 ) return 0;                 /* No table references */
120879  if( (mPrereq&(mPrereq-1))!=0 ) return 0;   /* Refs more than one table */
120880  for(i=0; mPrereq>1; i++, mPrereq>>=1){}
120881  iCur = pFrom->a[i].iCursor;
120882  for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
120883    if( pIdx->aColExpr==0 ) continue;
120884    for(i=0; i<pIdx->nKeyCol; i++){
120885      if( pIdx->aiColumn[i]!=(-2) ) continue;
120886      if( sqlite3ExprCompare(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
120887        *piCur = iCur;
120888        *piColumn = -2;
120889        return 1;
120890      }
120891    }
120892  }
120893  return 0;
120894}
120895
120896/*
120897** The input to this routine is an WhereTerm structure with only the
120898** "pExpr" field filled in.  The job of this routine is to analyze the
120899** subexpression and populate all the other fields of the WhereTerm
120900** structure.
120901**
120902** If the expression is of the form "<expr> <op> X" it gets commuted
120903** to the standard form of "X <op> <expr>".
120904**
120905** If the expression is of the form "X <op> Y" where both X and Y are
120906** columns, then the original expression is unchanged and a new virtual
120907** term of the form "Y <op> X" is added to the WHERE clause and
120908** analyzed separately.  The original term is marked with TERM_COPIED
120909** and the new term is marked with TERM_DYNAMIC (because it's pExpr
120910** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
120911** is a commuted copy of a prior term.)  The original term has nChild=1
120912** and the copy has idxParent set to the index of the original term.
120913*/
120914static void exprAnalyze(
120915  SrcList *pSrc,            /* the FROM clause */
120916  WhereClause *pWC,         /* the WHERE clause */
120917  int idxTerm               /* Index of the term to be analyzed */
120918){
120919  WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
120920  WhereTerm *pTerm;                /* The term to be analyzed */
120921  WhereMaskSet *pMaskSet;          /* Set of table index masks */
120922  Expr *pExpr;                     /* The expression to be analyzed */
120923  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
120924  Bitmask prereqAll;               /* Prerequesites of pExpr */
120925  Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
120926  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
120927  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
120928  int noCase = 0;                  /* uppercase equivalent to lowercase */
120929  int op;                          /* Top-level operator.  pExpr->op */
120930  Parse *pParse = pWInfo->pParse;  /* Parsing context */
120931  sqlite3 *db = pParse->db;        /* Database connection */
120932
120933  if( db->mallocFailed ){
120934    return;
120935  }
120936  pTerm = &pWC->a[idxTerm];
120937  pMaskSet = &pWInfo->sMaskSet;
120938  pExpr = pTerm->pExpr;
120939  assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
120940  prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
120941  op = pExpr->op;
120942  if( op==TK_IN ){
120943    assert( pExpr->pRight==0 );
120944    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
120945      pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
120946    }else{
120947      pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
120948    }
120949  }else if( op==TK_ISNULL ){
120950    pTerm->prereqRight = 0;
120951  }else{
120952    pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
120953  }
120954  prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
120955  if( ExprHasProperty(pExpr, EP_FromJoin) ){
120956    Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
120957    prereqAll |= x;
120958    extraRight = x-1;  /* ON clause terms may not be used with an index
120959                       ** on left table of a LEFT JOIN.  Ticket #3015 */
120960  }
120961  pTerm->prereqAll = prereqAll;
120962  pTerm->leftCursor = -1;
120963  pTerm->iParent = -1;
120964  pTerm->eOperator = 0;
120965  if( allowedOp(op) ){
120966    int iCur, iColumn;
120967    Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
120968    Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
120969    u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
120970    if( exprMightBeIndexed(pSrc, prereqLeft, pLeft, &iCur, &iColumn) ){
120971      pTerm->leftCursor = iCur;
120972      pTerm->u.leftColumn = iColumn;
120973      pTerm->eOperator = operatorMask(op) & opMask;
120974    }
120975    if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
120976    if( pRight
120977     && exprMightBeIndexed(pSrc, pTerm->prereqRight, pRight, &iCur, &iColumn)
120978    ){
120979      WhereTerm *pNew;
120980      Expr *pDup;
120981      u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
120982      if( pTerm->leftCursor>=0 ){
120983        int idxNew;
120984        pDup = sqlite3ExprDup(db, pExpr, 0);
120985        if( db->mallocFailed ){
120986          sqlite3ExprDelete(db, pDup);
120987          return;
120988        }
120989        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
120990        if( idxNew==0 ) return;
120991        pNew = &pWC->a[idxNew];
120992        markTermAsChild(pWC, idxNew, idxTerm);
120993        if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
120994        pTerm = &pWC->a[idxTerm];
120995        pTerm->wtFlags |= TERM_COPIED;
120996
120997        if( termIsEquivalence(pParse, pDup) ){
120998          pTerm->eOperator |= WO_EQUIV;
120999          eExtraOp = WO_EQUIV;
121000        }
121001      }else{
121002        pDup = pExpr;
121003        pNew = pTerm;
121004      }
121005      exprCommute(pParse, pDup);
121006      pNew->leftCursor = iCur;
121007      pNew->u.leftColumn = iColumn;
121008      testcase( (prereqLeft | extraRight) != prereqLeft );
121009      pNew->prereqRight = prereqLeft | extraRight;
121010      pNew->prereqAll = prereqAll;
121011      pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
121012    }
121013  }
121014
121015#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
121016  /* If a term is the BETWEEN operator, create two new virtual terms
121017  ** that define the range that the BETWEEN implements.  For example:
121018  **
121019  **      a BETWEEN b AND c
121020  **
121021  ** is converted into:
121022  **
121023  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
121024  **
121025  ** The two new terms are added onto the end of the WhereClause object.
121026  ** The new terms are "dynamic" and are children of the original BETWEEN
121027  ** term.  That means that if the BETWEEN term is coded, the children are
121028  ** skipped.  Or, if the children are satisfied by an index, the original
121029  ** BETWEEN term is skipped.
121030  */
121031  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
121032    ExprList *pList = pExpr->x.pList;
121033    int i;
121034    static const u8 ops[] = {TK_GE, TK_LE};
121035    assert( pList!=0 );
121036    assert( pList->nExpr==2 );
121037    for(i=0; i<2; i++){
121038      Expr *pNewExpr;
121039      int idxNew;
121040      pNewExpr = sqlite3PExpr(pParse, ops[i],
121041                             sqlite3ExprDup(db, pExpr->pLeft, 0),
121042                             sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
121043      transferJoinMarkings(pNewExpr, pExpr);
121044      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
121045      testcase( idxNew==0 );
121046      exprAnalyze(pSrc, pWC, idxNew);
121047      pTerm = &pWC->a[idxTerm];
121048      markTermAsChild(pWC, idxNew, idxTerm);
121049    }
121050  }
121051#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
121052
121053#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
121054  /* Analyze a term that is composed of two or more subterms connected by
121055  ** an OR operator.
121056  */
121057  else if( pExpr->op==TK_OR ){
121058    assert( pWC->op==TK_AND );
121059    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
121060    pTerm = &pWC->a[idxTerm];
121061  }
121062#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
121063
121064#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
121065  /* Add constraints to reduce the search space on a LIKE or GLOB
121066  ** operator.
121067  **
121068  ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
121069  **
121070  **          x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
121071  **
121072  ** The last character of the prefix "abc" is incremented to form the
121073  ** termination condition "abd".  If case is not significant (the default
121074  ** for LIKE) then the lower-bound is made all uppercase and the upper-
121075  ** bound is made all lowercase so that the bounds also work when comparing
121076  ** BLOBs.
121077  */
121078  if( pWC->op==TK_AND
121079   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
121080  ){
121081    Expr *pLeft;       /* LHS of LIKE/GLOB operator */
121082    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
121083    Expr *pNewExpr1;
121084    Expr *pNewExpr2;
121085    int idxNew1;
121086    int idxNew2;
121087    const char *zCollSeqName;     /* Name of collating sequence */
121088    const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
121089
121090    pLeft = pExpr->x.pList->a[1].pExpr;
121091    pStr2 = sqlite3ExprDup(db, pStr1, 0);
121092
121093    /* Convert the lower bound to upper-case and the upper bound to
121094    ** lower-case (upper-case is less than lower-case in ASCII) so that
121095    ** the range constraints also work for BLOBs
121096    */
121097    if( noCase && !pParse->db->mallocFailed ){
121098      int i;
121099      char c;
121100      pTerm->wtFlags |= TERM_LIKE;
121101      for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
121102        pStr1->u.zToken[i] = sqlite3Toupper(c);
121103        pStr2->u.zToken[i] = sqlite3Tolower(c);
121104      }
121105    }
121106
121107    if( !db->mallocFailed ){
121108      u8 c, *pC;       /* Last character before the first wildcard */
121109      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
121110      c = *pC;
121111      if( noCase ){
121112        /* The point is to increment the last character before the first
121113        ** wildcard.  But if we increment '@', that will push it into the
121114        ** alphabetic range where case conversions will mess up the
121115        ** inequality.  To avoid this, make sure to also run the full
121116        ** LIKE on all candidate expressions by clearing the isComplete flag
121117        */
121118        if( c=='A'-1 ) isComplete = 0;
121119        c = sqlite3UpperToLower[c];
121120      }
121121      *pC = c + 1;
121122    }
121123    zCollSeqName = noCase ? "NOCASE" : "BINARY";
121124    pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
121125    pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
121126           sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
121127           pStr1, 0);
121128    transferJoinMarkings(pNewExpr1, pExpr);
121129    idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
121130    testcase( idxNew1==0 );
121131    exprAnalyze(pSrc, pWC, idxNew1);
121132    pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
121133    pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
121134           sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
121135           pStr2, 0);
121136    transferJoinMarkings(pNewExpr2, pExpr);
121137    idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
121138    testcase( idxNew2==0 );
121139    exprAnalyze(pSrc, pWC, idxNew2);
121140    pTerm = &pWC->a[idxTerm];
121141    if( isComplete ){
121142      markTermAsChild(pWC, idxNew1, idxTerm);
121143      markTermAsChild(pWC, idxNew2, idxTerm);
121144    }
121145  }
121146#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
121147
121148#ifndef SQLITE_OMIT_VIRTUALTABLE
121149  /* Add a WO_MATCH auxiliary term to the constraint set if the
121150  ** current expression is of the form:  column MATCH expr.
121151  ** This information is used by the xBestIndex methods of
121152  ** virtual tables.  The native query optimizer does not attempt
121153  ** to do anything with MATCH functions.
121154  */
121155  if( isMatchOfColumn(pExpr) ){
121156    int idxNew;
121157    Expr *pRight, *pLeft;
121158    WhereTerm *pNewTerm;
121159    Bitmask prereqColumn, prereqExpr;
121160
121161    pRight = pExpr->x.pList->a[0].pExpr;
121162    pLeft = pExpr->x.pList->a[1].pExpr;
121163    prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
121164    prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
121165    if( (prereqExpr & prereqColumn)==0 ){
121166      Expr *pNewExpr;
121167      pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
121168                              0, sqlite3ExprDup(db, pRight, 0), 0);
121169      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
121170      testcase( idxNew==0 );
121171      pNewTerm = &pWC->a[idxNew];
121172      pNewTerm->prereqRight = prereqExpr;
121173      pNewTerm->leftCursor = pLeft->iTable;
121174      pNewTerm->u.leftColumn = pLeft->iColumn;
121175      pNewTerm->eOperator = WO_MATCH;
121176      markTermAsChild(pWC, idxNew, idxTerm);
121177      pTerm = &pWC->a[idxTerm];
121178      pTerm->wtFlags |= TERM_COPIED;
121179      pNewTerm->prereqAll = pTerm->prereqAll;
121180    }
121181  }
121182#endif /* SQLITE_OMIT_VIRTUALTABLE */
121183
121184#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
121185  /* When sqlite_stat3 histogram data is available an operator of the
121186  ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
121187  ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
121188  ** virtual term of that form.
121189  **
121190  ** Note that the virtual term must be tagged with TERM_VNULL.
121191  */
121192  if( pExpr->op==TK_NOTNULL
121193   && pExpr->pLeft->op==TK_COLUMN
121194   && pExpr->pLeft->iColumn>=0
121195   && OptimizationEnabled(db, SQLITE_Stat34)
121196  ){
121197    Expr *pNewExpr;
121198    Expr *pLeft = pExpr->pLeft;
121199    int idxNew;
121200    WhereTerm *pNewTerm;
121201
121202    pNewExpr = sqlite3PExpr(pParse, TK_GT,
121203                            sqlite3ExprDup(db, pLeft, 0),
121204                            sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
121205
121206    idxNew = whereClauseInsert(pWC, pNewExpr,
121207                              TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
121208    if( idxNew ){
121209      pNewTerm = &pWC->a[idxNew];
121210      pNewTerm->prereqRight = 0;
121211      pNewTerm->leftCursor = pLeft->iTable;
121212      pNewTerm->u.leftColumn = pLeft->iColumn;
121213      pNewTerm->eOperator = WO_GT;
121214      markTermAsChild(pWC, idxNew, idxTerm);
121215      pTerm = &pWC->a[idxTerm];
121216      pTerm->wtFlags |= TERM_COPIED;
121217      pNewTerm->prereqAll = pTerm->prereqAll;
121218    }
121219  }
121220#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
121221
121222  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
121223  ** an index for tables to the left of the join.
121224  */
121225  pTerm->prereqRight |= extraRight;
121226}
121227
121228/***************************************************************************
121229** Routines with file scope above.  Interface to the rest of the where.c
121230** subsystem follows.
121231***************************************************************************/
121232
121233/*
121234** This routine identifies subexpressions in the WHERE clause where
121235** each subexpression is separated by the AND operator or some other
121236** operator specified in the op parameter.  The WhereClause structure
121237** is filled with pointers to subexpressions.  For example:
121238**
121239**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
121240**           \________/     \_______________/     \________________/
121241**            slot[0]            slot[1]               slot[2]
121242**
121243** The original WHERE clause in pExpr is unaltered.  All this routine
121244** does is make slot[] entries point to substructure within pExpr.
121245**
121246** In the previous sentence and in the diagram, "slot[]" refers to
121247** the WhereClause.a[] array.  The slot[] array grows as needed to contain
121248** all terms of the WHERE clause.
121249*/
121250SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
121251  Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
121252  pWC->op = op;
121253  if( pE2==0 ) return;
121254  if( pE2->op!=op ){
121255    whereClauseInsert(pWC, pExpr, 0);
121256  }else{
121257    sqlite3WhereSplit(pWC, pE2->pLeft, op);
121258    sqlite3WhereSplit(pWC, pE2->pRight, op);
121259  }
121260}
121261
121262/*
121263** Initialize a preallocated WhereClause structure.
121264*/
121265SQLITE_PRIVATE void sqlite3WhereClauseInit(
121266  WhereClause *pWC,        /* The WhereClause to be initialized */
121267  WhereInfo *pWInfo        /* The WHERE processing context */
121268){
121269  pWC->pWInfo = pWInfo;
121270  pWC->pOuter = 0;
121271  pWC->nTerm = 0;
121272  pWC->nSlot = ArraySize(pWC->aStatic);
121273  pWC->a = pWC->aStatic;
121274}
121275
121276/*
121277** Deallocate a WhereClause structure.  The WhereClause structure
121278** itself is not freed.  This routine is the inverse of sqlite3WhereClauseInit().
121279*/
121280SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
121281  int i;
121282  WhereTerm *a;
121283  sqlite3 *db = pWC->pWInfo->pParse->db;
121284  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
121285    if( a->wtFlags & TERM_DYNAMIC ){
121286      sqlite3ExprDelete(db, a->pExpr);
121287    }
121288    if( a->wtFlags & TERM_ORINFO ){
121289      whereOrInfoDelete(db, a->u.pOrInfo);
121290    }else if( a->wtFlags & TERM_ANDINFO ){
121291      whereAndInfoDelete(db, a->u.pAndInfo);
121292    }
121293  }
121294  if( pWC->a!=pWC->aStatic ){
121295    sqlite3DbFree(db, pWC->a);
121296  }
121297}
121298
121299
121300/*
121301** These routines walk (recursively) an expression tree and generate
121302** a bitmask indicating which tables are used in that expression
121303** tree.
121304*/
121305SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
121306  Bitmask mask = 0;
121307  if( p==0 ) return 0;
121308  if( p->op==TK_COLUMN ){
121309    mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
121310    return mask;
121311  }
121312  mask = sqlite3WhereExprUsage(pMaskSet, p->pRight);
121313  mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
121314  if( ExprHasProperty(p, EP_xIsSelect) ){
121315    mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
121316  }else{
121317    mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
121318  }
121319  return mask;
121320}
121321SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
121322  int i;
121323  Bitmask mask = 0;
121324  if( pList ){
121325    for(i=0; i<pList->nExpr; i++){
121326      mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
121327    }
121328  }
121329  return mask;
121330}
121331
121332
121333/*
121334** Call exprAnalyze on all terms in a WHERE clause.
121335**
121336** Note that exprAnalyze() might add new virtual terms onto the
121337** end of the WHERE clause.  We do not want to analyze these new
121338** virtual terms, so start analyzing at the end and work forward
121339** so that the added virtual terms are never processed.
121340*/
121341SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
121342  SrcList *pTabList,       /* the FROM clause */
121343  WhereClause *pWC         /* the WHERE clause to be analyzed */
121344){
121345  int i;
121346  for(i=pWC->nTerm-1; i>=0; i--){
121347    exprAnalyze(pTabList, pWC, i);
121348  }
121349}
121350
121351/*
121352** For table-valued-functions, transform the function arguments into
121353** new WHERE clause terms.
121354**
121355** Each function argument translates into an equality constraint against
121356** a HIDDEN column in the table.
121357*/
121358SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
121359  Parse *pParse,                    /* Parsing context */
121360  struct SrcList_item *pItem,       /* The FROM clause term to process */
121361  WhereClause *pWC                  /* Xfer function arguments to here */
121362){
121363  Table *pTab;
121364  int j, k;
121365  ExprList *pArgs;
121366  Expr *pColRef;
121367  Expr *pTerm;
121368  if( pItem->fg.isTabFunc==0 ) return;
121369  pTab = pItem->pTab;
121370  assert( pTab!=0 );
121371  pArgs = pItem->u1.pFuncArg;
121372  assert( pArgs!=0 );
121373  for(j=k=0; j<pArgs->nExpr; j++){
121374    while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){ k++; }
121375    if( k>=pTab->nCol ){
121376      sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
121377                      pTab->zName, j);
121378      return;
121379    }
121380    pColRef = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
121381    if( pColRef==0 ) return;
121382    pColRef->iTable = pItem->iCursor;
121383    pColRef->iColumn = k++;
121384    pColRef->pTab = pTab;
121385    pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
121386                         sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
121387    whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
121388  }
121389}
121390
121391/************** End of whereexpr.c *******************************************/
121392/************** Begin file where.c *******************************************/
121393/*
121394** 2001 September 15
121395**
121396** The author disclaims copyright to this source code.  In place of
121397** a legal notice, here is a blessing:
121398**
121399**    May you do good and not evil.
121400**    May you find forgiveness for yourself and forgive others.
121401**    May you share freely, never taking more than you give.
121402**
121403*************************************************************************
121404** This module contains C code that generates VDBE code used to process
121405** the WHERE clause of SQL statements.  This module is responsible for
121406** generating the code that loops through a table looking for applicable
121407** rows.  Indices are selected and used to speed the search when doing
121408** so is applicable.  Because this module is responsible for selecting
121409** indices, you might also think of this module as the "query optimizer".
121410*/
121411/* #include "sqliteInt.h" */
121412/* #include "whereInt.h" */
121413
121414/* Forward declaration of methods */
121415static int whereLoopResize(sqlite3*, WhereLoop*, int);
121416
121417/* Test variable that can be set to enable WHERE tracing */
121418#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
121419/***/ int sqlite3WhereTrace = 0;
121420#endif
121421
121422
121423/*
121424** Return the estimated number of output rows from a WHERE clause
121425*/
121426SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
121427  return sqlite3LogEstToInt(pWInfo->nRowOut);
121428}
121429
121430/*
121431** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
121432** WHERE clause returns outputs for DISTINCT processing.
121433*/
121434SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
121435  return pWInfo->eDistinct;
121436}
121437
121438/*
121439** Return TRUE if the WHERE clause returns rows in ORDER BY order.
121440** Return FALSE if the output needs to be sorted.
121441*/
121442SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
121443  return pWInfo->nOBSat;
121444}
121445
121446/*
121447** Return the VDBE address or label to jump to in order to continue
121448** immediately with the next row of a WHERE clause.
121449*/
121450SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
121451  assert( pWInfo->iContinue!=0 );
121452  return pWInfo->iContinue;
121453}
121454
121455/*
121456** Return the VDBE address or label to jump to in order to break
121457** out of a WHERE loop.
121458*/
121459SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
121460  return pWInfo->iBreak;
121461}
121462
121463/*
121464** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
121465** operate directly on the rowis returned by a WHERE clause.  Return
121466** ONEPASS_SINGLE (1) if the statement can operation directly because only
121467** a single row is to be changed.  Return ONEPASS_MULTI (2) if the one-pass
121468** optimization can be used on multiple
121469**
121470** If the ONEPASS optimization is used (if this routine returns true)
121471** then also write the indices of open cursors used by ONEPASS
121472** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data
121473** table and iaCur[1] gets the cursor used by an auxiliary index.
121474** Either value may be -1, indicating that cursor is not used.
121475** Any cursors returned will have been opened for writing.
121476**
121477** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
121478** unable to use the ONEPASS optimization.
121479*/
121480SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
121481  memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
121482#ifdef WHERETRACE_ENABLED
121483  if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
121484    sqlite3DebugPrintf("%s cursors: %d %d\n",
121485         pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
121486         aiCur[0], aiCur[1]);
121487  }
121488#endif
121489  return pWInfo->eOnePass;
121490}
121491
121492/*
121493** Move the content of pSrc into pDest
121494*/
121495static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
121496  pDest->n = pSrc->n;
121497  memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
121498}
121499
121500/*
121501** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
121502**
121503** The new entry might overwrite an existing entry, or it might be
121504** appended, or it might be discarded.  Do whatever is the right thing
121505** so that pSet keeps the N_OR_COST best entries seen so far.
121506*/
121507static int whereOrInsert(
121508  WhereOrSet *pSet,      /* The WhereOrSet to be updated */
121509  Bitmask prereq,        /* Prerequisites of the new entry */
121510  LogEst rRun,           /* Run-cost of the new entry */
121511  LogEst nOut            /* Number of outputs for the new entry */
121512){
121513  u16 i;
121514  WhereOrCost *p;
121515  for(i=pSet->n, p=pSet->a; i>0; i--, p++){
121516    if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
121517      goto whereOrInsert_done;
121518    }
121519    if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
121520      return 0;
121521    }
121522  }
121523  if( pSet->n<N_OR_COST ){
121524    p = &pSet->a[pSet->n++];
121525    p->nOut = nOut;
121526  }else{
121527    p = pSet->a;
121528    for(i=1; i<pSet->n; i++){
121529      if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
121530    }
121531    if( p->rRun<=rRun ) return 0;
121532  }
121533whereOrInsert_done:
121534  p->prereq = prereq;
121535  p->rRun = rRun;
121536  if( p->nOut>nOut ) p->nOut = nOut;
121537  return 1;
121538}
121539
121540/*
121541** Return the bitmask for the given cursor number.  Return 0 if
121542** iCursor is not in the set.
121543*/
121544SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
121545  int i;
121546  assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
121547  for(i=0; i<pMaskSet->n; i++){
121548    if( pMaskSet->ix[i]==iCursor ){
121549      return MASKBIT(i);
121550    }
121551  }
121552  return 0;
121553}
121554
121555/*
121556** Create a new mask for cursor iCursor.
121557**
121558** There is one cursor per table in the FROM clause.  The number of
121559** tables in the FROM clause is limited by a test early in the
121560** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
121561** array will never overflow.
121562*/
121563static void createMask(WhereMaskSet *pMaskSet, int iCursor){
121564  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
121565  pMaskSet->ix[pMaskSet->n++] = iCursor;
121566}
121567
121568/*
121569** Advance to the next WhereTerm that matches according to the criteria
121570** established when the pScan object was initialized by whereScanInit().
121571** Return NULL if there are no more matching WhereTerms.
121572*/
121573static WhereTerm *whereScanNext(WhereScan *pScan){
121574  int iCur;            /* The cursor on the LHS of the term */
121575  i16 iColumn;         /* The column on the LHS of the term.  -1 for IPK */
121576  Expr *pX;            /* An expression being tested */
121577  WhereClause *pWC;    /* Shorthand for pScan->pWC */
121578  WhereTerm *pTerm;    /* The term being tested */
121579  int k = pScan->k;    /* Where to start scanning */
121580
121581  while( pScan->iEquiv<=pScan->nEquiv ){
121582    iCur = pScan->aiCur[pScan->iEquiv-1];
121583    iColumn = pScan->aiColumn[pScan->iEquiv-1];
121584    if( iColumn==XN_EXPR && pScan->pIdxExpr==0 ) return 0;
121585    while( (pWC = pScan->pWC)!=0 ){
121586      for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
121587        if( pTerm->leftCursor==iCur
121588         && pTerm->u.leftColumn==iColumn
121589         && (iColumn!=XN_EXPR
121590             || sqlite3ExprCompare(pTerm->pExpr->pLeft,pScan->pIdxExpr,iCur)==0)
121591         && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
121592        ){
121593          if( (pTerm->eOperator & WO_EQUIV)!=0
121594           && pScan->nEquiv<ArraySize(pScan->aiCur)
121595           && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
121596          ){
121597            int j;
121598            for(j=0; j<pScan->nEquiv; j++){
121599              if( pScan->aiCur[j]==pX->iTable
121600               && pScan->aiColumn[j]==pX->iColumn ){
121601                  break;
121602              }
121603            }
121604            if( j==pScan->nEquiv ){
121605              pScan->aiCur[j] = pX->iTable;
121606              pScan->aiColumn[j] = pX->iColumn;
121607              pScan->nEquiv++;
121608            }
121609          }
121610          if( (pTerm->eOperator & pScan->opMask)!=0 ){
121611            /* Verify the affinity and collating sequence match */
121612            if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
121613              CollSeq *pColl;
121614              Parse *pParse = pWC->pWInfo->pParse;
121615              pX = pTerm->pExpr;
121616              if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
121617                continue;
121618              }
121619              assert(pX->pLeft);
121620              pColl = sqlite3BinaryCompareCollSeq(pParse,
121621                                                  pX->pLeft, pX->pRight);
121622              if( pColl==0 ) pColl = pParse->db->pDfltColl;
121623              if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
121624                continue;
121625              }
121626            }
121627            if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
121628             && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
121629             && pX->iTable==pScan->aiCur[0]
121630             && pX->iColumn==pScan->aiColumn[0]
121631            ){
121632              testcase( pTerm->eOperator & WO_IS );
121633              continue;
121634            }
121635            pScan->k = k+1;
121636            return pTerm;
121637          }
121638        }
121639      }
121640      pScan->pWC = pScan->pWC->pOuter;
121641      k = 0;
121642    }
121643    pScan->pWC = pScan->pOrigWC;
121644    k = 0;
121645    pScan->iEquiv++;
121646  }
121647  return 0;
121648}
121649
121650/*
121651** Initialize a WHERE clause scanner object.  Return a pointer to the
121652** first match.  Return NULL if there are no matches.
121653**
121654** The scanner will be searching the WHERE clause pWC.  It will look
121655** for terms of the form "X <op> <expr>" where X is column iColumn of table
121656** iCur.  The <op> must be one of the operators described by opMask.
121657**
121658** If the search is for X and the WHERE clause contains terms of the
121659** form X=Y then this routine might also return terms of the form
121660** "Y <op> <expr>".  The number of levels of transitivity is limited,
121661** but is enough to handle most commonly occurring SQL statements.
121662**
121663** If X is not the INTEGER PRIMARY KEY then X must be compatible with
121664** index pIdx.
121665*/
121666static WhereTerm *whereScanInit(
121667  WhereScan *pScan,       /* The WhereScan object being initialized */
121668  WhereClause *pWC,       /* The WHERE clause to be scanned */
121669  int iCur,               /* Cursor to scan for */
121670  int iColumn,            /* Column to scan for */
121671  u32 opMask,             /* Operator(s) to scan for */
121672  Index *pIdx             /* Must be compatible with this index */
121673){
121674  int j = 0;
121675
121676  /* memset(pScan, 0, sizeof(*pScan)); */
121677  pScan->pOrigWC = pWC;
121678  pScan->pWC = pWC;
121679  pScan->pIdxExpr = 0;
121680  if( pIdx ){
121681    j = iColumn;
121682    iColumn = pIdx->aiColumn[j];
121683    if( iColumn==XN_EXPR ) pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
121684  }
121685  if( pIdx && iColumn>=0 ){
121686    pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
121687    pScan->zCollName = pIdx->azColl[j];
121688  }else{
121689    pScan->idxaff = 0;
121690    pScan->zCollName = 0;
121691  }
121692  pScan->opMask = opMask;
121693  pScan->k = 0;
121694  pScan->aiCur[0] = iCur;
121695  pScan->aiColumn[0] = iColumn;
121696  pScan->nEquiv = 1;
121697  pScan->iEquiv = 1;
121698  return whereScanNext(pScan);
121699}
121700
121701/*
121702** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
121703** where X is a reference to the iColumn of table iCur and <op> is one of
121704** the WO_xx operator codes specified by the op parameter.
121705** Return a pointer to the term.  Return 0 if not found.
121706**
121707** If pIdx!=0 then search for terms matching the iColumn-th column of pIdx
121708** rather than the iColumn-th column of table iCur.
121709**
121710** The term returned might by Y=<expr> if there is another constraint in
121711** the WHERE clause that specifies that X=Y.  Any such constraints will be
121712** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
121713** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
121714** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
121715** other equivalent values.  Hence a search for X will return <expr> if X=A1
121716** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
121717**
121718** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
121719** then try for the one with no dependencies on <expr> - in other words where
121720** <expr> is a constant expression of some kind.  Only return entries of
121721** the form "X <op> Y" where Y is a column in another table if no terms of
121722** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
121723** exist, try to return a term that does not use WO_EQUIV.
121724*/
121725SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
121726  WhereClause *pWC,     /* The WHERE clause to be searched */
121727  int iCur,             /* Cursor number of LHS */
121728  int iColumn,          /* Column number of LHS */
121729  Bitmask notReady,     /* RHS must not overlap with this mask */
121730  u32 op,               /* Mask of WO_xx values describing operator */
121731  Index *pIdx           /* Must be compatible with this index, if not NULL */
121732){
121733  WhereTerm *pResult = 0;
121734  WhereTerm *p;
121735  WhereScan scan;
121736
121737  p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
121738  op &= WO_EQ|WO_IS;
121739  while( p ){
121740    if( (p->prereqRight & notReady)==0 ){
121741      if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
121742        testcase( p->eOperator & WO_IS );
121743        return p;
121744      }
121745      if( pResult==0 ) pResult = p;
121746    }
121747    p = whereScanNext(&scan);
121748  }
121749  return pResult;
121750}
121751
121752/*
121753** This function searches pList for an entry that matches the iCol-th column
121754** of index pIdx.
121755**
121756** If such an expression is found, its index in pList->a[] is returned. If
121757** no expression is found, -1 is returned.
121758*/
121759static int findIndexCol(
121760  Parse *pParse,                  /* Parse context */
121761  ExprList *pList,                /* Expression list to search */
121762  int iBase,                      /* Cursor for table associated with pIdx */
121763  Index *pIdx,                    /* Index to match column of */
121764  int iCol                        /* Column of index to match */
121765){
121766  int i;
121767  const char *zColl = pIdx->azColl[iCol];
121768
121769  for(i=0; i<pList->nExpr; i++){
121770    Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
121771    if( p->op==TK_COLUMN
121772     && p->iColumn==pIdx->aiColumn[iCol]
121773     && p->iTable==iBase
121774    ){
121775      CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
121776      if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
121777        return i;
121778      }
121779    }
121780  }
121781
121782  return -1;
121783}
121784
121785/*
121786** Return TRUE if the iCol-th column of index pIdx is NOT NULL
121787*/
121788static int indexColumnNotNull(Index *pIdx, int iCol){
121789  int j;
121790  assert( pIdx!=0 );
121791  assert( iCol>=0 && iCol<pIdx->nColumn );
121792  j = pIdx->aiColumn[iCol];
121793  if( j>=0 ){
121794    return pIdx->pTable->aCol[j].notNull;
121795  }else if( j==(-1) ){
121796    return 1;
121797  }else{
121798    assert( j==(-2) );
121799    return 0;  /* Assume an indexed expression can always yield a NULL */
121800
121801  }
121802}
121803
121804/*
121805** Return true if the DISTINCT expression-list passed as the third argument
121806** is redundant.
121807**
121808** A DISTINCT list is redundant if any subset of the columns in the
121809** DISTINCT list are collectively unique and individually non-null.
121810*/
121811static int isDistinctRedundant(
121812  Parse *pParse,            /* Parsing context */
121813  SrcList *pTabList,        /* The FROM clause */
121814  WhereClause *pWC,         /* The WHERE clause */
121815  ExprList *pDistinct       /* The result set that needs to be DISTINCT */
121816){
121817  Table *pTab;
121818  Index *pIdx;
121819  int i;
121820  int iBase;
121821
121822  /* If there is more than one table or sub-select in the FROM clause of
121823  ** this query, then it will not be possible to show that the DISTINCT
121824  ** clause is redundant. */
121825  if( pTabList->nSrc!=1 ) return 0;
121826  iBase = pTabList->a[0].iCursor;
121827  pTab = pTabList->a[0].pTab;
121828
121829  /* If any of the expressions is an IPK column on table iBase, then return
121830  ** true. Note: The (p->iTable==iBase) part of this test may be false if the
121831  ** current SELECT is a correlated sub-query.
121832  */
121833  for(i=0; i<pDistinct->nExpr; i++){
121834    Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
121835    if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
121836  }
121837
121838  /* Loop through all indices on the table, checking each to see if it makes
121839  ** the DISTINCT qualifier redundant. It does so if:
121840  **
121841  **   1. The index is itself UNIQUE, and
121842  **
121843  **   2. All of the columns in the index are either part of the pDistinct
121844  **      list, or else the WHERE clause contains a term of the form "col=X",
121845  **      where X is a constant value. The collation sequences of the
121846  **      comparison and select-list expressions must match those of the index.
121847  **
121848  **   3. All of those index columns for which the WHERE clause does not
121849  **      contain a "col=X" term are subject to a NOT NULL constraint.
121850  */
121851  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
121852    if( !IsUniqueIndex(pIdx) ) continue;
121853    for(i=0; i<pIdx->nKeyCol; i++){
121854      if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
121855        if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
121856        if( indexColumnNotNull(pIdx, i)==0 ) break;
121857      }
121858    }
121859    if( i==pIdx->nKeyCol ){
121860      /* This index implies that the DISTINCT qualifier is redundant. */
121861      return 1;
121862    }
121863  }
121864
121865  return 0;
121866}
121867
121868
121869/*
121870** Estimate the logarithm of the input value to base 2.
121871*/
121872static LogEst estLog(LogEst N){
121873  return N<=10 ? 0 : sqlite3LogEst(N) - 33;
121874}
121875
121876/*
121877** Convert OP_Column opcodes to OP_Copy in previously generated code.
121878**
121879** This routine runs over generated VDBE code and translates OP_Column
121880** opcodes into OP_Copy when the table is being accessed via co-routine
121881** instead of via table lookup.
121882**
121883** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
121884** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
121885** then each OP_Rowid is transformed into an instruction to increment the
121886** value stored in its output register.
121887*/
121888static void translateColumnToCopy(
121889  Vdbe *v,            /* The VDBE containing code to translate */
121890  int iStart,         /* Translate from this opcode to the end */
121891  int iTabCur,        /* OP_Column/OP_Rowid references to this table */
121892  int iRegister,      /* The first column is in this register */
121893  int bIncrRowid      /* If non-zero, transform OP_rowid to OP_AddImm(1) */
121894){
121895  VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
121896  int iEnd = sqlite3VdbeCurrentAddr(v);
121897  for(; iStart<iEnd; iStart++, pOp++){
121898    if( pOp->p1!=iTabCur ) continue;
121899    if( pOp->opcode==OP_Column ){
121900      pOp->opcode = OP_Copy;
121901      pOp->p1 = pOp->p2 + iRegister;
121902      pOp->p2 = pOp->p3;
121903      pOp->p3 = 0;
121904    }else if( pOp->opcode==OP_Rowid ){
121905      if( bIncrRowid ){
121906        /* Increment the value stored in the P2 operand of the OP_Rowid. */
121907        pOp->opcode = OP_AddImm;
121908        pOp->p1 = pOp->p2;
121909        pOp->p2 = 1;
121910      }else{
121911        pOp->opcode = OP_Null;
121912        pOp->p1 = 0;
121913        pOp->p3 = 0;
121914      }
121915    }
121916  }
121917}
121918
121919/*
121920** Two routines for printing the content of an sqlite3_index_info
121921** structure.  Used for testing and debugging only.  If neither
121922** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
121923** are no-ops.
121924*/
121925#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
121926static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
121927  int i;
121928  if( !sqlite3WhereTrace ) return;
121929  for(i=0; i<p->nConstraint; i++){
121930    sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
121931       i,
121932       p->aConstraint[i].iColumn,
121933       p->aConstraint[i].iTermOffset,
121934       p->aConstraint[i].op,
121935       p->aConstraint[i].usable);
121936  }
121937  for(i=0; i<p->nOrderBy; i++){
121938    sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
121939       i,
121940       p->aOrderBy[i].iColumn,
121941       p->aOrderBy[i].desc);
121942  }
121943}
121944static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
121945  int i;
121946  if( !sqlite3WhereTrace ) return;
121947  for(i=0; i<p->nConstraint; i++){
121948    sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
121949       i,
121950       p->aConstraintUsage[i].argvIndex,
121951       p->aConstraintUsage[i].omit);
121952  }
121953  sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
121954  sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
121955  sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
121956  sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
121957  sqlite3DebugPrintf("  estimatedRows=%lld\n", p->estimatedRows);
121958}
121959#else
121960#define TRACE_IDX_INPUTS(A)
121961#define TRACE_IDX_OUTPUTS(A)
121962#endif
121963
121964#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
121965/*
121966** Return TRUE if the WHERE clause term pTerm is of a form where it
121967** could be used with an index to access pSrc, assuming an appropriate
121968** index existed.
121969*/
121970static int termCanDriveIndex(
121971  WhereTerm *pTerm,              /* WHERE clause term to check */
121972  struct SrcList_item *pSrc,     /* Table we are trying to access */
121973  Bitmask notReady               /* Tables in outer loops of the join */
121974){
121975  char aff;
121976  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
121977  if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
121978  if( (pTerm->prereqRight & notReady)!=0 ) return 0;
121979  if( pTerm->u.leftColumn<0 ) return 0;
121980  aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
121981  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
121982  testcase( pTerm->pExpr->op==TK_IS );
121983  return 1;
121984}
121985#endif
121986
121987
121988#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
121989/*
121990** Generate code to construct the Index object for an automatic index
121991** and to set up the WhereLevel object pLevel so that the code generator
121992** makes use of the automatic index.
121993*/
121994static void constructAutomaticIndex(
121995  Parse *pParse,              /* The parsing context */
121996  WhereClause *pWC,           /* The WHERE clause */
121997  struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
121998  Bitmask notReady,           /* Mask of cursors that are not available */
121999  WhereLevel *pLevel          /* Write new index here */
122000){
122001  int nKeyCol;                /* Number of columns in the constructed index */
122002  WhereTerm *pTerm;           /* A single term of the WHERE clause */
122003  WhereTerm *pWCEnd;          /* End of pWC->a[] */
122004  Index *pIdx;                /* Object describing the transient index */
122005  Vdbe *v;                    /* Prepared statement under construction */
122006  int addrInit;               /* Address of the initialization bypass jump */
122007  Table *pTable;              /* The table being indexed */
122008  int addrTop;                /* Top of the index fill loop */
122009  int regRecord;              /* Register holding an index record */
122010  int n;                      /* Column counter */
122011  int i;                      /* Loop counter */
122012  int mxBitCol;               /* Maximum column in pSrc->colUsed */
122013  CollSeq *pColl;             /* Collating sequence to on a column */
122014  WhereLoop *pLoop;           /* The Loop object */
122015  char *zNotUsed;             /* Extra space on the end of pIdx */
122016  Bitmask idxCols;            /* Bitmap of columns used for indexing */
122017  Bitmask extraCols;          /* Bitmap of additional columns */
122018  u8 sentWarning = 0;         /* True if a warnning has been issued */
122019  Expr *pPartial = 0;         /* Partial Index Expression */
122020  int iContinue = 0;          /* Jump here to skip excluded rows */
122021  struct SrcList_item *pTabItem;  /* FROM clause term being indexed */
122022  int addrCounter;            /* Address where integer counter is initialized */
122023  int regBase;                /* Array of registers where record is assembled */
122024
122025  /* Generate code to skip over the creation and initialization of the
122026  ** transient index on 2nd and subsequent iterations of the loop. */
122027  v = pParse->pVdbe;
122028  assert( v!=0 );
122029  addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
122030
122031  /* Count the number of columns that will be added to the index
122032  ** and used to match WHERE clause constraints */
122033  nKeyCol = 0;
122034  pTable = pSrc->pTab;
122035  pWCEnd = &pWC->a[pWC->nTerm];
122036  pLoop = pLevel->pWLoop;
122037  idxCols = 0;
122038  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
122039    Expr *pExpr = pTerm->pExpr;
122040    assert( !ExprHasProperty(pExpr, EP_FromJoin)    /* prereq always non-zero */
122041         || pExpr->iRightJoinTable!=pSrc->iCursor   /*   for the right-hand   */
122042         || pLoop->prereq!=0 );                     /*   table of a LEFT JOIN */
122043    if( pLoop->prereq==0
122044     && (pTerm->wtFlags & TERM_VIRTUAL)==0
122045     && !ExprHasProperty(pExpr, EP_FromJoin)
122046     && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
122047      pPartial = sqlite3ExprAnd(pParse->db, pPartial,
122048                                sqlite3ExprDup(pParse->db, pExpr, 0));
122049    }
122050    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
122051      int iCol = pTerm->u.leftColumn;
122052      Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
122053      testcase( iCol==BMS );
122054      testcase( iCol==BMS-1 );
122055      if( !sentWarning ){
122056        sqlite3_log(SQLITE_WARNING_AUTOINDEX,
122057            "automatic index on %s(%s)", pTable->zName,
122058            pTable->aCol[iCol].zName);
122059        sentWarning = 1;
122060      }
122061      if( (idxCols & cMask)==0 ){
122062        if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
122063          goto end_auto_index_create;
122064        }
122065        pLoop->aLTerm[nKeyCol++] = pTerm;
122066        idxCols |= cMask;
122067      }
122068    }
122069  }
122070  assert( nKeyCol>0 );
122071  pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
122072  pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
122073                     | WHERE_AUTO_INDEX;
122074
122075  /* Count the number of additional columns needed to create a
122076  ** covering index.  A "covering index" is an index that contains all
122077  ** columns that are needed by the query.  With a covering index, the
122078  ** original table never needs to be accessed.  Automatic indices must
122079  ** be a covering index because the index will not be updated if the
122080  ** original table changes and the index and table cannot both be used
122081  ** if they go out of sync.
122082  */
122083  extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
122084  mxBitCol = MIN(BMS-1,pTable->nCol);
122085  testcase( pTable->nCol==BMS-1 );
122086  testcase( pTable->nCol==BMS-2 );
122087  for(i=0; i<mxBitCol; i++){
122088    if( extraCols & MASKBIT(i) ) nKeyCol++;
122089  }
122090  if( pSrc->colUsed & MASKBIT(BMS-1) ){
122091    nKeyCol += pTable->nCol - BMS + 1;
122092  }
122093
122094  /* Construct the Index object to describe this index */
122095  pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
122096  if( pIdx==0 ) goto end_auto_index_create;
122097  pLoop->u.btree.pIndex = pIdx;
122098  pIdx->zName = "auto-index";
122099  pIdx->pTable = pTable;
122100  n = 0;
122101  idxCols = 0;
122102  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
122103    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
122104      int iCol = pTerm->u.leftColumn;
122105      Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
122106      testcase( iCol==BMS-1 );
122107      testcase( iCol==BMS );
122108      if( (idxCols & cMask)==0 ){
122109        Expr *pX = pTerm->pExpr;
122110        idxCols |= cMask;
122111        pIdx->aiColumn[n] = pTerm->u.leftColumn;
122112        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
122113        pIdx->azColl[n] = pColl ? pColl->zName : "BINARY";
122114        n++;
122115      }
122116    }
122117  }
122118  assert( (u32)n==pLoop->u.btree.nEq );
122119
122120  /* Add additional columns needed to make the automatic index into
122121  ** a covering index */
122122  for(i=0; i<mxBitCol; i++){
122123    if( extraCols & MASKBIT(i) ){
122124      pIdx->aiColumn[n] = i;
122125      pIdx->azColl[n] = "BINARY";
122126      n++;
122127    }
122128  }
122129  if( pSrc->colUsed & MASKBIT(BMS-1) ){
122130    for(i=BMS-1; i<pTable->nCol; i++){
122131      pIdx->aiColumn[n] = i;
122132      pIdx->azColl[n] = "BINARY";
122133      n++;
122134    }
122135  }
122136  assert( n==nKeyCol );
122137  pIdx->aiColumn[n] = XN_ROWID;
122138  pIdx->azColl[n] = "BINARY";
122139
122140  /* Create the automatic index */
122141  assert( pLevel->iIdxCur>=0 );
122142  pLevel->iIdxCur = pParse->nTab++;
122143  sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
122144  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
122145  VdbeComment((v, "for %s", pTable->zName));
122146
122147  /* Fill the automatic index with content */
122148  sqlite3ExprCachePush(pParse);
122149  pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
122150  if( pTabItem->fg.viaCoroutine ){
122151    int regYield = pTabItem->regReturn;
122152    addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
122153    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
122154    addrTop =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
122155    VdbeCoverage(v);
122156    VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
122157  }else{
122158    addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
122159  }
122160  if( pPartial ){
122161    iContinue = sqlite3VdbeMakeLabel(v);
122162    sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
122163    pLoop->wsFlags |= WHERE_PARTIALIDX;
122164  }
122165  regRecord = sqlite3GetTempReg(pParse);
122166  regBase = sqlite3GenerateIndexKey(
122167      pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
122168  );
122169  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
122170  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
122171  if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
122172  if( pTabItem->fg.viaCoroutine ){
122173    sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
122174    translateColumnToCopy(v, addrTop, pLevel->iTabCur, pTabItem->regResult, 1);
122175    sqlite3VdbeGoto(v, addrTop);
122176    pTabItem->fg.viaCoroutine = 0;
122177  }else{
122178    sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
122179  }
122180  sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
122181  sqlite3VdbeJumpHere(v, addrTop);
122182  sqlite3ReleaseTempReg(pParse, regRecord);
122183  sqlite3ExprCachePop(pParse);
122184
122185  /* Jump here when skipping the initialization */
122186  sqlite3VdbeJumpHere(v, addrInit);
122187
122188end_auto_index_create:
122189  sqlite3ExprDelete(pParse->db, pPartial);
122190}
122191#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
122192
122193#ifndef SQLITE_OMIT_VIRTUALTABLE
122194/*
122195** Allocate and populate an sqlite3_index_info structure. It is the
122196** responsibility of the caller to eventually release the structure
122197** by passing the pointer returned by this function to sqlite3_free().
122198*/
122199static sqlite3_index_info *allocateIndexInfo(
122200  Parse *pParse,
122201  WhereClause *pWC,
122202  Bitmask mUnusable,              /* Ignore terms with these prereqs */
122203  struct SrcList_item *pSrc,
122204  ExprList *pOrderBy
122205){
122206  int i, j;
122207  int nTerm;
122208  struct sqlite3_index_constraint *pIdxCons;
122209  struct sqlite3_index_orderby *pIdxOrderBy;
122210  struct sqlite3_index_constraint_usage *pUsage;
122211  WhereTerm *pTerm;
122212  int nOrderBy;
122213  sqlite3_index_info *pIdxInfo;
122214
122215  /* Count the number of possible WHERE clause constraints referring
122216  ** to this virtual table */
122217  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
122218    if( pTerm->leftCursor != pSrc->iCursor ) continue;
122219    if( pTerm->prereqRight & mUnusable ) continue;
122220    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
122221    testcase( pTerm->eOperator & WO_IN );
122222    testcase( pTerm->eOperator & WO_ISNULL );
122223    testcase( pTerm->eOperator & WO_IS );
122224    testcase( pTerm->eOperator & WO_ALL );
122225    if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
122226    if( pTerm->wtFlags & TERM_VNULL ) continue;
122227    assert( pTerm->u.leftColumn>=(-1) );
122228    nTerm++;
122229  }
122230
122231  /* If the ORDER BY clause contains only columns in the current
122232  ** virtual table then allocate space for the aOrderBy part of
122233  ** the sqlite3_index_info structure.
122234  */
122235  nOrderBy = 0;
122236  if( pOrderBy ){
122237    int n = pOrderBy->nExpr;
122238    for(i=0; i<n; i++){
122239      Expr *pExpr = pOrderBy->a[i].pExpr;
122240      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
122241    }
122242    if( i==n){
122243      nOrderBy = n;
122244    }
122245  }
122246
122247  /* Allocate the sqlite3_index_info structure
122248  */
122249  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
122250                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
122251                           + sizeof(*pIdxOrderBy)*nOrderBy );
122252  if( pIdxInfo==0 ){
122253    sqlite3ErrorMsg(pParse, "out of memory");
122254    return 0;
122255  }
122256
122257  /* Initialize the structure.  The sqlite3_index_info structure contains
122258  ** many fields that are declared "const" to prevent xBestIndex from
122259  ** changing them.  We have to do some funky casting in order to
122260  ** initialize those fields.
122261  */
122262  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
122263  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
122264  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
122265  *(int*)&pIdxInfo->nConstraint = nTerm;
122266  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
122267  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
122268  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
122269  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
122270                                                                   pUsage;
122271
122272  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
122273    u8 op;
122274    if( pTerm->leftCursor != pSrc->iCursor ) continue;
122275    if( pTerm->prereqRight & mUnusable ) continue;
122276    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
122277    testcase( pTerm->eOperator & WO_IN );
122278    testcase( pTerm->eOperator & WO_IS );
122279    testcase( pTerm->eOperator & WO_ISNULL );
122280    testcase( pTerm->eOperator & WO_ALL );
122281    if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
122282    if( pTerm->wtFlags & TERM_VNULL ) continue;
122283    assert( pTerm->u.leftColumn>=(-1) );
122284    pIdxCons[j].iColumn = pTerm->u.leftColumn;
122285    pIdxCons[j].iTermOffset = i;
122286    op = (u8)pTerm->eOperator & WO_ALL;
122287    if( op==WO_IN ) op = WO_EQ;
122288    pIdxCons[j].op = op;
122289    /* The direct assignment in the previous line is possible only because
122290    ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
122291    ** following asserts verify this fact. */
122292    assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
122293    assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
122294    assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
122295    assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
122296    assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
122297    assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
122298    assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
122299    j++;
122300  }
122301  for(i=0; i<nOrderBy; i++){
122302    Expr *pExpr = pOrderBy->a[i].pExpr;
122303    pIdxOrderBy[i].iColumn = pExpr->iColumn;
122304    pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
122305  }
122306
122307  return pIdxInfo;
122308}
122309
122310/*
122311** The table object reference passed as the second argument to this function
122312** must represent a virtual table. This function invokes the xBestIndex()
122313** method of the virtual table with the sqlite3_index_info object that
122314** comes in as the 3rd argument to this function.
122315**
122316** If an error occurs, pParse is populated with an error message and a
122317** non-zero value is returned. Otherwise, 0 is returned and the output
122318** part of the sqlite3_index_info structure is left populated.
122319**
122320** Whether or not an error is returned, it is the responsibility of the
122321** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
122322** that this is required.
122323*/
122324static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
122325  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
122326  int i;
122327  int rc;
122328
122329  TRACE_IDX_INPUTS(p);
122330  rc = pVtab->pModule->xBestIndex(pVtab, p);
122331  TRACE_IDX_OUTPUTS(p);
122332
122333  if( rc!=SQLITE_OK ){
122334    if( rc==SQLITE_NOMEM ){
122335      pParse->db->mallocFailed = 1;
122336    }else if( !pVtab->zErrMsg ){
122337      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
122338    }else{
122339      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
122340    }
122341  }
122342  sqlite3_free(pVtab->zErrMsg);
122343  pVtab->zErrMsg = 0;
122344
122345  for(i=0; i<p->nConstraint; i++){
122346    if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
122347      sqlite3ErrorMsg(pParse,
122348          "table %s: xBestIndex returned an invalid plan", pTab->zName);
122349    }
122350  }
122351
122352  return pParse->nErr;
122353}
122354#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
122355
122356#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
122357/*
122358** Estimate the location of a particular key among all keys in an
122359** index.  Store the results in aStat as follows:
122360**
122361**    aStat[0]      Est. number of rows less than pRec
122362**    aStat[1]      Est. number of rows equal to pRec
122363**
122364** Return the index of the sample that is the smallest sample that
122365** is greater than or equal to pRec. Note that this index is not an index
122366** into the aSample[] array - it is an index into a virtual set of samples
122367** based on the contents of aSample[] and the number of fields in record
122368** pRec.
122369*/
122370static int whereKeyStats(
122371  Parse *pParse,              /* Database connection */
122372  Index *pIdx,                /* Index to consider domain of */
122373  UnpackedRecord *pRec,       /* Vector of values to consider */
122374  int roundUp,                /* Round up if true.  Round down if false */
122375  tRowcnt *aStat              /* OUT: stats written here */
122376){
122377  IndexSample *aSample = pIdx->aSample;
122378  int iCol;                   /* Index of required stats in anEq[] etc. */
122379  int i;                      /* Index of first sample >= pRec */
122380  int iSample;                /* Smallest sample larger than or equal to pRec */
122381  int iMin = 0;               /* Smallest sample not yet tested */
122382  int iTest;                  /* Next sample to test */
122383  int res;                    /* Result of comparison operation */
122384  int nField;                 /* Number of fields in pRec */
122385  tRowcnt iLower = 0;         /* anLt[] + anEq[] of largest sample pRec is > */
122386
122387#ifndef SQLITE_DEBUG
122388  UNUSED_PARAMETER( pParse );
122389#endif
122390  assert( pRec!=0 );
122391  assert( pIdx->nSample>0 );
122392  assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
122393
122394  /* Do a binary search to find the first sample greater than or equal
122395  ** to pRec. If pRec contains a single field, the set of samples to search
122396  ** is simply the aSample[] array. If the samples in aSample[] contain more
122397  ** than one fields, all fields following the first are ignored.
122398  **
122399  ** If pRec contains N fields, where N is more than one, then as well as the
122400  ** samples in aSample[] (truncated to N fields), the search also has to
122401  ** consider prefixes of those samples. For example, if the set of samples
122402  ** in aSample is:
122403  **
122404  **     aSample[0] = (a, 5)
122405  **     aSample[1] = (a, 10)
122406  **     aSample[2] = (b, 5)
122407  **     aSample[3] = (c, 100)
122408  **     aSample[4] = (c, 105)
122409  **
122410  ** Then the search space should ideally be the samples above and the
122411  ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
122412  ** the code actually searches this set:
122413  **
122414  **     0: (a)
122415  **     1: (a, 5)
122416  **     2: (a, 10)
122417  **     3: (a, 10)
122418  **     4: (b)
122419  **     5: (b, 5)
122420  **     6: (c)
122421  **     7: (c, 100)
122422  **     8: (c, 105)
122423  **     9: (c, 105)
122424  **
122425  ** For each sample in the aSample[] array, N samples are present in the
122426  ** effective sample array. In the above, samples 0 and 1 are based on
122427  ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
122428  **
122429  ** Often, sample i of each block of N effective samples has (i+1) fields.
122430  ** Except, each sample may be extended to ensure that it is greater than or
122431  ** equal to the previous sample in the array. For example, in the above,
122432  ** sample 2 is the first sample of a block of N samples, so at first it
122433  ** appears that it should be 1 field in size. However, that would make it
122434  ** smaller than sample 1, so the binary search would not work. As a result,
122435  ** it is extended to two fields. The duplicates that this creates do not
122436  ** cause any problems.
122437  */
122438  nField = pRec->nField;
122439  iCol = 0;
122440  iSample = pIdx->nSample * nField;
122441  do{
122442    int iSamp;                    /* Index in aSample[] of test sample */
122443    int n;                        /* Number of fields in test sample */
122444
122445    iTest = (iMin+iSample)/2;
122446    iSamp = iTest / nField;
122447    if( iSamp>0 ){
122448      /* The proposed effective sample is a prefix of sample aSample[iSamp].
122449      ** Specifically, the shortest prefix of at least (1 + iTest%nField)
122450      ** fields that is greater than the previous effective sample.  */
122451      for(n=(iTest % nField) + 1; n<nField; n++){
122452        if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
122453      }
122454    }else{
122455      n = iTest + 1;
122456    }
122457
122458    pRec->nField = n;
122459    res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
122460    if( res<0 ){
122461      iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
122462      iMin = iTest+1;
122463    }else if( res==0 && n<nField ){
122464      iLower = aSample[iSamp].anLt[n-1];
122465      iMin = iTest+1;
122466      res = -1;
122467    }else{
122468      iSample = iTest;
122469      iCol = n-1;
122470    }
122471  }while( res && iMin<iSample );
122472  i = iSample / nField;
122473
122474#ifdef SQLITE_DEBUG
122475  /* The following assert statements check that the binary search code
122476  ** above found the right answer. This block serves no purpose other
122477  ** than to invoke the asserts.  */
122478  if( pParse->db->mallocFailed==0 ){
122479    if( res==0 ){
122480      /* If (res==0) is true, then pRec must be equal to sample i. */
122481      assert( i<pIdx->nSample );
122482      assert( iCol==nField-1 );
122483      pRec->nField = nField;
122484      assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
122485           || pParse->db->mallocFailed
122486      );
122487    }else{
122488      /* Unless i==pIdx->nSample, indicating that pRec is larger than
122489      ** all samples in the aSample[] array, pRec must be smaller than the
122490      ** (iCol+1) field prefix of sample i.  */
122491      assert( i<=pIdx->nSample && i>=0 );
122492      pRec->nField = iCol+1;
122493      assert( i==pIdx->nSample
122494           || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
122495           || pParse->db->mallocFailed );
122496
122497      /* if i==0 and iCol==0, then record pRec is smaller than all samples
122498      ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
122499      ** be greater than or equal to the (iCol) field prefix of sample i.
122500      ** If (i>0), then pRec must also be greater than sample (i-1).  */
122501      if( iCol>0 ){
122502        pRec->nField = iCol;
122503        assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
122504             || pParse->db->mallocFailed );
122505      }
122506      if( i>0 ){
122507        pRec->nField = nField;
122508        assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
122509             || pParse->db->mallocFailed );
122510      }
122511    }
122512  }
122513#endif /* ifdef SQLITE_DEBUG */
122514
122515  if( res==0 ){
122516    /* Record pRec is equal to sample i */
122517    assert( iCol==nField-1 );
122518    aStat[0] = aSample[i].anLt[iCol];
122519    aStat[1] = aSample[i].anEq[iCol];
122520  }else{
122521    /* At this point, the (iCol+1) field prefix of aSample[i] is the first
122522    ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
122523    ** is larger than all samples in the array. */
122524    tRowcnt iUpper, iGap;
122525    if( i>=pIdx->nSample ){
122526      iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
122527    }else{
122528      iUpper = aSample[i].anLt[iCol];
122529    }
122530
122531    if( iLower>=iUpper ){
122532      iGap = 0;
122533    }else{
122534      iGap = iUpper - iLower;
122535    }
122536    if( roundUp ){
122537      iGap = (iGap*2)/3;
122538    }else{
122539      iGap = iGap/3;
122540    }
122541    aStat[0] = iLower + iGap;
122542    aStat[1] = pIdx->aAvgEq[iCol];
122543  }
122544
122545  /* Restore the pRec->nField value before returning.  */
122546  pRec->nField = nField;
122547  return i;
122548}
122549#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
122550
122551/*
122552** If it is not NULL, pTerm is a term that provides an upper or lower
122553** bound on a range scan. Without considering pTerm, it is estimated
122554** that the scan will visit nNew rows. This function returns the number
122555** estimated to be visited after taking pTerm into account.
122556**
122557** If the user explicitly specified a likelihood() value for this term,
122558** then the return value is the likelihood multiplied by the number of
122559** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
122560** has a likelihood of 0.50, and any other term a likelihood of 0.25.
122561*/
122562static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
122563  LogEst nRet = nNew;
122564  if( pTerm ){
122565    if( pTerm->truthProb<=0 ){
122566      nRet += pTerm->truthProb;
122567    }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
122568      nRet -= 20;        assert( 20==sqlite3LogEst(4) );
122569    }
122570  }
122571  return nRet;
122572}
122573
122574
122575#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
122576/*
122577** Return the affinity for a single column of an index.
122578*/
122579static char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
122580  assert( iCol>=0 && iCol<pIdx->nColumn );
122581  if( !pIdx->zColAff ){
122582    if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
122583  }
122584  return pIdx->zColAff[iCol];
122585}
122586#endif
122587
122588
122589#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
122590/*
122591** This function is called to estimate the number of rows visited by a
122592** range-scan on a skip-scan index. For example:
122593**
122594**   CREATE INDEX i1 ON t1(a, b, c);
122595**   SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
122596**
122597** Value pLoop->nOut is currently set to the estimated number of rows
122598** visited for scanning (a=? AND b=?). This function reduces that estimate
122599** by some factor to account for the (c BETWEEN ? AND ?) expression based
122600** on the stat4 data for the index. this scan will be peformed multiple
122601** times (once for each (a,b) combination that matches a=?) is dealt with
122602** by the caller.
122603**
122604** It does this by scanning through all stat4 samples, comparing values
122605** extracted from pLower and pUpper with the corresponding column in each
122606** sample. If L and U are the number of samples found to be less than or
122607** equal to the values extracted from pLower and pUpper respectively, and
122608** N is the total number of samples, the pLoop->nOut value is adjusted
122609** as follows:
122610**
122611**   nOut = nOut * ( min(U - L, 1) / N )
122612**
122613** If pLower is NULL, or a value cannot be extracted from the term, L is
122614** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
122615** U is set to N.
122616**
122617** Normally, this function sets *pbDone to 1 before returning. However,
122618** if no value can be extracted from either pLower or pUpper (and so the
122619** estimate of the number of rows delivered remains unchanged), *pbDone
122620** is left as is.
122621**
122622** If an error occurs, an SQLite error code is returned. Otherwise,
122623** SQLITE_OK.
122624*/
122625static int whereRangeSkipScanEst(
122626  Parse *pParse,       /* Parsing & code generating context */
122627  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
122628  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
122629  WhereLoop *pLoop,    /* Update the .nOut value of this loop */
122630  int *pbDone          /* Set to true if at least one expr. value extracted */
122631){
122632  Index *p = pLoop->u.btree.pIndex;
122633  int nEq = pLoop->u.btree.nEq;
122634  sqlite3 *db = pParse->db;
122635  int nLower = -1;
122636  int nUpper = p->nSample+1;
122637  int rc = SQLITE_OK;
122638  u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
122639  CollSeq *pColl;
122640
122641  sqlite3_value *p1 = 0;          /* Value extracted from pLower */
122642  sqlite3_value *p2 = 0;          /* Value extracted from pUpper */
122643  sqlite3_value *pVal = 0;        /* Value extracted from record */
122644
122645  pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
122646  if( pLower ){
122647    rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
122648    nLower = 0;
122649  }
122650  if( pUpper && rc==SQLITE_OK ){
122651    rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
122652    nUpper = p2 ? 0 : p->nSample;
122653  }
122654
122655  if( p1 || p2 ){
122656    int i;
122657    int nDiff;
122658    for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
122659      rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
122660      if( rc==SQLITE_OK && p1 ){
122661        int res = sqlite3MemCompare(p1, pVal, pColl);
122662        if( res>=0 ) nLower++;
122663      }
122664      if( rc==SQLITE_OK && p2 ){
122665        int res = sqlite3MemCompare(p2, pVal, pColl);
122666        if( res>=0 ) nUpper++;
122667      }
122668    }
122669    nDiff = (nUpper - nLower);
122670    if( nDiff<=0 ) nDiff = 1;
122671
122672    /* If there is both an upper and lower bound specified, and the
122673    ** comparisons indicate that they are close together, use the fallback
122674    ** method (assume that the scan visits 1/64 of the rows) for estimating
122675    ** the number of rows visited. Otherwise, estimate the number of rows
122676    ** using the method described in the header comment for this function. */
122677    if( nDiff!=1 || pUpper==0 || pLower==0 ){
122678      int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
122679      pLoop->nOut -= nAdjust;
122680      *pbDone = 1;
122681      WHERETRACE(0x10, ("range skip-scan regions: %u..%u  adjust=%d est=%d\n",
122682                           nLower, nUpper, nAdjust*-1, pLoop->nOut));
122683    }
122684
122685  }else{
122686    assert( *pbDone==0 );
122687  }
122688
122689  sqlite3ValueFree(p1);
122690  sqlite3ValueFree(p2);
122691  sqlite3ValueFree(pVal);
122692
122693  return rc;
122694}
122695#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
122696
122697/*
122698** This function is used to estimate the number of rows that will be visited
122699** by scanning an index for a range of values. The range may have an upper
122700** bound, a lower bound, or both. The WHERE clause terms that set the upper
122701** and lower bounds are represented by pLower and pUpper respectively. For
122702** example, assuming that index p is on t1(a):
122703**
122704**   ... FROM t1 WHERE a > ? AND a < ? ...
122705**                    |_____|   |_____|
122706**                       |         |
122707**                     pLower    pUpper
122708**
122709** If either of the upper or lower bound is not present, then NULL is passed in
122710** place of the corresponding WhereTerm.
122711**
122712** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
122713** column subject to the range constraint. Or, equivalently, the number of
122714** equality constraints optimized by the proposed index scan. For example,
122715** assuming index p is on t1(a, b), and the SQL query is:
122716**
122717**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
122718**
122719** then nEq is set to 1 (as the range restricted column, b, is the second
122720** left-most column of the index). Or, if the query is:
122721**
122722**   ... FROM t1 WHERE a > ? AND a < ? ...
122723**
122724** then nEq is set to 0.
122725**
122726** When this function is called, *pnOut is set to the sqlite3LogEst() of the
122727** number of rows that the index scan is expected to visit without
122728** considering the range constraints. If nEq is 0, then *pnOut is the number of
122729** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
122730** to account for the range constraints pLower and pUpper.
122731**
122732** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
122733** used, a single range inequality reduces the search space by a factor of 4.
122734** and a pair of constraints (x>? AND x<?) reduces the expected number of
122735** rows visited by a factor of 64.
122736*/
122737static int whereRangeScanEst(
122738  Parse *pParse,       /* Parsing & code generating context */
122739  WhereLoopBuilder *pBuilder,
122740  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
122741  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
122742  WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */
122743){
122744  int rc = SQLITE_OK;
122745  int nOut = pLoop->nOut;
122746  LogEst nNew;
122747
122748#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
122749  Index *p = pLoop->u.btree.pIndex;
122750  int nEq = pLoop->u.btree.nEq;
122751
122752  if( p->nSample>0 && nEq<p->nSampleCol ){
122753    if( nEq==pBuilder->nRecValid ){
122754      UnpackedRecord *pRec = pBuilder->pRec;
122755      tRowcnt a[2];
122756      u8 aff;
122757
122758      /* Variable iLower will be set to the estimate of the number of rows in
122759      ** the index that are less than the lower bound of the range query. The
122760      ** lower bound being the concatenation of $P and $L, where $P is the
122761      ** key-prefix formed by the nEq values matched against the nEq left-most
122762      ** columns of the index, and $L is the value in pLower.
122763      **
122764      ** Or, if pLower is NULL or $L cannot be extracted from it (because it
122765      ** is not a simple variable or literal value), the lower bound of the
122766      ** range is $P. Due to a quirk in the way whereKeyStats() works, even
122767      ** if $L is available, whereKeyStats() is called for both ($P) and
122768      ** ($P:$L) and the larger of the two returned values is used.
122769      **
122770      ** Similarly, iUpper is to be set to the estimate of the number of rows
122771      ** less than the upper bound of the range query. Where the upper bound
122772      ** is either ($P) or ($P:$U). Again, even if $U is available, both values
122773      ** of iUpper are requested of whereKeyStats() and the smaller used.
122774      **
122775      ** The number of rows between the two bounds is then just iUpper-iLower.
122776      */
122777      tRowcnt iLower;     /* Rows less than the lower bound */
122778      tRowcnt iUpper;     /* Rows less than the upper bound */
122779      int iLwrIdx = -2;   /* aSample[] for the lower bound */
122780      int iUprIdx = -1;   /* aSample[] for the upper bound */
122781
122782      if( pRec ){
122783        testcase( pRec->nField!=pBuilder->nRecValid );
122784        pRec->nField = pBuilder->nRecValid;
122785      }
122786      aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq);
122787      assert( nEq!=p->nKeyCol || aff==SQLITE_AFF_INTEGER );
122788      /* Determine iLower and iUpper using ($P) only. */
122789      if( nEq==0 ){
122790        iLower = 0;
122791        iUpper = p->nRowEst0;
122792      }else{
122793        /* Note: this call could be optimized away - since the same values must
122794        ** have been requested when testing key $P in whereEqualScanEst().  */
122795        whereKeyStats(pParse, p, pRec, 0, a);
122796        iLower = a[0];
122797        iUpper = a[0] + a[1];
122798      }
122799
122800      assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
122801      assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
122802      assert( p->aSortOrder!=0 );
122803      if( p->aSortOrder[nEq] ){
122804        /* The roles of pLower and pUpper are swapped for a DESC index */
122805        SWAP(WhereTerm*, pLower, pUpper);
122806      }
122807
122808      /* If possible, improve on the iLower estimate using ($P:$L). */
122809      if( pLower ){
122810        int bOk;                    /* True if value is extracted from pExpr */
122811        Expr *pExpr = pLower->pExpr->pRight;
122812        rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
122813        if( rc==SQLITE_OK && bOk ){
122814          tRowcnt iNew;
122815          iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
122816          iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
122817          if( iNew>iLower ) iLower = iNew;
122818          nOut--;
122819          pLower = 0;
122820        }
122821      }
122822
122823      /* If possible, improve on the iUpper estimate using ($P:$U). */
122824      if( pUpper ){
122825        int bOk;                    /* True if value is extracted from pExpr */
122826        Expr *pExpr = pUpper->pExpr->pRight;
122827        rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
122828        if( rc==SQLITE_OK && bOk ){
122829          tRowcnt iNew;
122830          iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
122831          iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
122832          if( iNew<iUpper ) iUpper = iNew;
122833          nOut--;
122834          pUpper = 0;
122835        }
122836      }
122837
122838      pBuilder->pRec = pRec;
122839      if( rc==SQLITE_OK ){
122840        if( iUpper>iLower ){
122841          nNew = sqlite3LogEst(iUpper - iLower);
122842          /* TUNING:  If both iUpper and iLower are derived from the same
122843          ** sample, then assume they are 4x more selective.  This brings
122844          ** the estimated selectivity more in line with what it would be
122845          ** if estimated without the use of STAT3/4 tables. */
122846          if( iLwrIdx==iUprIdx ) nNew -= 20;  assert( 20==sqlite3LogEst(4) );
122847        }else{
122848          nNew = 10;        assert( 10==sqlite3LogEst(2) );
122849        }
122850        if( nNew<nOut ){
122851          nOut = nNew;
122852        }
122853        WHERETRACE(0x10, ("STAT4 range scan: %u..%u  est=%d\n",
122854                           (u32)iLower, (u32)iUpper, nOut));
122855      }
122856    }else{
122857      int bDone = 0;
122858      rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
122859      if( bDone ) return rc;
122860    }
122861  }
122862#else
122863  UNUSED_PARAMETER(pParse);
122864  UNUSED_PARAMETER(pBuilder);
122865  assert( pLower || pUpper );
122866#endif
122867  assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
122868  nNew = whereRangeAdjust(pLower, nOut);
122869  nNew = whereRangeAdjust(pUpper, nNew);
122870
122871  /* TUNING: If there is both an upper and lower limit and neither limit
122872  ** has an application-defined likelihood(), assume the range is
122873  ** reduced by an additional 75%. This means that, by default, an open-ended
122874  ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
122875  ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
122876  ** match 1/64 of the index. */
122877  if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
122878    nNew -= 20;
122879  }
122880
122881  nOut -= (pLower!=0) + (pUpper!=0);
122882  if( nNew<10 ) nNew = 10;
122883  if( nNew<nOut ) nOut = nNew;
122884#if defined(WHERETRACE_ENABLED)
122885  if( pLoop->nOut>nOut ){
122886    WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
122887                    pLoop->nOut, nOut));
122888  }
122889#endif
122890  pLoop->nOut = (LogEst)nOut;
122891  return rc;
122892}
122893
122894#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
122895/*
122896** Estimate the number of rows that will be returned based on
122897** an equality constraint x=VALUE and where that VALUE occurs in
122898** the histogram data.  This only works when x is the left-most
122899** column of an index and sqlite_stat3 histogram data is available
122900** for that index.  When pExpr==NULL that means the constraint is
122901** "x IS NULL" instead of "x=VALUE".
122902**
122903** Write the estimated row count into *pnRow and return SQLITE_OK.
122904** If unable to make an estimate, leave *pnRow unchanged and return
122905** non-zero.
122906**
122907** This routine can fail if it is unable to load a collating sequence
122908** required for string comparison, or if unable to allocate memory
122909** for a UTF conversion required for comparison.  The error is stored
122910** in the pParse structure.
122911*/
122912static int whereEqualScanEst(
122913  Parse *pParse,       /* Parsing & code generating context */
122914  WhereLoopBuilder *pBuilder,
122915  Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
122916  tRowcnt *pnRow       /* Write the revised row estimate here */
122917){
122918  Index *p = pBuilder->pNew->u.btree.pIndex;
122919  int nEq = pBuilder->pNew->u.btree.nEq;
122920  UnpackedRecord *pRec = pBuilder->pRec;
122921  u8 aff;                   /* Column affinity */
122922  int rc;                   /* Subfunction return code */
122923  tRowcnt a[2];             /* Statistics */
122924  int bOk;
122925
122926  assert( nEq>=1 );
122927  assert( nEq<=p->nColumn );
122928  assert( p->aSample!=0 );
122929  assert( p->nSample>0 );
122930  assert( pBuilder->nRecValid<nEq );
122931
122932  /* If values are not available for all fields of the index to the left
122933  ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
122934  if( pBuilder->nRecValid<(nEq-1) ){
122935    return SQLITE_NOTFOUND;
122936  }
122937
122938  /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
122939  ** below would return the same value.  */
122940  if( nEq>=p->nColumn ){
122941    *pnRow = 1;
122942    return SQLITE_OK;
122943  }
122944
122945  aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq-1);
122946  rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
122947  pBuilder->pRec = pRec;
122948  if( rc!=SQLITE_OK ) return rc;
122949  if( bOk==0 ) return SQLITE_NOTFOUND;
122950  pBuilder->nRecValid = nEq;
122951
122952  whereKeyStats(pParse, p, pRec, 0, a);
122953  WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
122954  *pnRow = a[1];
122955
122956  return rc;
122957}
122958#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
122959
122960#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
122961/*
122962** Estimate the number of rows that will be returned based on
122963** an IN constraint where the right-hand side of the IN operator
122964** is a list of values.  Example:
122965**
122966**        WHERE x IN (1,2,3,4)
122967**
122968** Write the estimated row count into *pnRow and return SQLITE_OK.
122969** If unable to make an estimate, leave *pnRow unchanged and return
122970** non-zero.
122971**
122972** This routine can fail if it is unable to load a collating sequence
122973** required for string comparison, or if unable to allocate memory
122974** for a UTF conversion required for comparison.  The error is stored
122975** in the pParse structure.
122976*/
122977static int whereInScanEst(
122978  Parse *pParse,       /* Parsing & code generating context */
122979  WhereLoopBuilder *pBuilder,
122980  ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
122981  tRowcnt *pnRow       /* Write the revised row estimate here */
122982){
122983  Index *p = pBuilder->pNew->u.btree.pIndex;
122984  i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
122985  int nRecValid = pBuilder->nRecValid;
122986  int rc = SQLITE_OK;     /* Subfunction return code */
122987  tRowcnt nEst;           /* Number of rows for a single term */
122988  tRowcnt nRowEst = 0;    /* New estimate of the number of rows */
122989  int i;                  /* Loop counter */
122990
122991  assert( p->aSample!=0 );
122992  for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
122993    nEst = nRow0;
122994    rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
122995    nRowEst += nEst;
122996    pBuilder->nRecValid = nRecValid;
122997  }
122998
122999  if( rc==SQLITE_OK ){
123000    if( nRowEst > nRow0 ) nRowEst = nRow0;
123001    *pnRow = nRowEst;
123002    WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
123003  }
123004  assert( pBuilder->nRecValid==nRecValid );
123005  return rc;
123006}
123007#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
123008
123009
123010#ifdef WHERETRACE_ENABLED
123011/*
123012** Print the content of a WhereTerm object
123013*/
123014static void whereTermPrint(WhereTerm *pTerm, int iTerm){
123015  if( pTerm==0 ){
123016    sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
123017  }else{
123018    char zType[4];
123019    memcpy(zType, "...", 4);
123020    if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
123021    if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
123022    if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
123023    sqlite3DebugPrintf(
123024       "TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x wtFlags=0x%04x\n",
123025       iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
123026       pTerm->eOperator, pTerm->wtFlags);
123027    sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
123028  }
123029}
123030#endif
123031
123032#ifdef WHERETRACE_ENABLED
123033/*
123034** Print a WhereLoop object for debugging purposes
123035*/
123036static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
123037  WhereInfo *pWInfo = pWC->pWInfo;
123038  int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
123039  struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
123040  Table *pTab = pItem->pTab;
123041  sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
123042                     p->iTab, nb, p->maskSelf, nb, p->prereq);
123043  sqlite3DebugPrintf(" %12s",
123044                     pItem->zAlias ? pItem->zAlias : pTab->zName);
123045  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
123046    const char *zName;
123047    if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
123048      if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
123049        int i = sqlite3Strlen30(zName) - 1;
123050        while( zName[i]!='_' ) i--;
123051        zName += i;
123052      }
123053      sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
123054    }else{
123055      sqlite3DebugPrintf("%20s","");
123056    }
123057  }else{
123058    char *z;
123059    if( p->u.vtab.idxStr ){
123060      z = sqlite3_mprintf("(%d,\"%s\",%x)",
123061                p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
123062    }else{
123063      z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
123064    }
123065    sqlite3DebugPrintf(" %-19s", z);
123066    sqlite3_free(z);
123067  }
123068  if( p->wsFlags & WHERE_SKIPSCAN ){
123069    sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
123070  }else{
123071    sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
123072  }
123073  sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
123074  if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
123075    int i;
123076    for(i=0; i<p->nLTerm; i++){
123077      whereTermPrint(p->aLTerm[i], i);
123078    }
123079  }
123080}
123081#endif
123082
123083/*
123084** Convert bulk memory into a valid WhereLoop that can be passed
123085** to whereLoopClear harmlessly.
123086*/
123087static void whereLoopInit(WhereLoop *p){
123088  p->aLTerm = p->aLTermSpace;
123089  p->nLTerm = 0;
123090  p->nLSlot = ArraySize(p->aLTermSpace);
123091  p->wsFlags = 0;
123092}
123093
123094/*
123095** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.
123096*/
123097static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
123098  if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
123099    if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
123100      sqlite3_free(p->u.vtab.idxStr);
123101      p->u.vtab.needFree = 0;
123102      p->u.vtab.idxStr = 0;
123103    }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
123104      sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
123105      sqlite3DbFree(db, p->u.btree.pIndex);
123106      p->u.btree.pIndex = 0;
123107    }
123108  }
123109}
123110
123111/*
123112** Deallocate internal memory used by a WhereLoop object
123113*/
123114static void whereLoopClear(sqlite3 *db, WhereLoop *p){
123115  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
123116  whereLoopClearUnion(db, p);
123117  whereLoopInit(p);
123118}
123119
123120/*
123121** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
123122*/
123123static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
123124  WhereTerm **paNew;
123125  if( p->nLSlot>=n ) return SQLITE_OK;
123126  n = (n+7)&~7;
123127  paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
123128  if( paNew==0 ) return SQLITE_NOMEM;
123129  memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
123130  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
123131  p->aLTerm = paNew;
123132  p->nLSlot = n;
123133  return SQLITE_OK;
123134}
123135
123136/*
123137** Transfer content from the second pLoop into the first.
123138*/
123139static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
123140  whereLoopClearUnion(db, pTo);
123141  if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
123142    memset(&pTo->u, 0, sizeof(pTo->u));
123143    return SQLITE_NOMEM;
123144  }
123145  memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
123146  memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
123147  if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
123148    pFrom->u.vtab.needFree = 0;
123149  }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
123150    pFrom->u.btree.pIndex = 0;
123151  }
123152  return SQLITE_OK;
123153}
123154
123155/*
123156** Delete a WhereLoop object
123157*/
123158static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
123159  whereLoopClear(db, p);
123160  sqlite3DbFree(db, p);
123161}
123162
123163/*
123164** Free a WhereInfo structure
123165*/
123166static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
123167  if( ALWAYS(pWInfo) ){
123168    int i;
123169    for(i=0; i<pWInfo->nLevel; i++){
123170      WhereLevel *pLevel = &pWInfo->a[i];
123171      if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
123172        sqlite3DbFree(db, pLevel->u.in.aInLoop);
123173      }
123174    }
123175    sqlite3WhereClauseClear(&pWInfo->sWC);
123176    while( pWInfo->pLoops ){
123177      WhereLoop *p = pWInfo->pLoops;
123178      pWInfo->pLoops = p->pNextLoop;
123179      whereLoopDelete(db, p);
123180    }
123181    sqlite3DbFree(db, pWInfo);
123182  }
123183}
123184
123185/*
123186** Return TRUE if all of the following are true:
123187**
123188**   (1)  X has the same or lower cost that Y
123189**   (2)  X is a proper subset of Y
123190**   (3)  X skips at least as many columns as Y
123191**
123192** By "proper subset" we mean that X uses fewer WHERE clause terms
123193** than Y and that every WHERE clause term used by X is also used
123194** by Y.
123195**
123196** If X is a proper subset of Y then Y is a better choice and ought
123197** to have a lower cost.  This routine returns TRUE when that cost
123198** relationship is inverted and needs to be adjusted.  The third rule
123199** was added because if X uses skip-scan less than Y it still might
123200** deserve a lower cost even if it is a proper subset of Y.
123201*/
123202static int whereLoopCheaperProperSubset(
123203  const WhereLoop *pX,       /* First WhereLoop to compare */
123204  const WhereLoop *pY        /* Compare against this WhereLoop */
123205){
123206  int i, j;
123207  if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
123208    return 0; /* X is not a subset of Y */
123209  }
123210  if( pY->nSkip > pX->nSkip ) return 0;
123211  if( pX->rRun >= pY->rRun ){
123212    if( pX->rRun > pY->rRun ) return 0;    /* X costs more than Y */
123213    if( pX->nOut > pY->nOut ) return 0;    /* X costs more than Y */
123214  }
123215  for(i=pX->nLTerm-1; i>=0; i--){
123216    if( pX->aLTerm[i]==0 ) continue;
123217    for(j=pY->nLTerm-1; j>=0; j--){
123218      if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
123219    }
123220    if( j<0 ) return 0;  /* X not a subset of Y since term X[i] not used by Y */
123221  }
123222  return 1;  /* All conditions meet */
123223}
123224
123225/*
123226** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
123227** that:
123228**
123229**   (1) pTemplate costs less than any other WhereLoops that are a proper
123230**       subset of pTemplate
123231**
123232**   (2) pTemplate costs more than any other WhereLoops for which pTemplate
123233**       is a proper subset.
123234**
123235** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
123236** WHERE clause terms than Y and that every WHERE clause term used by X is
123237** also used by Y.
123238*/
123239static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
123240  if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
123241  for(; p; p=p->pNextLoop){
123242    if( p->iTab!=pTemplate->iTab ) continue;
123243    if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
123244    if( whereLoopCheaperProperSubset(p, pTemplate) ){
123245      /* Adjust pTemplate cost downward so that it is cheaper than its
123246      ** subset p. */
123247      WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
123248                       pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
123249      pTemplate->rRun = p->rRun;
123250      pTemplate->nOut = p->nOut - 1;
123251    }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
123252      /* Adjust pTemplate cost upward so that it is costlier than p since
123253      ** pTemplate is a proper subset of p */
123254      WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
123255                       pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
123256      pTemplate->rRun = p->rRun;
123257      pTemplate->nOut = p->nOut + 1;
123258    }
123259  }
123260}
123261
123262/*
123263** Search the list of WhereLoops in *ppPrev looking for one that can be
123264** supplanted by pTemplate.
123265**
123266** Return NULL if the WhereLoop list contains an entry that can supplant
123267** pTemplate, in other words if pTemplate does not belong on the list.
123268**
123269** If pX is a WhereLoop that pTemplate can supplant, then return the
123270** link that points to pX.
123271**
123272** If pTemplate cannot supplant any existing element of the list but needs
123273** to be added to the list, then return a pointer to the tail of the list.
123274*/
123275static WhereLoop **whereLoopFindLesser(
123276  WhereLoop **ppPrev,
123277  const WhereLoop *pTemplate
123278){
123279  WhereLoop *p;
123280  for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
123281    if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
123282      /* If either the iTab or iSortIdx values for two WhereLoop are different
123283      ** then those WhereLoops need to be considered separately.  Neither is
123284      ** a candidate to replace the other. */
123285      continue;
123286    }
123287    /* In the current implementation, the rSetup value is either zero
123288    ** or the cost of building an automatic index (NlogN) and the NlogN
123289    ** is the same for compatible WhereLoops. */
123290    assert( p->rSetup==0 || pTemplate->rSetup==0
123291                 || p->rSetup==pTemplate->rSetup );
123292
123293    /* whereLoopAddBtree() always generates and inserts the automatic index
123294    ** case first.  Hence compatible candidate WhereLoops never have a larger
123295    ** rSetup. Call this SETUP-INVARIANT */
123296    assert( p->rSetup>=pTemplate->rSetup );
123297
123298    /* Any loop using an appliation-defined index (or PRIMARY KEY or
123299    ** UNIQUE constraint) with one or more == constraints is better
123300    ** than an automatic index. Unless it is a skip-scan. */
123301    if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
123302     && (pTemplate->nSkip)==0
123303     && (pTemplate->wsFlags & WHERE_INDEXED)!=0
123304     && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
123305     && (p->prereq & pTemplate->prereq)==pTemplate->prereq
123306    ){
123307      break;
123308    }
123309
123310    /* If existing WhereLoop p is better than pTemplate, pTemplate can be
123311    ** discarded.  WhereLoop p is better if:
123312    **   (1)  p has no more dependencies than pTemplate, and
123313    **   (2)  p has an equal or lower cost than pTemplate
123314    */
123315    if( (p->prereq & pTemplate->prereq)==p->prereq    /* (1)  */
123316     && p->rSetup<=pTemplate->rSetup                  /* (2a) */
123317     && p->rRun<=pTemplate->rRun                      /* (2b) */
123318     && p->nOut<=pTemplate->nOut                      /* (2c) */
123319    ){
123320      return 0;  /* Discard pTemplate */
123321    }
123322
123323    /* If pTemplate is always better than p, then cause p to be overwritten
123324    ** with pTemplate.  pTemplate is better than p if:
123325    **   (1)  pTemplate has no more dependences than p, and
123326    **   (2)  pTemplate has an equal or lower cost than p.
123327    */
123328    if( (p->prereq & pTemplate->prereq)==pTemplate->prereq   /* (1)  */
123329     && p->rRun>=pTemplate->rRun                             /* (2a) */
123330     && p->nOut>=pTemplate->nOut                             /* (2b) */
123331    ){
123332      assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
123333      break;   /* Cause p to be overwritten by pTemplate */
123334    }
123335  }
123336  return ppPrev;
123337}
123338
123339/*
123340** Insert or replace a WhereLoop entry using the template supplied.
123341**
123342** An existing WhereLoop entry might be overwritten if the new template
123343** is better and has fewer dependencies.  Or the template will be ignored
123344** and no insert will occur if an existing WhereLoop is faster and has
123345** fewer dependencies than the template.  Otherwise a new WhereLoop is
123346** added based on the template.
123347**
123348** If pBuilder->pOrSet is not NULL then we care about only the
123349** prerequisites and rRun and nOut costs of the N best loops.  That
123350** information is gathered in the pBuilder->pOrSet object.  This special
123351** processing mode is used only for OR clause processing.
123352**
123353** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
123354** still might overwrite similar loops with the new template if the
123355** new template is better.  Loops may be overwritten if the following
123356** conditions are met:
123357**
123358**    (1)  They have the same iTab.
123359**    (2)  They have the same iSortIdx.
123360**    (3)  The template has same or fewer dependencies than the current loop
123361**    (4)  The template has the same or lower cost than the current loop
123362*/
123363static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
123364  WhereLoop **ppPrev, *p;
123365  WhereInfo *pWInfo = pBuilder->pWInfo;
123366  sqlite3 *db = pWInfo->pParse->db;
123367
123368  /* If pBuilder->pOrSet is defined, then only keep track of the costs
123369  ** and prereqs.
123370  */
123371  if( pBuilder->pOrSet!=0 ){
123372    if( pTemplate->nLTerm ){
123373#if WHERETRACE_ENABLED
123374      u16 n = pBuilder->pOrSet->n;
123375      int x =
123376#endif
123377      whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
123378                                    pTemplate->nOut);
123379#if WHERETRACE_ENABLED /* 0x8 */
123380      if( sqlite3WhereTrace & 0x8 ){
123381        sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
123382        whereLoopPrint(pTemplate, pBuilder->pWC);
123383      }
123384#endif
123385    }
123386    return SQLITE_OK;
123387  }
123388
123389  /* Look for an existing WhereLoop to replace with pTemplate
123390  */
123391  whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
123392  ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
123393
123394  if( ppPrev==0 ){
123395    /* There already exists a WhereLoop on the list that is better
123396    ** than pTemplate, so just ignore pTemplate */
123397#if WHERETRACE_ENABLED /* 0x8 */
123398    if( sqlite3WhereTrace & 0x8 ){
123399      sqlite3DebugPrintf("   skip: ");
123400      whereLoopPrint(pTemplate, pBuilder->pWC);
123401    }
123402#endif
123403    return SQLITE_OK;
123404  }else{
123405    p = *ppPrev;
123406  }
123407
123408  /* If we reach this point it means that either p[] should be overwritten
123409  ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
123410  ** WhereLoop and insert it.
123411  */
123412#if WHERETRACE_ENABLED /* 0x8 */
123413  if( sqlite3WhereTrace & 0x8 ){
123414    if( p!=0 ){
123415      sqlite3DebugPrintf("replace: ");
123416      whereLoopPrint(p, pBuilder->pWC);
123417    }
123418    sqlite3DebugPrintf("    add: ");
123419    whereLoopPrint(pTemplate, pBuilder->pWC);
123420  }
123421#endif
123422  if( p==0 ){
123423    /* Allocate a new WhereLoop to add to the end of the list */
123424    *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
123425    if( p==0 ) return SQLITE_NOMEM;
123426    whereLoopInit(p);
123427    p->pNextLoop = 0;
123428  }else{
123429    /* We will be overwriting WhereLoop p[].  But before we do, first
123430    ** go through the rest of the list and delete any other entries besides
123431    ** p[] that are also supplated by pTemplate */
123432    WhereLoop **ppTail = &p->pNextLoop;
123433    WhereLoop *pToDel;
123434    while( *ppTail ){
123435      ppTail = whereLoopFindLesser(ppTail, pTemplate);
123436      if( ppTail==0 ) break;
123437      pToDel = *ppTail;
123438      if( pToDel==0 ) break;
123439      *ppTail = pToDel->pNextLoop;
123440#if WHERETRACE_ENABLED /* 0x8 */
123441      if( sqlite3WhereTrace & 0x8 ){
123442        sqlite3DebugPrintf(" delete: ");
123443        whereLoopPrint(pToDel, pBuilder->pWC);
123444      }
123445#endif
123446      whereLoopDelete(db, pToDel);
123447    }
123448  }
123449  whereLoopXfer(db, p, pTemplate);
123450  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
123451    Index *pIndex = p->u.btree.pIndex;
123452    if( pIndex && pIndex->tnum==0 ){
123453      p->u.btree.pIndex = 0;
123454    }
123455  }
123456  return SQLITE_OK;
123457}
123458
123459/*
123460** Adjust the WhereLoop.nOut value downward to account for terms of the
123461** WHERE clause that reference the loop but which are not used by an
123462** index.
123463*
123464** For every WHERE clause term that is not used by the index
123465** and which has a truth probability assigned by one of the likelihood(),
123466** likely(), or unlikely() SQL functions, reduce the estimated number
123467** of output rows by the probability specified.
123468**
123469** TUNING:  For every WHERE clause term that is not used by the index
123470** and which does not have an assigned truth probability, heuristics
123471** described below are used to try to estimate the truth probability.
123472** TODO --> Perhaps this is something that could be improved by better
123473** table statistics.
123474**
123475** Heuristic 1:  Estimate the truth probability as 93.75%.  The 93.75%
123476** value corresponds to -1 in LogEst notation, so this means decrement
123477** the WhereLoop.nOut field for every such WHERE clause term.
123478**
123479** Heuristic 2:  If there exists one or more WHERE clause terms of the
123480** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
123481** final output row estimate is no greater than 1/4 of the total number
123482** of rows in the table.  In other words, assume that x==EXPR will filter
123483** out at least 3 out of 4 rows.  If EXPR is -1 or 0 or 1, then maybe the
123484** "x" column is boolean or else -1 or 0 or 1 is a common default value
123485** on the "x" column and so in that case only cap the output row estimate
123486** at 1/2 instead of 1/4.
123487*/
123488static void whereLoopOutputAdjust(
123489  WhereClause *pWC,      /* The WHERE clause */
123490  WhereLoop *pLoop,      /* The loop to adjust downward */
123491  LogEst nRow            /* Number of rows in the entire table */
123492){
123493  WhereTerm *pTerm, *pX;
123494  Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
123495  int i, j, k;
123496  LogEst iReduce = 0;    /* pLoop->nOut should not exceed nRow-iReduce */
123497
123498  assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
123499  for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
123500    if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
123501    if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
123502    if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
123503    for(j=pLoop->nLTerm-1; j>=0; j--){
123504      pX = pLoop->aLTerm[j];
123505      if( pX==0 ) continue;
123506      if( pX==pTerm ) break;
123507      if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
123508    }
123509    if( j<0 ){
123510      if( pTerm->truthProb<=0 ){
123511        /* If a truth probability is specified using the likelihood() hints,
123512        ** then use the probability provided by the application. */
123513        pLoop->nOut += pTerm->truthProb;
123514      }else{
123515        /* In the absence of explicit truth probabilities, use heuristics to
123516        ** guess a reasonable truth probability. */
123517        pLoop->nOut--;
123518        if( pTerm->eOperator&(WO_EQ|WO_IS) ){
123519          Expr *pRight = pTerm->pExpr->pRight;
123520          testcase( pTerm->pExpr->op==TK_IS );
123521          if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
123522            k = 10;
123523          }else{
123524            k = 20;
123525          }
123526          if( iReduce<k ) iReduce = k;
123527        }
123528      }
123529    }
123530  }
123531  if( pLoop->nOut > nRow-iReduce )  pLoop->nOut = nRow - iReduce;
123532}
123533
123534/*
123535** Adjust the cost C by the costMult facter T.  This only occurs if
123536** compiled with -DSQLITE_ENABLE_COSTMULT
123537*/
123538#ifdef SQLITE_ENABLE_COSTMULT
123539# define ApplyCostMultiplier(C,T)  C += T
123540#else
123541# define ApplyCostMultiplier(C,T)
123542#endif
123543
123544/*
123545** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
123546** index pIndex. Try to match one more.
123547**
123548** When this function is called, pBuilder->pNew->nOut contains the
123549** number of rows expected to be visited by filtering using the nEq
123550** terms only. If it is modified, this value is restored before this
123551** function returns.
123552**
123553** If pProbe->tnum==0, that means pIndex is a fake index used for the
123554** INTEGER PRIMARY KEY.
123555*/
123556static int whereLoopAddBtreeIndex(
123557  WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
123558  struct SrcList_item *pSrc,      /* FROM clause term being analyzed */
123559  Index *pProbe,                  /* An index on pSrc */
123560  LogEst nInMul                   /* log(Number of iterations due to IN) */
123561){
123562  WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */
123563  Parse *pParse = pWInfo->pParse;        /* Parsing context */
123564  sqlite3 *db = pParse->db;       /* Database connection malloc context */
123565  WhereLoop *pNew;                /* Template WhereLoop under construction */
123566  WhereTerm *pTerm;               /* A WhereTerm under consideration */
123567  int opMask;                     /* Valid operators for constraints */
123568  WhereScan scan;                 /* Iterator for WHERE terms */
123569  Bitmask saved_prereq;           /* Original value of pNew->prereq */
123570  u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
123571  u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */
123572  u16 saved_nSkip;                /* Original value of pNew->nSkip */
123573  u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
123574  LogEst saved_nOut;              /* Original value of pNew->nOut */
123575  int rc = SQLITE_OK;             /* Return code */
123576  LogEst rSize;                   /* Number of rows in the table */
123577  LogEst rLogSize;                /* Logarithm of table size */
123578  WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
123579
123580  pNew = pBuilder->pNew;
123581  if( db->mallocFailed ) return SQLITE_NOMEM;
123582
123583  assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
123584  assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
123585  if( pNew->wsFlags & WHERE_BTM_LIMIT ){
123586    opMask = WO_LT|WO_LE;
123587  }else if( /*pProbe->tnum<=0 ||*/ (pSrc->fg.jointype & JT_LEFT)!=0 ){
123588    opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
123589  }else{
123590    opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
123591  }
123592  if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
123593
123594  assert( pNew->u.btree.nEq<pProbe->nColumn );
123595
123596  saved_nEq = pNew->u.btree.nEq;
123597  saved_nSkip = pNew->nSkip;
123598  saved_nLTerm = pNew->nLTerm;
123599  saved_wsFlags = pNew->wsFlags;
123600  saved_prereq = pNew->prereq;
123601  saved_nOut = pNew->nOut;
123602  pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
123603                        opMask, pProbe);
123604  pNew->rSetup = 0;
123605  rSize = pProbe->aiRowLogEst[0];
123606  rLogSize = estLog(rSize);
123607  for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
123608    u16 eOp = pTerm->eOperator;   /* Shorthand for pTerm->eOperator */
123609    LogEst rCostIdx;
123610    LogEst nOutUnadjusted;        /* nOut before IN() and WHERE adjustments */
123611    int nIn = 0;
123612#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
123613    int nRecValid = pBuilder->nRecValid;
123614#endif
123615    if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
123616     && indexColumnNotNull(pProbe, saved_nEq)
123617    ){
123618      continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
123619    }
123620    if( pTerm->prereqRight & pNew->maskSelf ) continue;
123621
123622    /* Do not allow the upper bound of a LIKE optimization range constraint
123623    ** to mix with a lower range bound from some other source */
123624    if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
123625
123626    pNew->wsFlags = saved_wsFlags;
123627    pNew->u.btree.nEq = saved_nEq;
123628    pNew->nLTerm = saved_nLTerm;
123629    if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
123630    pNew->aLTerm[pNew->nLTerm++] = pTerm;
123631    pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
123632
123633    assert( nInMul==0
123634        || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
123635        || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
123636        || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
123637    );
123638
123639    if( eOp & WO_IN ){
123640      Expr *pExpr = pTerm->pExpr;
123641      pNew->wsFlags |= WHERE_COLUMN_IN;
123642      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
123643        /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
123644        nIn = 46;  assert( 46==sqlite3LogEst(25) );
123645      }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
123646        /* "x IN (value, value, ...)" */
123647        nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
123648      }
123649      assert( nIn>0 );  /* RHS always has 2 or more terms...  The parser
123650                        ** changes "x IN (?)" into "x=?". */
123651
123652    }else if( eOp & (WO_EQ|WO_IS) ){
123653      int iCol = pProbe->aiColumn[saved_nEq];
123654      pNew->wsFlags |= WHERE_COLUMN_EQ;
123655      assert( saved_nEq==pNew->u.btree.nEq );
123656      if( iCol==XN_ROWID
123657       || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
123658      ){
123659        if( iCol>=0 && pProbe->uniqNotNull==0 ){
123660          pNew->wsFlags |= WHERE_UNQ_WANTED;
123661        }else{
123662          pNew->wsFlags |= WHERE_ONEROW;
123663        }
123664      }
123665    }else if( eOp & WO_ISNULL ){
123666      pNew->wsFlags |= WHERE_COLUMN_NULL;
123667    }else if( eOp & (WO_GT|WO_GE) ){
123668      testcase( eOp & WO_GT );
123669      testcase( eOp & WO_GE );
123670      pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
123671      pBtm = pTerm;
123672      pTop = 0;
123673      if( pTerm->wtFlags & TERM_LIKEOPT ){
123674        /* Range contraints that come from the LIKE optimization are
123675        ** always used in pairs. */
123676        pTop = &pTerm[1];
123677        assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
123678        assert( pTop->wtFlags & TERM_LIKEOPT );
123679        assert( pTop->eOperator==WO_LT );
123680        if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
123681        pNew->aLTerm[pNew->nLTerm++] = pTop;
123682        pNew->wsFlags |= WHERE_TOP_LIMIT;
123683      }
123684    }else{
123685      assert( eOp & (WO_LT|WO_LE) );
123686      testcase( eOp & WO_LT );
123687      testcase( eOp & WO_LE );
123688      pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
123689      pTop = pTerm;
123690      pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
123691                     pNew->aLTerm[pNew->nLTerm-2] : 0;
123692    }
123693
123694    /* At this point pNew->nOut is set to the number of rows expected to
123695    ** be visited by the index scan before considering term pTerm, or the
123696    ** values of nIn and nInMul. In other words, assuming that all
123697    ** "x IN(...)" terms are replaced with "x = ?". This block updates
123698    ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */
123699    assert( pNew->nOut==saved_nOut );
123700    if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
123701      /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
123702      ** data, using some other estimate.  */
123703      whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
123704    }else{
123705      int nEq = ++pNew->u.btree.nEq;
123706      assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
123707
123708      assert( pNew->nOut==saved_nOut );
123709      if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
123710        assert( (eOp & WO_IN) || nIn==0 );
123711        testcase( eOp & WO_IN );
123712        pNew->nOut += pTerm->truthProb;
123713        pNew->nOut -= nIn;
123714      }else{
123715#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
123716        tRowcnt nOut = 0;
123717        if( nInMul==0
123718         && pProbe->nSample
123719         && pNew->u.btree.nEq<=pProbe->nSampleCol
123720         && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
123721        ){
123722          Expr *pExpr = pTerm->pExpr;
123723          if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
123724            testcase( eOp & WO_EQ );
123725            testcase( eOp & WO_IS );
123726            testcase( eOp & WO_ISNULL );
123727            rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
123728          }else{
123729            rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
123730          }
123731          if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
123732          if( rc!=SQLITE_OK ) break;          /* Jump out of the pTerm loop */
123733          if( nOut ){
123734            pNew->nOut = sqlite3LogEst(nOut);
123735            if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
123736            pNew->nOut -= nIn;
123737          }
123738        }
123739        if( nOut==0 )
123740#endif
123741        {
123742          pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
123743          if( eOp & WO_ISNULL ){
123744            /* TUNING: If there is no likelihood() value, assume that a
123745            ** "col IS NULL" expression matches twice as many rows
123746            ** as (col=?). */
123747            pNew->nOut += 10;
123748          }
123749        }
123750      }
123751    }
123752
123753    /* Set rCostIdx to the cost of visiting selected rows in index. Add
123754    ** it to pNew->rRun, which is currently set to the cost of the index
123755    ** seek only. Then, if this is a non-covering index, add the cost of
123756    ** visiting the rows in the main table.  */
123757    rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
123758    pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
123759    if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
123760      pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
123761    }
123762    ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
123763
123764    nOutUnadjusted = pNew->nOut;
123765    pNew->rRun += nInMul + nIn;
123766    pNew->nOut += nInMul + nIn;
123767    whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
123768    rc = whereLoopInsert(pBuilder, pNew);
123769
123770    if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
123771      pNew->nOut = saved_nOut;
123772    }else{
123773      pNew->nOut = nOutUnadjusted;
123774    }
123775
123776    if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
123777     && pNew->u.btree.nEq<pProbe->nColumn
123778    ){
123779      whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
123780    }
123781    pNew->nOut = saved_nOut;
123782#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
123783    pBuilder->nRecValid = nRecValid;
123784#endif
123785  }
123786  pNew->prereq = saved_prereq;
123787  pNew->u.btree.nEq = saved_nEq;
123788  pNew->nSkip = saved_nSkip;
123789  pNew->wsFlags = saved_wsFlags;
123790  pNew->nOut = saved_nOut;
123791  pNew->nLTerm = saved_nLTerm;
123792
123793  /* Consider using a skip-scan if there are no WHERE clause constraints
123794  ** available for the left-most terms of the index, and if the average
123795  ** number of repeats in the left-most terms is at least 18.
123796  **
123797  ** The magic number 18 is selected on the basis that scanning 17 rows
123798  ** is almost always quicker than an index seek (even though if the index
123799  ** contains fewer than 2^17 rows we assume otherwise in other parts of
123800  ** the code). And, even if it is not, it should not be too much slower.
123801  ** On the other hand, the extra seeks could end up being significantly
123802  ** more expensive.  */
123803  assert( 42==sqlite3LogEst(18) );
123804  if( saved_nEq==saved_nSkip
123805   && saved_nEq+1<pProbe->nKeyCol
123806   && pProbe->noSkipScan==0
123807   && pProbe->aiRowLogEst[saved_nEq+1]>=42  /* TUNING: Minimum for skip-scan */
123808   && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
123809  ){
123810    LogEst nIter;
123811    pNew->u.btree.nEq++;
123812    pNew->nSkip++;
123813    pNew->aLTerm[pNew->nLTerm++] = 0;
123814    pNew->wsFlags |= WHERE_SKIPSCAN;
123815    nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
123816    pNew->nOut -= nIter;
123817    /* TUNING:  Because uncertainties in the estimates for skip-scan queries,
123818    ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
123819    nIter += 5;
123820    whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
123821    pNew->nOut = saved_nOut;
123822    pNew->u.btree.nEq = saved_nEq;
123823    pNew->nSkip = saved_nSkip;
123824    pNew->wsFlags = saved_wsFlags;
123825  }
123826
123827  return rc;
123828}
123829
123830/*
123831** Return True if it is possible that pIndex might be useful in
123832** implementing the ORDER BY clause in pBuilder.
123833**
123834** Return False if pBuilder does not contain an ORDER BY clause or
123835** if there is no way for pIndex to be useful in implementing that
123836** ORDER BY clause.
123837*/
123838static int indexMightHelpWithOrderBy(
123839  WhereLoopBuilder *pBuilder,
123840  Index *pIndex,
123841  int iCursor
123842){
123843  ExprList *pOB;
123844  ExprList *aColExpr;
123845  int ii, jj;
123846
123847  if( pIndex->bUnordered ) return 0;
123848  if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
123849  for(ii=0; ii<pOB->nExpr; ii++){
123850    Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
123851    if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
123852      if( pExpr->iColumn<0 ) return 1;
123853      for(jj=0; jj<pIndex->nKeyCol; jj++){
123854        if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
123855      }
123856    }else if( (aColExpr = pIndex->aColExpr)!=0 ){
123857      for(jj=0; jj<pIndex->nKeyCol; jj++){
123858        if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
123859        if( sqlite3ExprCompare(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
123860          return 1;
123861        }
123862      }
123863    }
123864  }
123865  return 0;
123866}
123867
123868/*
123869** Return a bitmask where 1s indicate that the corresponding column of
123870** the table is used by an index.  Only the first 63 columns are considered.
123871*/
123872static Bitmask columnsInIndex(Index *pIdx){
123873  Bitmask m = 0;
123874  int j;
123875  for(j=pIdx->nColumn-1; j>=0; j--){
123876    int x = pIdx->aiColumn[j];
123877    if( x>=0 ){
123878      testcase( x==BMS-1 );
123879      testcase( x==BMS-2 );
123880      if( x<BMS-1 ) m |= MASKBIT(x);
123881    }
123882  }
123883  return m;
123884}
123885
123886/* Check to see if a partial index with pPartIndexWhere can be used
123887** in the current query.  Return true if it can be and false if not.
123888*/
123889static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
123890  int i;
123891  WhereTerm *pTerm;
123892  while( pWhere->op==TK_AND ){
123893    if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
123894    pWhere = pWhere->pRight;
123895  }
123896  for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
123897    Expr *pExpr = pTerm->pExpr;
123898    if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
123899     && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
123900    ){
123901      return 1;
123902    }
123903  }
123904  return 0;
123905}
123906
123907/*
123908** Add all WhereLoop objects for a single table of the join where the table
123909** is idenfied by pBuilder->pNew->iTab.  That table is guaranteed to be
123910** a b-tree table, not a virtual table.
123911**
123912** The costs (WhereLoop.rRun) of the b-tree loops added by this function
123913** are calculated as follows:
123914**
123915** For a full scan, assuming the table (or index) contains nRow rows:
123916**
123917**     cost = nRow * 3.0                    // full-table scan
123918**     cost = nRow * K                      // scan of covering index
123919**     cost = nRow * (K+3.0)                // scan of non-covering index
123920**
123921** where K is a value between 1.1 and 3.0 set based on the relative
123922** estimated average size of the index and table records.
123923**
123924** For an index scan, where nVisit is the number of index rows visited
123925** by the scan, and nSeek is the number of seek operations required on
123926** the index b-tree:
123927**
123928**     cost = nSeek * (log(nRow) + K * nVisit)          // covering index
123929**     cost = nSeek * (log(nRow) + (K+3.0) * nVisit)    // non-covering index
123930**
123931** Normally, nSeek is 1. nSeek values greater than 1 come about if the
123932** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
123933** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
123934**
123935** The estimated values (nRow, nVisit, nSeek) often contain a large amount
123936** of uncertainty.  For this reason, scoring is designed to pick plans that
123937** "do the least harm" if the estimates are inaccurate.  For example, a
123938** log(nRow) factor is omitted from a non-covering index scan in order to
123939** bias the scoring in favor of using an index, since the worst-case
123940** performance of using an index is far better than the worst-case performance
123941** of a full table scan.
123942*/
123943static int whereLoopAddBtree(
123944  WhereLoopBuilder *pBuilder, /* WHERE clause information */
123945  Bitmask mExtra              /* Extra prerequesites for using this table */
123946){
123947  WhereInfo *pWInfo;          /* WHERE analysis context */
123948  Index *pProbe;              /* An index we are evaluating */
123949  Index sPk;                  /* A fake index object for the primary key */
123950  LogEst aiRowEstPk[2];       /* The aiRowLogEst[] value for the sPk index */
123951  i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
123952  SrcList *pTabList;          /* The FROM clause */
123953  struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
123954  WhereLoop *pNew;            /* Template WhereLoop object */
123955  int rc = SQLITE_OK;         /* Return code */
123956  int iSortIdx = 1;           /* Index number */
123957  int b;                      /* A boolean value */
123958  LogEst rSize;               /* number of rows in the table */
123959  LogEst rLogSize;            /* Logarithm of the number of rows in the table */
123960  WhereClause *pWC;           /* The parsed WHERE clause */
123961  Table *pTab;                /* Table being queried */
123962
123963  pNew = pBuilder->pNew;
123964  pWInfo = pBuilder->pWInfo;
123965  pTabList = pWInfo->pTabList;
123966  pSrc = pTabList->a + pNew->iTab;
123967  pTab = pSrc->pTab;
123968  pWC = pBuilder->pWC;
123969  assert( !IsVirtual(pSrc->pTab) );
123970
123971  if( pSrc->pIBIndex ){
123972    /* An INDEXED BY clause specifies a particular index to use */
123973    pProbe = pSrc->pIBIndex;
123974  }else if( !HasRowid(pTab) ){
123975    pProbe = pTab->pIndex;
123976  }else{
123977    /* There is no INDEXED BY clause.  Create a fake Index object in local
123978    ** variable sPk to represent the rowid primary key index.  Make this
123979    ** fake index the first in a chain of Index objects with all of the real
123980    ** indices to follow */
123981    Index *pFirst;                  /* First of real indices on the table */
123982    memset(&sPk, 0, sizeof(Index));
123983    sPk.nKeyCol = 1;
123984    sPk.nColumn = 1;
123985    sPk.aiColumn = &aiColumnPk;
123986    sPk.aiRowLogEst = aiRowEstPk;
123987    sPk.onError = OE_Replace;
123988    sPk.pTable = pTab;
123989    sPk.szIdxRow = pTab->szTabRow;
123990    aiRowEstPk[0] = pTab->nRowLogEst;
123991    aiRowEstPk[1] = 0;
123992    pFirst = pSrc->pTab->pIndex;
123993    if( pSrc->fg.notIndexed==0 ){
123994      /* The real indices of the table are only considered if the
123995      ** NOT INDEXED qualifier is omitted from the FROM clause */
123996      sPk.pNext = pFirst;
123997    }
123998    pProbe = &sPk;
123999  }
124000  rSize = pTab->nRowLogEst;
124001  rLogSize = estLog(rSize);
124002
124003#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
124004  /* Automatic indexes */
124005  if( !pBuilder->pOrSet      /* Not part of an OR optimization */
124006   && (pWInfo->wctrlFlags & WHERE_NO_AUTOINDEX)==0
124007   && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
124008   && pSrc->pIBIndex==0      /* Has no INDEXED BY clause */
124009   && !pSrc->fg.notIndexed   /* Has no NOT INDEXED clause */
124010   && HasRowid(pTab)         /* Not WITHOUT ROWID table. (FIXME: Why not?) */
124011   && !pSrc->fg.isCorrelated /* Not a correlated subquery */
124012   && !pSrc->fg.isRecursive  /* Not a recursive common table expression. */
124013  ){
124014    /* Generate auto-index WhereLoops */
124015    WhereTerm *pTerm;
124016    WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
124017    for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
124018      if( pTerm->prereqRight & pNew->maskSelf ) continue;
124019      if( termCanDriveIndex(pTerm, pSrc, 0) ){
124020        pNew->u.btree.nEq = 1;
124021        pNew->nSkip = 0;
124022        pNew->u.btree.pIndex = 0;
124023        pNew->nLTerm = 1;
124024        pNew->aLTerm[0] = pTerm;
124025        /* TUNING: One-time cost for computing the automatic index is
124026        ** estimated to be X*N*log2(N) where N is the number of rows in
124027        ** the table being indexed and where X is 7 (LogEst=28) for normal
124028        ** tables or 1.375 (LogEst=4) for views and subqueries.  The value
124029        ** of X is smaller for views and subqueries so that the query planner
124030        ** will be more aggressive about generating automatic indexes for
124031        ** those objects, since there is no opportunity to add schema
124032        ** indexes on subqueries and views. */
124033        pNew->rSetup = rLogSize + rSize + 4;
124034        if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
124035          pNew->rSetup += 24;
124036        }
124037        ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
124038        /* TUNING: Each index lookup yields 20 rows in the table.  This
124039        ** is more than the usual guess of 10 rows, since we have no way
124040        ** of knowing how selective the index will ultimately be.  It would
124041        ** not be unreasonable to make this value much larger. */
124042        pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
124043        pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
124044        pNew->wsFlags = WHERE_AUTO_INDEX;
124045        pNew->prereq = mExtra | pTerm->prereqRight;
124046        rc = whereLoopInsert(pBuilder, pNew);
124047      }
124048    }
124049  }
124050#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
124051
124052  /* Loop over all indices
124053  */
124054  for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
124055    if( pProbe->pPartIdxWhere!=0
124056     && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
124057      testcase( pNew->iTab!=pSrc->iCursor );  /* See ticket [98d973b8f5] */
124058      continue;  /* Partial index inappropriate for this query */
124059    }
124060    rSize = pProbe->aiRowLogEst[0];
124061    pNew->u.btree.nEq = 0;
124062    pNew->nSkip = 0;
124063    pNew->nLTerm = 0;
124064    pNew->iSortIdx = 0;
124065    pNew->rSetup = 0;
124066    pNew->prereq = mExtra;
124067    pNew->nOut = rSize;
124068    pNew->u.btree.pIndex = pProbe;
124069    b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
124070    /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
124071    assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
124072    if( pProbe->tnum<=0 ){
124073      /* Integer primary key index */
124074      pNew->wsFlags = WHERE_IPK;
124075
124076      /* Full table scan */
124077      pNew->iSortIdx = b ? iSortIdx : 0;
124078      /* TUNING: Cost of full table scan is (N*3.0). */
124079      pNew->rRun = rSize + 16;
124080      ApplyCostMultiplier(pNew->rRun, pTab->costMult);
124081      whereLoopOutputAdjust(pWC, pNew, rSize);
124082      rc = whereLoopInsert(pBuilder, pNew);
124083      pNew->nOut = rSize;
124084      if( rc ) break;
124085    }else{
124086      Bitmask m;
124087      if( pProbe->isCovering ){
124088        pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
124089        m = 0;
124090      }else{
124091        m = pSrc->colUsed & ~columnsInIndex(pProbe);
124092        pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
124093      }
124094
124095      /* Full scan via index */
124096      if( b
124097       || !HasRowid(pTab)
124098       || ( m==0
124099         && pProbe->bUnordered==0
124100         && (pProbe->szIdxRow<pTab->szTabRow)
124101         && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
124102         && sqlite3GlobalConfig.bUseCis
124103         && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
124104          )
124105      ){
124106        pNew->iSortIdx = b ? iSortIdx : 0;
124107
124108        /* The cost of visiting the index rows is N*K, where K is
124109        ** between 1.1 and 3.0, depending on the relative sizes of the
124110        ** index and table rows. If this is a non-covering index scan,
124111        ** also add the cost of visiting table rows (N*3.0).  */
124112        pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
124113        if( m!=0 ){
124114          pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
124115        }
124116        ApplyCostMultiplier(pNew->rRun, pTab->costMult);
124117        whereLoopOutputAdjust(pWC, pNew, rSize);
124118        rc = whereLoopInsert(pBuilder, pNew);
124119        pNew->nOut = rSize;
124120        if( rc ) break;
124121      }
124122    }
124123
124124    rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
124125#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
124126    sqlite3Stat4ProbeFree(pBuilder->pRec);
124127    pBuilder->nRecValid = 0;
124128    pBuilder->pRec = 0;
124129#endif
124130
124131    /* If there was an INDEXED BY clause, then only that one index is
124132    ** considered. */
124133    if( pSrc->pIBIndex ) break;
124134  }
124135  return rc;
124136}
124137
124138#ifndef SQLITE_OMIT_VIRTUALTABLE
124139/*
124140** Add all WhereLoop objects for a table of the join identified by
124141** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
124142**
124143** If there are no LEFT or CROSS JOIN joins in the query, both mExtra and
124144** mUnusable are set to 0. Otherwise, mExtra is a mask of all FROM clause
124145** entries that occur before the virtual table in the FROM clause and are
124146** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
124147** mUnusable mask contains all FROM clause entries that occur after the
124148** virtual table and are separated from it by at least one LEFT or
124149** CROSS JOIN.
124150**
124151** For example, if the query were:
124152**
124153**   ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
124154**
124155** then mExtra corresponds to (t1, t2) and mUnusable to (t5, t6).
124156**
124157** All the tables in mExtra must be scanned before the current virtual
124158** table. So any terms for which all prerequisites are satisfied by
124159** mExtra may be specified as "usable" in all calls to xBestIndex.
124160** Conversely, all tables in mUnusable must be scanned after the current
124161** virtual table, so any terms for which the prerequisites overlap with
124162** mUnusable should always be configured as "not-usable" for xBestIndex.
124163*/
124164static int whereLoopAddVirtual(
124165  WhereLoopBuilder *pBuilder,  /* WHERE clause information */
124166  Bitmask mExtra,              /* Tables that must be scanned before this one */
124167  Bitmask mUnusable            /* Tables that must be scanned after this one */
124168){
124169  WhereInfo *pWInfo;           /* WHERE analysis context */
124170  Parse *pParse;               /* The parsing context */
124171  WhereClause *pWC;            /* The WHERE clause */
124172  struct SrcList_item *pSrc;   /* The FROM clause term to search */
124173  Table *pTab;
124174  sqlite3 *db;
124175  sqlite3_index_info *pIdxInfo;
124176  struct sqlite3_index_constraint *pIdxCons;
124177  struct sqlite3_index_constraint_usage *pUsage;
124178  WhereTerm *pTerm;
124179  int i, j;
124180  int iTerm, mxTerm;
124181  int nConstraint;
124182  int seenIn = 0;              /* True if an IN operator is seen */
124183  int seenVar = 0;             /* True if a non-constant constraint is seen */
124184  int iPhase;                  /* 0: const w/o IN, 1: const, 2: no IN,  2: IN */
124185  WhereLoop *pNew;
124186  int rc = SQLITE_OK;
124187
124188  assert( (mExtra & mUnusable)==0 );
124189  pWInfo = pBuilder->pWInfo;
124190  pParse = pWInfo->pParse;
124191  db = pParse->db;
124192  pWC = pBuilder->pWC;
124193  pNew = pBuilder->pNew;
124194  pSrc = &pWInfo->pTabList->a[pNew->iTab];
124195  pTab = pSrc->pTab;
124196  assert( IsVirtual(pTab) );
124197  pIdxInfo = allocateIndexInfo(pParse, pWC, mUnusable, pSrc,pBuilder->pOrderBy);
124198  if( pIdxInfo==0 ) return SQLITE_NOMEM;
124199  pNew->prereq = 0;
124200  pNew->rSetup = 0;
124201  pNew->wsFlags = WHERE_VIRTUALTABLE;
124202  pNew->nLTerm = 0;
124203  pNew->u.vtab.needFree = 0;
124204  pUsage = pIdxInfo->aConstraintUsage;
124205  nConstraint = pIdxInfo->nConstraint;
124206  if( whereLoopResize(db, pNew, nConstraint) ){
124207    sqlite3DbFree(db, pIdxInfo);
124208    return SQLITE_NOMEM;
124209  }
124210
124211  for(iPhase=0; iPhase<=3; iPhase++){
124212    if( !seenIn && (iPhase&1)!=0 ){
124213      iPhase++;
124214      if( iPhase>3 ) break;
124215    }
124216    if( !seenVar && iPhase>1 ) break;
124217    pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
124218    for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
124219      j = pIdxCons->iTermOffset;
124220      pTerm = &pWC->a[j];
124221      switch( iPhase ){
124222        case 0:    /* Constants without IN operator */
124223          pIdxCons->usable = 0;
124224          if( (pTerm->eOperator & WO_IN)!=0 ){
124225            seenIn = 1;
124226          }
124227          if( (pTerm->prereqRight & ~mExtra)!=0 ){
124228            seenVar = 1;
124229          }else if( (pTerm->eOperator & WO_IN)==0 ){
124230            pIdxCons->usable = 1;
124231          }
124232          break;
124233        case 1:    /* Constants with IN operators */
124234          assert( seenIn );
124235          pIdxCons->usable = (pTerm->prereqRight & ~mExtra)==0;
124236          break;
124237        case 2:    /* Variables without IN */
124238          assert( seenVar );
124239          pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
124240          break;
124241        default:   /* Variables with IN */
124242          assert( seenVar && seenIn );
124243          pIdxCons->usable = 1;
124244          break;
124245      }
124246    }
124247    memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
124248    if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
124249    pIdxInfo->idxStr = 0;
124250    pIdxInfo->idxNum = 0;
124251    pIdxInfo->needToFreeIdxStr = 0;
124252    pIdxInfo->orderByConsumed = 0;
124253    pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
124254    pIdxInfo->estimatedRows = 25;
124255    pIdxInfo->idxFlags = 0;
124256    rc = vtabBestIndex(pParse, pTab, pIdxInfo);
124257    if( rc ) goto whereLoopAddVtab_exit;
124258    pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
124259    pNew->prereq = mExtra;
124260    mxTerm = -1;
124261    assert( pNew->nLSlot>=nConstraint );
124262    for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
124263    pNew->u.vtab.omitMask = 0;
124264    for(i=0; i<nConstraint; i++, pIdxCons++){
124265      if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
124266        j = pIdxCons->iTermOffset;
124267        if( iTerm>=nConstraint
124268         || j<0
124269         || j>=pWC->nTerm
124270         || pNew->aLTerm[iTerm]!=0
124271        ){
124272          rc = SQLITE_ERROR;
124273          sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
124274          goto whereLoopAddVtab_exit;
124275        }
124276        testcase( iTerm==nConstraint-1 );
124277        testcase( j==0 );
124278        testcase( j==pWC->nTerm-1 );
124279        pTerm = &pWC->a[j];
124280        pNew->prereq |= pTerm->prereqRight;
124281        assert( iTerm<pNew->nLSlot );
124282        pNew->aLTerm[iTerm] = pTerm;
124283        if( iTerm>mxTerm ) mxTerm = iTerm;
124284        testcase( iTerm==15 );
124285        testcase( iTerm==16 );
124286        if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
124287        if( (pTerm->eOperator & WO_IN)!=0 ){
124288          if( pUsage[i].omit==0 ){
124289            /* Do not attempt to use an IN constraint if the virtual table
124290            ** says that the equivalent EQ constraint cannot be safely omitted.
124291            ** If we do attempt to use such a constraint, some rows might be
124292            ** repeated in the output. */
124293            break;
124294          }
124295          /* A virtual table that is constrained by an IN clause may not
124296          ** consume the ORDER BY clause because (1) the order of IN terms
124297          ** is not necessarily related to the order of output terms and
124298          ** (2) Multiple outputs from a single IN value will not merge
124299          ** together.  */
124300          pIdxInfo->orderByConsumed = 0;
124301          pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
124302        }
124303      }
124304    }
124305    if( i>=nConstraint ){
124306      pNew->nLTerm = mxTerm+1;
124307      assert( pNew->nLTerm<=pNew->nLSlot );
124308      pNew->u.vtab.idxNum = pIdxInfo->idxNum;
124309      pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
124310      pIdxInfo->needToFreeIdxStr = 0;
124311      pNew->u.vtab.idxStr = pIdxInfo->idxStr;
124312      pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
124313                                      pIdxInfo->nOrderBy : 0);
124314      pNew->rSetup = 0;
124315      pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
124316      pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
124317
124318      /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
124319      ** that the scan will visit at most one row. Clear it otherwise. */
124320      if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
124321        pNew->wsFlags |= WHERE_ONEROW;
124322      }else{
124323        pNew->wsFlags &= ~WHERE_ONEROW;
124324      }
124325      whereLoopInsert(pBuilder, pNew);
124326      if( pNew->u.vtab.needFree ){
124327        sqlite3_free(pNew->u.vtab.idxStr);
124328        pNew->u.vtab.needFree = 0;
124329      }
124330    }
124331  }
124332
124333whereLoopAddVtab_exit:
124334  if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
124335  sqlite3DbFree(db, pIdxInfo);
124336  return rc;
124337}
124338#endif /* SQLITE_OMIT_VIRTUALTABLE */
124339
124340/*
124341** Add WhereLoop entries to handle OR terms.  This works for either
124342** btrees or virtual tables.
124343*/
124344static int whereLoopAddOr(
124345  WhereLoopBuilder *pBuilder,
124346  Bitmask mExtra,
124347  Bitmask mUnusable
124348){
124349  WhereInfo *pWInfo = pBuilder->pWInfo;
124350  WhereClause *pWC;
124351  WhereLoop *pNew;
124352  WhereTerm *pTerm, *pWCEnd;
124353  int rc = SQLITE_OK;
124354  int iCur;
124355  WhereClause tempWC;
124356  WhereLoopBuilder sSubBuild;
124357  WhereOrSet sSum, sCur;
124358  struct SrcList_item *pItem;
124359
124360  pWC = pBuilder->pWC;
124361  pWCEnd = pWC->a + pWC->nTerm;
124362  pNew = pBuilder->pNew;
124363  memset(&sSum, 0, sizeof(sSum));
124364  pItem = pWInfo->pTabList->a + pNew->iTab;
124365  iCur = pItem->iCursor;
124366
124367  for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
124368    if( (pTerm->eOperator & WO_OR)!=0
124369     && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
124370    ){
124371      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
124372      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
124373      WhereTerm *pOrTerm;
124374      int once = 1;
124375      int i, j;
124376
124377      sSubBuild = *pBuilder;
124378      sSubBuild.pOrderBy = 0;
124379      sSubBuild.pOrSet = &sCur;
124380
124381      WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
124382      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
124383        if( (pOrTerm->eOperator & WO_AND)!=0 ){
124384          sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
124385        }else if( pOrTerm->leftCursor==iCur ){
124386          tempWC.pWInfo = pWC->pWInfo;
124387          tempWC.pOuter = pWC;
124388          tempWC.op = TK_AND;
124389          tempWC.nTerm = 1;
124390          tempWC.a = pOrTerm;
124391          sSubBuild.pWC = &tempWC;
124392        }else{
124393          continue;
124394        }
124395        sCur.n = 0;
124396#ifdef WHERETRACE_ENABLED
124397        WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
124398                   (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
124399        if( sqlite3WhereTrace & 0x400 ){
124400          for(i=0; i<sSubBuild.pWC->nTerm; i++){
124401            whereTermPrint(&sSubBuild.pWC->a[i], i);
124402          }
124403        }
124404#endif
124405#ifndef SQLITE_OMIT_VIRTUALTABLE
124406        if( IsVirtual(pItem->pTab) ){
124407          rc = whereLoopAddVirtual(&sSubBuild, mExtra, mUnusable);
124408        }else
124409#endif
124410        {
124411          rc = whereLoopAddBtree(&sSubBuild, mExtra);
124412        }
124413        if( rc==SQLITE_OK ){
124414          rc = whereLoopAddOr(&sSubBuild, mExtra, mUnusable);
124415        }
124416        assert( rc==SQLITE_OK || sCur.n==0 );
124417        if( sCur.n==0 ){
124418          sSum.n = 0;
124419          break;
124420        }else if( once ){
124421          whereOrMove(&sSum, &sCur);
124422          once = 0;
124423        }else{
124424          WhereOrSet sPrev;
124425          whereOrMove(&sPrev, &sSum);
124426          sSum.n = 0;
124427          for(i=0; i<sPrev.n; i++){
124428            for(j=0; j<sCur.n; j++){
124429              whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
124430                            sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
124431                            sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
124432            }
124433          }
124434        }
124435      }
124436      pNew->nLTerm = 1;
124437      pNew->aLTerm[0] = pTerm;
124438      pNew->wsFlags = WHERE_MULTI_OR;
124439      pNew->rSetup = 0;
124440      pNew->iSortIdx = 0;
124441      memset(&pNew->u, 0, sizeof(pNew->u));
124442      for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
124443        /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
124444        ** of all sub-scans required by the OR-scan. However, due to rounding
124445        ** errors, it may be that the cost of the OR-scan is equal to its
124446        ** most expensive sub-scan. Add the smallest possible penalty
124447        ** (equivalent to multiplying the cost by 1.07) to ensure that
124448        ** this does not happen. Otherwise, for WHERE clauses such as the
124449        ** following where there is an index on "y":
124450        **
124451        **     WHERE likelihood(x=?, 0.99) OR y=?
124452        **
124453        ** the planner may elect to "OR" together a full-table scan and an
124454        ** index lookup. And other similarly odd results.  */
124455        pNew->rRun = sSum.a[i].rRun + 1;
124456        pNew->nOut = sSum.a[i].nOut;
124457        pNew->prereq = sSum.a[i].prereq;
124458        rc = whereLoopInsert(pBuilder, pNew);
124459      }
124460      WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
124461    }
124462  }
124463  return rc;
124464}
124465
124466/*
124467** Add all WhereLoop objects for all tables
124468*/
124469static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
124470  WhereInfo *pWInfo = pBuilder->pWInfo;
124471  Bitmask mExtra = 0;
124472  Bitmask mPrior = 0;
124473  int iTab;
124474  SrcList *pTabList = pWInfo->pTabList;
124475  struct SrcList_item *pItem;
124476  struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
124477  sqlite3 *db = pWInfo->pParse->db;
124478  int rc = SQLITE_OK;
124479  WhereLoop *pNew;
124480  u8 priorJointype = 0;
124481
124482  /* Loop over the tables in the join, from left to right */
124483  pNew = pBuilder->pNew;
124484  whereLoopInit(pNew);
124485  for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
124486    Bitmask mUnusable = 0;
124487    pNew->iTab = iTab;
124488    pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
124489    if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
124490      /* This condition is true when pItem is the FROM clause term on the
124491      ** right-hand-side of a LEFT or CROSS JOIN.  */
124492      mExtra = mPrior;
124493    }
124494    priorJointype = pItem->fg.jointype;
124495    if( IsVirtual(pItem->pTab) ){
124496      struct SrcList_item *p;
124497      for(p=&pItem[1]; p<pEnd; p++){
124498        if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
124499          mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
124500        }
124501      }
124502      rc = whereLoopAddVirtual(pBuilder, mExtra, mUnusable);
124503    }else{
124504      rc = whereLoopAddBtree(pBuilder, mExtra);
124505    }
124506    if( rc==SQLITE_OK ){
124507      rc = whereLoopAddOr(pBuilder, mExtra, mUnusable);
124508    }
124509    mPrior |= pNew->maskSelf;
124510    if( rc || db->mallocFailed ) break;
124511  }
124512
124513  whereLoopClear(db, pNew);
124514  return rc;
124515}
124516
124517/*
124518** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
124519** parameters) to see if it outputs rows in the requested ORDER BY
124520** (or GROUP BY) without requiring a separate sort operation.  Return N:
124521**
124522**   N>0:   N terms of the ORDER BY clause are satisfied
124523**   N==0:  No terms of the ORDER BY clause are satisfied
124524**   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.
124525**
124526** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
124527** strict.  With GROUP BY and DISTINCT the only requirement is that
124528** equivalent rows appear immediately adjacent to one another.  GROUP BY
124529** and DISTINCT do not require rows to appear in any particular order as long
124530** as equivalent rows are grouped together.  Thus for GROUP BY and DISTINCT
124531** the pOrderBy terms can be matched in any order.  With ORDER BY, the
124532** pOrderBy terms must be matched in strict left-to-right order.
124533*/
124534static i8 wherePathSatisfiesOrderBy(
124535  WhereInfo *pWInfo,    /* The WHERE clause */
124536  ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */
124537  WherePath *pPath,     /* The WherePath to check */
124538  u16 wctrlFlags,       /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
124539  u16 nLoop,            /* Number of entries in pPath->aLoop[] */
124540  WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */
124541  Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */
124542){
124543  u8 revSet;            /* True if rev is known */
124544  u8 rev;               /* Composite sort order */
124545  u8 revIdx;            /* Index sort order */
124546  u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */
124547  u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */
124548  u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */
124549  u16 nKeyCol;          /* Number of key columns in pIndex */
124550  u16 nColumn;          /* Total number of ordered columns in the index */
124551  u16 nOrderBy;         /* Number terms in the ORDER BY clause */
124552  int iLoop;            /* Index of WhereLoop in pPath being processed */
124553  int i, j;             /* Loop counters */
124554  int iCur;             /* Cursor number for current WhereLoop */
124555  int iColumn;          /* A column number within table iCur */
124556  WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
124557  WhereTerm *pTerm;     /* A single term of the WHERE clause */
124558  Expr *pOBExpr;        /* An expression from the ORDER BY clause */
124559  CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */
124560  Index *pIndex;        /* The index associated with pLoop */
124561  sqlite3 *db = pWInfo->pParse->db;  /* Database connection */
124562  Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */
124563  Bitmask obDone;       /* Mask of all ORDER BY terms */
124564  Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */
124565  Bitmask ready;              /* Mask of inner loops */
124566
124567  /*
124568  ** We say the WhereLoop is "one-row" if it generates no more than one
124569  ** row of output.  A WhereLoop is one-row if all of the following are true:
124570  **  (a) All index columns match with WHERE_COLUMN_EQ.
124571  **  (b) The index is unique
124572  ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
124573  ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
124574  **
124575  ** We say the WhereLoop is "order-distinct" if the set of columns from
124576  ** that WhereLoop that are in the ORDER BY clause are different for every
124577  ** row of the WhereLoop.  Every one-row WhereLoop is automatically
124578  ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
124579  ** is not order-distinct. To be order-distinct is not quite the same as being
124580  ** UNIQUE since a UNIQUE column or index can have multiple rows that
124581  ** are NULL and NULL values are equivalent for the purpose of order-distinct.
124582  ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
124583  **
124584  ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
124585  ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
124586  ** automatically order-distinct.
124587  */
124588
124589  assert( pOrderBy!=0 );
124590  if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
124591
124592  nOrderBy = pOrderBy->nExpr;
124593  testcase( nOrderBy==BMS-1 );
124594  if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */
124595  isOrderDistinct = 1;
124596  obDone = MASKBIT(nOrderBy)-1;
124597  orderDistinctMask = 0;
124598  ready = 0;
124599  for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
124600    if( iLoop>0 ) ready |= pLoop->maskSelf;
124601    pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
124602    if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
124603      if( pLoop->u.vtab.isOrdered ) obSat = obDone;
124604      break;
124605    }
124606    iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
124607
124608    /* Mark off any ORDER BY term X that is a column in the table of
124609    ** the current loop for which there is term in the WHERE
124610    ** clause of the form X IS NULL or X=? that reference only outer
124611    ** loops.
124612    */
124613    for(i=0; i<nOrderBy; i++){
124614      if( MASKBIT(i) & obSat ) continue;
124615      pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
124616      if( pOBExpr->op!=TK_COLUMN ) continue;
124617      if( pOBExpr->iTable!=iCur ) continue;
124618      pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
124619                       ~ready, WO_EQ|WO_ISNULL|WO_IS, 0);
124620      if( pTerm==0 ) continue;
124621      if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
124622        const char *z1, *z2;
124623        pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
124624        if( !pColl ) pColl = db->pDfltColl;
124625        z1 = pColl->zName;
124626        pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
124627        if( !pColl ) pColl = db->pDfltColl;
124628        z2 = pColl->zName;
124629        if( sqlite3StrICmp(z1, z2)!=0 ) continue;
124630        testcase( pTerm->pExpr->op==TK_IS );
124631      }
124632      obSat |= MASKBIT(i);
124633    }
124634
124635    if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
124636      if( pLoop->wsFlags & WHERE_IPK ){
124637        pIndex = 0;
124638        nKeyCol = 0;
124639        nColumn = 1;
124640      }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
124641        return 0;
124642      }else{
124643        nKeyCol = pIndex->nKeyCol;
124644        nColumn = pIndex->nColumn;
124645        assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
124646        assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
124647                          || !HasRowid(pIndex->pTable));
124648        isOrderDistinct = IsUniqueIndex(pIndex);
124649      }
124650
124651      /* Loop through all columns of the index and deal with the ones
124652      ** that are not constrained by == or IN.
124653      */
124654      rev = revSet = 0;
124655      distinctColumns = 0;
124656      for(j=0; j<nColumn; j++){
124657        u8 bOnce;   /* True to run the ORDER BY search loop */
124658
124659        /* Skip over == and IS NULL terms */
124660        if( j<pLoop->u.btree.nEq
124661         && pLoop->nSkip==0
124662         && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL|WO_IS))!=0
124663        ){
124664          if( i & WO_ISNULL ){
124665            testcase( isOrderDistinct );
124666            isOrderDistinct = 0;
124667          }
124668          continue;
124669        }
124670
124671        /* Get the column number in the table (iColumn) and sort order
124672        ** (revIdx) for the j-th column of the index.
124673        */
124674        if( pIndex ){
124675          iColumn = pIndex->aiColumn[j];
124676          revIdx = pIndex->aSortOrder[j];
124677          if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
124678        }else{
124679          iColumn = XN_ROWID;
124680          revIdx = 0;
124681        }
124682
124683        /* An unconstrained column that might be NULL means that this
124684        ** WhereLoop is not well-ordered
124685        */
124686        if( isOrderDistinct
124687         && iColumn>=0
124688         && j>=pLoop->u.btree.nEq
124689         && pIndex->pTable->aCol[iColumn].notNull==0
124690        ){
124691          isOrderDistinct = 0;
124692        }
124693
124694        /* Find the ORDER BY term that corresponds to the j-th column
124695        ** of the index and mark that ORDER BY term off
124696        */
124697        bOnce = 1;
124698        isMatch = 0;
124699        for(i=0; bOnce && i<nOrderBy; i++){
124700          if( MASKBIT(i) & obSat ) continue;
124701          pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
124702          testcase( wctrlFlags & WHERE_GROUPBY );
124703          testcase( wctrlFlags & WHERE_DISTINCTBY );
124704          if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
124705          if( iColumn>=(-1) ){
124706            if( pOBExpr->op!=TK_COLUMN ) continue;
124707            if( pOBExpr->iTable!=iCur ) continue;
124708            if( pOBExpr->iColumn!=iColumn ) continue;
124709          }else{
124710            if( sqlite3ExprCompare(pOBExpr,pIndex->aColExpr->a[j].pExpr,iCur) ){
124711              continue;
124712            }
124713          }
124714          if( iColumn>=0 ){
124715            pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
124716            if( !pColl ) pColl = db->pDfltColl;
124717            if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
124718          }
124719          isMatch = 1;
124720          break;
124721        }
124722        if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
124723          /* Make sure the sort order is compatible in an ORDER BY clause.
124724          ** Sort order is irrelevant for a GROUP BY clause. */
124725          if( revSet ){
124726            if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
124727          }else{
124728            rev = revIdx ^ pOrderBy->a[i].sortOrder;
124729            if( rev ) *pRevMask |= MASKBIT(iLoop);
124730            revSet = 1;
124731          }
124732        }
124733        if( isMatch ){
124734          if( iColumn<0 ){
124735            testcase( distinctColumns==0 );
124736            distinctColumns = 1;
124737          }
124738          obSat |= MASKBIT(i);
124739        }else{
124740          /* No match found */
124741          if( j==0 || j<nKeyCol ){
124742            testcase( isOrderDistinct!=0 );
124743            isOrderDistinct = 0;
124744          }
124745          break;
124746        }
124747      } /* end Loop over all index columns */
124748      if( distinctColumns ){
124749        testcase( isOrderDistinct==0 );
124750        isOrderDistinct = 1;
124751      }
124752    } /* end-if not one-row */
124753
124754    /* Mark off any other ORDER BY terms that reference pLoop */
124755    if( isOrderDistinct ){
124756      orderDistinctMask |= pLoop->maskSelf;
124757      for(i=0; i<nOrderBy; i++){
124758        Expr *p;
124759        Bitmask mTerm;
124760        if( MASKBIT(i) & obSat ) continue;
124761        p = pOrderBy->a[i].pExpr;
124762        mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
124763        if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
124764        if( (mTerm&~orderDistinctMask)==0 ){
124765          obSat |= MASKBIT(i);
124766        }
124767      }
124768    }
124769  } /* End the loop over all WhereLoops from outer-most down to inner-most */
124770  if( obSat==obDone ) return (i8)nOrderBy;
124771  if( !isOrderDistinct ){
124772    for(i=nOrderBy-1; i>0; i--){
124773      Bitmask m = MASKBIT(i) - 1;
124774      if( (obSat&m)==m ) return i;
124775    }
124776    return 0;
124777  }
124778  return -1;
124779}
124780
124781
124782/*
124783** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
124784** the planner assumes that the specified pOrderBy list is actually a GROUP
124785** BY clause - and so any order that groups rows as required satisfies the
124786** request.
124787**
124788** Normally, in this case it is not possible for the caller to determine
124789** whether or not the rows are really being delivered in sorted order, or
124790** just in some other order that provides the required grouping. However,
124791** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
124792** this function may be called on the returned WhereInfo object. It returns
124793** true if the rows really will be sorted in the specified order, or false
124794** otherwise.
124795**
124796** For example, assuming:
124797**
124798**   CREATE INDEX i1 ON t1(x, Y);
124799**
124800** then
124801**
124802**   SELECT * FROM t1 GROUP BY x,y ORDER BY x,y;   -- IsSorted()==1
124803**   SELECT * FROM t1 GROUP BY y,x ORDER BY y,x;   -- IsSorted()==0
124804*/
124805SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
124806  assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
124807  assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
124808  return pWInfo->sorted;
124809}
124810
124811#ifdef WHERETRACE_ENABLED
124812/* For debugging use only: */
124813static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
124814  static char zName[65];
124815  int i;
124816  for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
124817  if( pLast ) zName[i++] = pLast->cId;
124818  zName[i] = 0;
124819  return zName;
124820}
124821#endif
124822
124823/*
124824** Return the cost of sorting nRow rows, assuming that the keys have
124825** nOrderby columns and that the first nSorted columns are already in
124826** order.
124827*/
124828static LogEst whereSortingCost(
124829  WhereInfo *pWInfo,
124830  LogEst nRow,
124831  int nOrderBy,
124832  int nSorted
124833){
124834  /* TUNING: Estimated cost of a full external sort, where N is
124835  ** the number of rows to sort is:
124836  **
124837  **   cost = (3.0 * N * log(N)).
124838  **
124839  ** Or, if the order-by clause has X terms but only the last Y
124840  ** terms are out of order, then block-sorting will reduce the
124841  ** sorting cost to:
124842  **
124843  **   cost = (3.0 * N * log(N)) * (Y/X)
124844  **
124845  ** The (Y/X) term is implemented using stack variable rScale
124846  ** below.  */
124847  LogEst rScale, rSortCost;
124848  assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
124849  rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
124850  rSortCost = nRow + estLog(nRow) + rScale + 16;
124851
124852  /* TUNING: The cost of implementing DISTINCT using a B-TREE is
124853  ** similar but with a larger constant of proportionality.
124854  ** Multiply by an additional factor of 3.0.  */
124855  if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
124856    rSortCost += 16;
124857  }
124858
124859  return rSortCost;
124860}
124861
124862/*
124863** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
124864** attempts to find the lowest cost path that visits each WhereLoop
124865** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
124866**
124867** Assume that the total number of output rows that will need to be sorted
124868** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
124869** costs if nRowEst==0.
124870**
124871** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
124872** error occurs.
124873*/
124874static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
124875  int mxChoice;             /* Maximum number of simultaneous paths tracked */
124876  int nLoop;                /* Number of terms in the join */
124877  Parse *pParse;            /* Parsing context */
124878  sqlite3 *db;              /* The database connection */
124879  int iLoop;                /* Loop counter over the terms of the join */
124880  int ii, jj;               /* Loop counters */
124881  int mxI = 0;              /* Index of next entry to replace */
124882  int nOrderBy;             /* Number of ORDER BY clause terms */
124883  LogEst mxCost = 0;        /* Maximum cost of a set of paths */
124884  LogEst mxUnsorted = 0;    /* Maximum unsorted cost of a set of path */
124885  int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
124886  WherePath *aFrom;         /* All nFrom paths at the previous level */
124887  WherePath *aTo;           /* The nTo best paths at the current level */
124888  WherePath *pFrom;         /* An element of aFrom[] that we are working on */
124889  WherePath *pTo;           /* An element of aTo[] that we are working on */
124890  WhereLoop *pWLoop;        /* One of the WhereLoop objects */
124891  WhereLoop **pX;           /* Used to divy up the pSpace memory */
124892  LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */
124893  char *pSpace;             /* Temporary memory used by this routine */
124894  int nSpace;               /* Bytes of space allocated at pSpace */
124895
124896  pParse = pWInfo->pParse;
124897  db = pParse->db;
124898  nLoop = pWInfo->nLevel;
124899  /* TUNING: For simple queries, only the best path is tracked.
124900  ** For 2-way joins, the 5 best paths are followed.
124901  ** For joins of 3 or more tables, track the 10 best paths */
124902  mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
124903  assert( nLoop<=pWInfo->pTabList->nSrc );
124904  WHERETRACE(0x002, ("---- begin solver.  (nRowEst=%d)\n", nRowEst));
124905
124906  /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
124907  ** case the purpose of this call is to estimate the number of rows returned
124908  ** by the overall query. Once this estimate has been obtained, the caller
124909  ** will invoke this function a second time, passing the estimate as the
124910  ** nRowEst parameter.  */
124911  if( pWInfo->pOrderBy==0 || nRowEst==0 ){
124912    nOrderBy = 0;
124913  }else{
124914    nOrderBy = pWInfo->pOrderBy->nExpr;
124915  }
124916
124917  /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
124918  nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
124919  nSpace += sizeof(LogEst) * nOrderBy;
124920  pSpace = sqlite3DbMallocRaw(db, nSpace);
124921  if( pSpace==0 ) return SQLITE_NOMEM;
124922  aTo = (WherePath*)pSpace;
124923  aFrom = aTo+mxChoice;
124924  memset(aFrom, 0, sizeof(aFrom[0]));
124925  pX = (WhereLoop**)(aFrom+mxChoice);
124926  for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
124927    pFrom->aLoop = pX;
124928  }
124929  if( nOrderBy ){
124930    /* If there is an ORDER BY clause and it is not being ignored, set up
124931    ** space for the aSortCost[] array. Each element of the aSortCost array
124932    ** is either zero - meaning it has not yet been initialized - or the
124933    ** cost of sorting nRowEst rows of data where the first X terms of
124934    ** the ORDER BY clause are already in order, where X is the array
124935    ** index.  */
124936    aSortCost = (LogEst*)pX;
124937    memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
124938  }
124939  assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
124940  assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
124941
124942  /* Seed the search with a single WherePath containing zero WhereLoops.
124943  **
124944  ** TUNING: Do not let the number of iterations go above 28.  If the cost
124945  ** of computing an automatic index is not paid back within the first 28
124946  ** rows, then do not use the automatic index. */
124947  aFrom[0].nRow = MIN(pParse->nQueryLoop, 48);  assert( 48==sqlite3LogEst(28) );
124948  nFrom = 1;
124949  assert( aFrom[0].isOrdered==0 );
124950  if( nOrderBy ){
124951    /* If nLoop is zero, then there are no FROM terms in the query. Since
124952    ** in this case the query may return a maximum of one row, the results
124953    ** are already in the requested order. Set isOrdered to nOrderBy to
124954    ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
124955    ** -1, indicating that the result set may or may not be ordered,
124956    ** depending on the loops added to the current plan.  */
124957    aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
124958  }
124959
124960  /* Compute successively longer WherePaths using the previous generation
124961  ** of WherePaths as the basis for the next.  Keep track of the mxChoice
124962  ** best paths at each generation */
124963  for(iLoop=0; iLoop<nLoop; iLoop++){
124964    nTo = 0;
124965    for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
124966      for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
124967        LogEst nOut;                      /* Rows visited by (pFrom+pWLoop) */
124968        LogEst rCost;                     /* Cost of path (pFrom+pWLoop) */
124969        LogEst rUnsorted;                 /* Unsorted cost of (pFrom+pWLoop) */
124970        i8 isOrdered = pFrom->isOrdered;  /* isOrdered for (pFrom+pWLoop) */
124971        Bitmask maskNew;                  /* Mask of src visited by (..) */
124972        Bitmask revMask = 0;              /* Mask of rev-order loops for (..) */
124973
124974        if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
124975        if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
124976        /* At this point, pWLoop is a candidate to be the next loop.
124977        ** Compute its cost */
124978        rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
124979        rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
124980        nOut = pFrom->nRow + pWLoop->nOut;
124981        maskNew = pFrom->maskLoop | pWLoop->maskSelf;
124982        if( isOrdered<0 ){
124983          isOrdered = wherePathSatisfiesOrderBy(pWInfo,
124984                       pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
124985                       iLoop, pWLoop, &revMask);
124986        }else{
124987          revMask = pFrom->revLoop;
124988        }
124989        if( isOrdered>=0 && isOrdered<nOrderBy ){
124990          if( aSortCost[isOrdered]==0 ){
124991            aSortCost[isOrdered] = whereSortingCost(
124992                pWInfo, nRowEst, nOrderBy, isOrdered
124993            );
124994          }
124995          rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
124996
124997          WHERETRACE(0x002,
124998              ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
124999               aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
125000               rUnsorted, rCost));
125001        }else{
125002          rCost = rUnsorted;
125003        }
125004
125005        /* Check to see if pWLoop should be added to the set of
125006        ** mxChoice best-so-far paths.
125007        **
125008        ** First look for an existing path among best-so-far paths
125009        ** that covers the same set of loops and has the same isOrdered
125010        ** setting as the current path candidate.
125011        **
125012        ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
125013        ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
125014        ** of legal values for isOrdered, -1..64.
125015        */
125016        for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
125017          if( pTo->maskLoop==maskNew
125018           && ((pTo->isOrdered^isOrdered)&0x80)==0
125019          ){
125020            testcase( jj==nTo-1 );
125021            break;
125022          }
125023        }
125024        if( jj>=nTo ){
125025          /* None of the existing best-so-far paths match the candidate. */
125026          if( nTo>=mxChoice
125027           && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
125028          ){
125029            /* The current candidate is no better than any of the mxChoice
125030            ** paths currently in the best-so-far buffer.  So discard
125031            ** this candidate as not viable. */
125032#ifdef WHERETRACE_ENABLED /* 0x4 */
125033            if( sqlite3WhereTrace&0x4 ){
125034              sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d order=%c\n",
125035                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
125036                  isOrdered>=0 ? isOrdered+'0' : '?');
125037            }
125038#endif
125039            continue;
125040          }
125041          /* If we reach this points it means that the new candidate path
125042          ** needs to be added to the set of best-so-far paths. */
125043          if( nTo<mxChoice ){
125044            /* Increase the size of the aTo set by one */
125045            jj = nTo++;
125046          }else{
125047            /* New path replaces the prior worst to keep count below mxChoice */
125048            jj = mxI;
125049          }
125050          pTo = &aTo[jj];
125051#ifdef WHERETRACE_ENABLED /* 0x4 */
125052          if( sqlite3WhereTrace&0x4 ){
125053            sqlite3DebugPrintf("New    %s cost=%-3d,%3d order=%c\n",
125054                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
125055                isOrdered>=0 ? isOrdered+'0' : '?');
125056          }
125057#endif
125058        }else{
125059          /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
125060          ** same set of loops and has the sam isOrdered setting as the
125061          ** candidate path.  Check to see if the candidate should replace
125062          ** pTo or if the candidate should be skipped */
125063          if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
125064#ifdef WHERETRACE_ENABLED /* 0x4 */
125065            if( sqlite3WhereTrace&0x4 ){
125066              sqlite3DebugPrintf(
125067                  "Skip   %s cost=%-3d,%3d order=%c",
125068                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
125069                  isOrdered>=0 ? isOrdered+'0' : '?');
125070              sqlite3DebugPrintf("   vs %s cost=%-3d,%d order=%c\n",
125071                  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
125072                  pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
125073            }
125074#endif
125075            /* Discard the candidate path from further consideration */
125076            testcase( pTo->rCost==rCost );
125077            continue;
125078          }
125079          testcase( pTo->rCost==rCost+1 );
125080          /* Control reaches here if the candidate path is better than the
125081          ** pTo path.  Replace pTo with the candidate. */
125082#ifdef WHERETRACE_ENABLED /* 0x4 */
125083          if( sqlite3WhereTrace&0x4 ){
125084            sqlite3DebugPrintf(
125085                "Update %s cost=%-3d,%3d order=%c",
125086                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
125087                isOrdered>=0 ? isOrdered+'0' : '?');
125088            sqlite3DebugPrintf("  was %s cost=%-3d,%3d order=%c\n",
125089                wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
125090                pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
125091          }
125092#endif
125093        }
125094        /* pWLoop is a winner.  Add it to the set of best so far */
125095        pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
125096        pTo->revLoop = revMask;
125097        pTo->nRow = nOut;
125098        pTo->rCost = rCost;
125099        pTo->rUnsorted = rUnsorted;
125100        pTo->isOrdered = isOrdered;
125101        memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
125102        pTo->aLoop[iLoop] = pWLoop;
125103        if( nTo>=mxChoice ){
125104          mxI = 0;
125105          mxCost = aTo[0].rCost;
125106          mxUnsorted = aTo[0].nRow;
125107          for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
125108            if( pTo->rCost>mxCost
125109             || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
125110            ){
125111              mxCost = pTo->rCost;
125112              mxUnsorted = pTo->rUnsorted;
125113              mxI = jj;
125114            }
125115          }
125116        }
125117      }
125118    }
125119
125120#ifdef WHERETRACE_ENABLED  /* >=2 */
125121    if( sqlite3WhereTrace & 0x02 ){
125122      sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
125123      for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
125124        sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
125125           wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
125126           pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
125127        if( pTo->isOrdered>0 ){
125128          sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
125129        }else{
125130          sqlite3DebugPrintf("\n");
125131        }
125132      }
125133    }
125134#endif
125135
125136    /* Swap the roles of aFrom and aTo for the next generation */
125137    pFrom = aTo;
125138    aTo = aFrom;
125139    aFrom = pFrom;
125140    nFrom = nTo;
125141  }
125142
125143  if( nFrom==0 ){
125144    sqlite3ErrorMsg(pParse, "no query solution");
125145    sqlite3DbFree(db, pSpace);
125146    return SQLITE_ERROR;
125147  }
125148
125149  /* Find the lowest cost path.  pFrom will be left pointing to that path */
125150  pFrom = aFrom;
125151  for(ii=1; ii<nFrom; ii++){
125152    if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
125153  }
125154  assert( pWInfo->nLevel==nLoop );
125155  /* Load the lowest cost path into pWInfo */
125156  for(iLoop=0; iLoop<nLoop; iLoop++){
125157    WhereLevel *pLevel = pWInfo->a + iLoop;
125158    pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
125159    pLevel->iFrom = pWLoop->iTab;
125160    pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
125161  }
125162  if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
125163   && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
125164   && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
125165   && nRowEst
125166  ){
125167    Bitmask notUsed;
125168    int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
125169                 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
125170    if( rc==pWInfo->pResultSet->nExpr ){
125171      pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
125172    }
125173  }
125174  if( pWInfo->pOrderBy ){
125175    if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
125176      if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
125177        pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
125178      }
125179    }else{
125180      pWInfo->nOBSat = pFrom->isOrdered;
125181      if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
125182      pWInfo->revMask = pFrom->revLoop;
125183    }
125184    if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
125185        && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
125186    ){
125187      Bitmask revMask = 0;
125188      int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
125189          pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
125190      );
125191      assert( pWInfo->sorted==0 );
125192      if( nOrder==pWInfo->pOrderBy->nExpr ){
125193        pWInfo->sorted = 1;
125194        pWInfo->revMask = revMask;
125195      }
125196    }
125197  }
125198
125199
125200  pWInfo->nRowOut = pFrom->nRow;
125201
125202  /* Free temporary memory and return success */
125203  sqlite3DbFree(db, pSpace);
125204  return SQLITE_OK;
125205}
125206
125207/*
125208** Most queries use only a single table (they are not joins) and have
125209** simple == constraints against indexed fields.  This routine attempts
125210** to plan those simple cases using much less ceremony than the
125211** general-purpose query planner, and thereby yield faster sqlite3_prepare()
125212** times for the common case.
125213**
125214** Return non-zero on success, if this query can be handled by this
125215** no-frills query planner.  Return zero if this query needs the
125216** general-purpose query planner.
125217*/
125218static int whereShortCut(WhereLoopBuilder *pBuilder){
125219  WhereInfo *pWInfo;
125220  struct SrcList_item *pItem;
125221  WhereClause *pWC;
125222  WhereTerm *pTerm;
125223  WhereLoop *pLoop;
125224  int iCur;
125225  int j;
125226  Table *pTab;
125227  Index *pIdx;
125228
125229  pWInfo = pBuilder->pWInfo;
125230  if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
125231  assert( pWInfo->pTabList->nSrc>=1 );
125232  pItem = pWInfo->pTabList->a;
125233  pTab = pItem->pTab;
125234  if( IsVirtual(pTab) ) return 0;
125235  if( pItem->fg.isIndexedBy ) return 0;
125236  iCur = pItem->iCursor;
125237  pWC = &pWInfo->sWC;
125238  pLoop = pBuilder->pNew;
125239  pLoop->wsFlags = 0;
125240  pLoop->nSkip = 0;
125241  pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
125242  if( pTerm ){
125243    testcase( pTerm->eOperator & WO_IS );
125244    pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
125245    pLoop->aLTerm[0] = pTerm;
125246    pLoop->nLTerm = 1;
125247    pLoop->u.btree.nEq = 1;
125248    /* TUNING: Cost of a rowid lookup is 10 */
125249    pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
125250  }else{
125251    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
125252      int opMask;
125253      assert( pLoop->aLTermSpace==pLoop->aLTerm );
125254      if( !IsUniqueIndex(pIdx)
125255       || pIdx->pPartIdxWhere!=0
125256       || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
125257      ) continue;
125258      opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
125259      for(j=0; j<pIdx->nKeyCol; j++){
125260        pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
125261        if( pTerm==0 ) break;
125262        testcase( pTerm->eOperator & WO_IS );
125263        pLoop->aLTerm[j] = pTerm;
125264      }
125265      if( j!=pIdx->nKeyCol ) continue;
125266      pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
125267      if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
125268        pLoop->wsFlags |= WHERE_IDX_ONLY;
125269      }
125270      pLoop->nLTerm = j;
125271      pLoop->u.btree.nEq = j;
125272      pLoop->u.btree.pIndex = pIdx;
125273      /* TUNING: Cost of a unique index lookup is 15 */
125274      pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
125275      break;
125276    }
125277  }
125278  if( pLoop->wsFlags ){
125279    pLoop->nOut = (LogEst)1;
125280    pWInfo->a[0].pWLoop = pLoop;
125281    pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
125282    pWInfo->a[0].iTabCur = iCur;
125283    pWInfo->nRowOut = 1;
125284    if( pWInfo->pOrderBy ) pWInfo->nOBSat =  pWInfo->pOrderBy->nExpr;
125285    if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
125286      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
125287    }
125288#ifdef SQLITE_DEBUG
125289    pLoop->cId = '0';
125290#endif
125291    return 1;
125292  }
125293  return 0;
125294}
125295
125296/*
125297** Generate the beginning of the loop used for WHERE clause processing.
125298** The return value is a pointer to an opaque structure that contains
125299** information needed to terminate the loop.  Later, the calling routine
125300** should invoke sqlite3WhereEnd() with the return value of this function
125301** in order to complete the WHERE clause processing.
125302**
125303** If an error occurs, this routine returns NULL.
125304**
125305** The basic idea is to do a nested loop, one loop for each table in
125306** the FROM clause of a select.  (INSERT and UPDATE statements are the
125307** same as a SELECT with only a single table in the FROM clause.)  For
125308** example, if the SQL is this:
125309**
125310**       SELECT * FROM t1, t2, t3 WHERE ...;
125311**
125312** Then the code generated is conceptually like the following:
125313**
125314**      foreach row1 in t1 do       \    Code generated
125315**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
125316**          foreach row3 in t3 do   /
125317**            ...
125318**          end                     \    Code generated
125319**        end                        |-- by sqlite3WhereEnd()
125320**      end                         /
125321**
125322** Note that the loops might not be nested in the order in which they
125323** appear in the FROM clause if a different order is better able to make
125324** use of indices.  Note also that when the IN operator appears in
125325** the WHERE clause, it might result in additional nested loops for
125326** scanning through all values on the right-hand side of the IN.
125327**
125328** There are Btree cursors associated with each table.  t1 uses cursor
125329** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
125330** And so forth.  This routine generates code to open those VDBE cursors
125331** and sqlite3WhereEnd() generates the code to close them.
125332**
125333** The code that sqlite3WhereBegin() generates leaves the cursors named
125334** in pTabList pointing at their appropriate entries.  The [...] code
125335** can use OP_Column and OP_Rowid opcodes on these cursors to extract
125336** data from the various tables of the loop.
125337**
125338** If the WHERE clause is empty, the foreach loops must each scan their
125339** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
125340** the tables have indices and there are terms in the WHERE clause that
125341** refer to those indices, a complete table scan can be avoided and the
125342** code will run much faster.  Most of the work of this routine is checking
125343** to see if there are indices that can be used to speed up the loop.
125344**
125345** Terms of the WHERE clause are also used to limit which rows actually
125346** make it to the "..." in the middle of the loop.  After each "foreach",
125347** terms of the WHERE clause that use only terms in that loop and outer
125348** loops are evaluated and if false a jump is made around all subsequent
125349** inner loops (or around the "..." if the test occurs within the inner-
125350** most loop)
125351**
125352** OUTER JOINS
125353**
125354** An outer join of tables t1 and t2 is conceptally coded as follows:
125355**
125356**    foreach row1 in t1 do
125357**      flag = 0
125358**      foreach row2 in t2 do
125359**        start:
125360**          ...
125361**          flag = 1
125362**      end
125363**      if flag==0 then
125364**        move the row2 cursor to a null row
125365**        goto start
125366**      fi
125367**    end
125368**
125369** ORDER BY CLAUSE PROCESSING
125370**
125371** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
125372** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
125373** if there is one.  If there is no ORDER BY clause or if this routine
125374** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
125375**
125376** The iIdxCur parameter is the cursor number of an index.  If
125377** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
125378** to use for OR clause processing.  The WHERE clause should use this
125379** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
125380** the first cursor in an array of cursors for all indices.  iIdxCur should
125381** be used to compute the appropriate cursor depending on which index is
125382** used.
125383*/
125384SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
125385  Parse *pParse,        /* The parser context */
125386  SrcList *pTabList,    /* FROM clause: A list of all tables to be scanned */
125387  Expr *pWhere,         /* The WHERE clause */
125388  ExprList *pOrderBy,   /* An ORDER BY (or GROUP BY) clause, or NULL */
125389  ExprList *pResultSet, /* Result set of the query */
125390  u16 wctrlFlags,       /* One of the WHERE_* flags defined in sqliteInt.h */
125391  int iIdxCur           /* If WHERE_ONETABLE_ONLY is set, index cursor number */
125392){
125393  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
125394  int nTabList;              /* Number of elements in pTabList */
125395  WhereInfo *pWInfo;         /* Will become the return value of this function */
125396  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
125397  Bitmask notReady;          /* Cursors that are not yet positioned */
125398  WhereLoopBuilder sWLB;     /* The WhereLoop builder */
125399  WhereMaskSet *pMaskSet;    /* The expression mask set */
125400  WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
125401  WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */
125402  int ii;                    /* Loop counter */
125403  sqlite3 *db;               /* Database connection */
125404  int rc;                    /* Return code */
125405
125406  assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
125407        (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
125408     && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
125409  ));
125410
125411  /* Variable initialization */
125412  db = pParse->db;
125413  memset(&sWLB, 0, sizeof(sWLB));
125414
125415  /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
125416  testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
125417  if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
125418  sWLB.pOrderBy = pOrderBy;
125419
125420  /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
125421  ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
125422  if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
125423    wctrlFlags &= ~WHERE_WANT_DISTINCT;
125424  }
125425
125426  /* The number of tables in the FROM clause is limited by the number of
125427  ** bits in a Bitmask
125428  */
125429  testcase( pTabList->nSrc==BMS );
125430  if( pTabList->nSrc>BMS ){
125431    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
125432    return 0;
125433  }
125434
125435  /* This function normally generates a nested loop for all tables in
125436  ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
125437  ** only generate code for the first table in pTabList and assume that
125438  ** any cursors associated with subsequent tables are uninitialized.
125439  */
125440  nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
125441
125442  /* Allocate and initialize the WhereInfo structure that will become the
125443  ** return value. A single allocation is used to store the WhereInfo
125444  ** struct, the contents of WhereInfo.a[], the WhereClause structure
125445  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
125446  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
125447  ** some architectures. Hence the ROUND8() below.
125448  */
125449  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
125450  pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
125451  if( db->mallocFailed ){
125452    sqlite3DbFree(db, pWInfo);
125453    pWInfo = 0;
125454    goto whereBeginError;
125455  }
125456  pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
125457  pWInfo->nLevel = nTabList;
125458  pWInfo->pParse = pParse;
125459  pWInfo->pTabList = pTabList;
125460  pWInfo->pOrderBy = pOrderBy;
125461  pWInfo->pResultSet = pResultSet;
125462  pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
125463  pWInfo->wctrlFlags = wctrlFlags;
125464  pWInfo->savedNQueryLoop = pParse->nQueryLoop;
125465  assert( pWInfo->eOnePass==ONEPASS_OFF );  /* ONEPASS defaults to OFF */
125466  pMaskSet = &pWInfo->sMaskSet;
125467  sWLB.pWInfo = pWInfo;
125468  sWLB.pWC = &pWInfo->sWC;
125469  sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
125470  assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
125471  whereLoopInit(sWLB.pNew);
125472#ifdef SQLITE_DEBUG
125473  sWLB.pNew->cId = '*';
125474#endif
125475
125476  /* Split the WHERE clause into separate subexpressions where each
125477  ** subexpression is separated by an AND operator.
125478  */
125479  initMaskSet(pMaskSet);
125480  sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
125481  sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
125482
125483  /* Special case: a WHERE clause that is constant.  Evaluate the
125484  ** expression and either jump over all of the code or fall thru.
125485  */
125486  for(ii=0; ii<sWLB.pWC->nTerm; ii++){
125487    if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
125488      sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
125489                         SQLITE_JUMPIFNULL);
125490      sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
125491    }
125492  }
125493
125494  /* Special case: No FROM clause
125495  */
125496  if( nTabList==0 ){
125497    if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
125498    if( wctrlFlags & WHERE_WANT_DISTINCT ){
125499      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
125500    }
125501  }
125502
125503  /* Assign a bit from the bitmask to every term in the FROM clause.
125504  **
125505  ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
125506  **
125507  ** The rule of the previous sentence ensures thta if X is the bitmask for
125508  ** a table T, then X-1 is the bitmask for all other tables to the left of T.
125509  ** Knowing the bitmask for all tables to the left of a left join is
125510  ** important.  Ticket #3015.
125511  **
125512  ** Note that bitmasks are created for all pTabList->nSrc tables in
125513  ** pTabList, not just the first nTabList tables.  nTabList is normally
125514  ** equal to pTabList->nSrc but might be shortened to 1 if the
125515  ** WHERE_ONETABLE_ONLY flag is set.
125516  */
125517  for(ii=0; ii<pTabList->nSrc; ii++){
125518    createMask(pMaskSet, pTabList->a[ii].iCursor);
125519    sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
125520  }
125521#ifdef SQLITE_DEBUG
125522  for(ii=0; ii<pTabList->nSrc; ii++){
125523    Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
125524    assert( m==MASKBIT(ii) );
125525  }
125526#endif
125527
125528  /* Analyze all of the subexpressions. */
125529  sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
125530  if( db->mallocFailed ) goto whereBeginError;
125531
125532  if( wctrlFlags & WHERE_WANT_DISTINCT ){
125533    if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
125534      /* The DISTINCT marking is pointless.  Ignore it. */
125535      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
125536    }else if( pOrderBy==0 ){
125537      /* Try to ORDER BY the result set to make distinct processing easier */
125538      pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
125539      pWInfo->pOrderBy = pResultSet;
125540    }
125541  }
125542
125543  /* Construct the WhereLoop objects */
125544  WHERETRACE(0xffff,("*** Optimizer Start *** (wctrlFlags: 0x%x)\n",
125545             wctrlFlags));
125546#if defined(WHERETRACE_ENABLED)
125547  if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
125548    int i;
125549    for(i=0; i<sWLB.pWC->nTerm; i++){
125550      whereTermPrint(&sWLB.pWC->a[i], i);
125551    }
125552  }
125553#endif
125554
125555  if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
125556    rc = whereLoopAddAll(&sWLB);
125557    if( rc ) goto whereBeginError;
125558
125559#ifdef WHERETRACE_ENABLED
125560    if( sqlite3WhereTrace ){    /* Display all of the WhereLoop objects */
125561      WhereLoop *p;
125562      int i;
125563      static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
125564                                             "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
125565      for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
125566        p->cId = zLabel[i%sizeof(zLabel)];
125567        whereLoopPrint(p, sWLB.pWC);
125568      }
125569    }
125570#endif
125571
125572    wherePathSolver(pWInfo, 0);
125573    if( db->mallocFailed ) goto whereBeginError;
125574    if( pWInfo->pOrderBy ){
125575       wherePathSolver(pWInfo, pWInfo->nRowOut+1);
125576       if( db->mallocFailed ) goto whereBeginError;
125577    }
125578  }
125579  if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
125580     pWInfo->revMask = (Bitmask)(-1);
125581  }
125582  if( pParse->nErr || NEVER(db->mallocFailed) ){
125583    goto whereBeginError;
125584  }
125585#ifdef WHERETRACE_ENABLED
125586  if( sqlite3WhereTrace ){
125587    sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
125588    if( pWInfo->nOBSat>0 ){
125589      sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
125590    }
125591    switch( pWInfo->eDistinct ){
125592      case WHERE_DISTINCT_UNIQUE: {
125593        sqlite3DebugPrintf("  DISTINCT=unique");
125594        break;
125595      }
125596      case WHERE_DISTINCT_ORDERED: {
125597        sqlite3DebugPrintf("  DISTINCT=ordered");
125598        break;
125599      }
125600      case WHERE_DISTINCT_UNORDERED: {
125601        sqlite3DebugPrintf("  DISTINCT=unordered");
125602        break;
125603      }
125604    }
125605    sqlite3DebugPrintf("\n");
125606    for(ii=0; ii<pWInfo->nLevel; ii++){
125607      whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
125608    }
125609  }
125610#endif
125611  /* Attempt to omit tables from the join that do not effect the result */
125612  if( pWInfo->nLevel>=2
125613   && pResultSet!=0
125614   && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
125615  ){
125616    Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
125617    if( sWLB.pOrderBy ){
125618      tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
125619    }
125620    while( pWInfo->nLevel>=2 ){
125621      WhereTerm *pTerm, *pEnd;
125622      pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
125623      if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break;
125624      if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
125625       && (pLoop->wsFlags & WHERE_ONEROW)==0
125626      ){
125627        break;
125628      }
125629      if( (tabUsed & pLoop->maskSelf)!=0 ) break;
125630      pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
125631      for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
125632        if( (pTerm->prereqAll & pLoop->maskSelf)!=0
125633         && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
125634        ){
125635          break;
125636        }
125637      }
125638      if( pTerm<pEnd ) break;
125639      WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
125640      pWInfo->nLevel--;
125641      nTabList--;
125642    }
125643  }
125644  WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
125645  pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
125646
125647  /* If the caller is an UPDATE or DELETE statement that is requesting
125648  ** to use a one-pass algorithm, determine if this is appropriate.
125649  ** The one-pass algorithm only works if the WHERE clause constrains
125650  ** the statement to update or delete a single row.
125651  */
125652  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
125653  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
125654    int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
125655    int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
125656    if( bOnerow || ( (wctrlFlags & WHERE_ONEPASS_MULTIROW)
125657       && 0==(wsFlags & WHERE_VIRTUALTABLE)
125658    )){
125659      pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
125660      if( HasRowid(pTabList->a[0].pTab) ){
125661        pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
125662      }
125663    }
125664  }
125665
125666  /* Open all tables in the pTabList and any indices selected for
125667  ** searching those tables.
125668  */
125669  for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
125670    Table *pTab;     /* Table to open */
125671    int iDb;         /* Index of database containing table/index */
125672    struct SrcList_item *pTabItem;
125673
125674    pTabItem = &pTabList->a[pLevel->iFrom];
125675    pTab = pTabItem->pTab;
125676    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
125677    pLoop = pLevel->pWLoop;
125678    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
125679      /* Do nothing */
125680    }else
125681#ifndef SQLITE_OMIT_VIRTUALTABLE
125682    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
125683      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
125684      int iCur = pTabItem->iCursor;
125685      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
125686    }else if( IsVirtual(pTab) ){
125687      /* noop */
125688    }else
125689#endif
125690    if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
125691         && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
125692      int op = OP_OpenRead;
125693      if( pWInfo->eOnePass!=ONEPASS_OFF ){
125694        op = OP_OpenWrite;
125695        pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
125696      };
125697      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
125698      assert( pTabItem->iCursor==pLevel->iTabCur );
125699      testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
125700      testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
125701      if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
125702        Bitmask b = pTabItem->colUsed;
125703        int n = 0;
125704        for(; b; b=b>>1, n++){}
125705        sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
125706                            SQLITE_INT_TO_PTR(n), P4_INT32);
125707        assert( n<=pTab->nCol );
125708      }
125709#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
125710      sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
125711                            (const u8*)&pTabItem->colUsed, P4_INT64);
125712#endif
125713    }else{
125714      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
125715    }
125716    if( pLoop->wsFlags & WHERE_INDEXED ){
125717      Index *pIx = pLoop->u.btree.pIndex;
125718      int iIndexCur;
125719      int op = OP_OpenRead;
125720      /* iIdxCur is always set if to a positive value if ONEPASS is possible */
125721      assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
125722      if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
125723       && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
125724      ){
125725        /* This is one term of an OR-optimization using the PRIMARY KEY of a
125726        ** WITHOUT ROWID table.  No need for a separate index */
125727        iIndexCur = pLevel->iTabCur;
125728        op = 0;
125729      }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
125730        Index *pJ = pTabItem->pTab->pIndex;
125731        iIndexCur = iIdxCur;
125732        assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
125733        while( ALWAYS(pJ) && pJ!=pIx ){
125734          iIndexCur++;
125735          pJ = pJ->pNext;
125736        }
125737        op = OP_OpenWrite;
125738        pWInfo->aiCurOnePass[1] = iIndexCur;
125739      }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
125740        iIndexCur = iIdxCur;
125741        if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
125742      }else{
125743        iIndexCur = pParse->nTab++;
125744      }
125745      pLevel->iIdxCur = iIndexCur;
125746      assert( pIx->pSchema==pTab->pSchema );
125747      assert( iIndexCur>=0 );
125748      if( op ){
125749        sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
125750        sqlite3VdbeSetP4KeyInfo(pParse, pIx);
125751        if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
125752         && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
125753         && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
125754        ){
125755          sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
125756        }
125757        VdbeComment((v, "%s", pIx->zName));
125758#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
125759        {
125760          u64 colUsed = 0;
125761          int ii, jj;
125762          for(ii=0; ii<pIx->nColumn; ii++){
125763            jj = pIx->aiColumn[ii];
125764            if( jj<0 ) continue;
125765            if( jj>63 ) jj = 63;
125766            if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
125767            colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
125768          }
125769          sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
125770                                (u8*)&colUsed, P4_INT64);
125771        }
125772#endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
125773      }
125774    }
125775    if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
125776  }
125777  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
125778  if( db->mallocFailed ) goto whereBeginError;
125779
125780  /* Generate the code to do the search.  Each iteration of the for
125781  ** loop below generates code for a single nested loop of the VM
125782  ** program.
125783  */
125784  notReady = ~(Bitmask)0;
125785  for(ii=0; ii<nTabList; ii++){
125786    int addrExplain;
125787    int wsFlags;
125788    pLevel = &pWInfo->a[ii];
125789    wsFlags = pLevel->pWLoop->wsFlags;
125790#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
125791    if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
125792      constructAutomaticIndex(pParse, &pWInfo->sWC,
125793                &pTabList->a[pLevel->iFrom], notReady, pLevel);
125794      if( db->mallocFailed ) goto whereBeginError;
125795    }
125796#endif
125797    addrExplain = sqlite3WhereExplainOneScan(
125798        pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
125799    );
125800    pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
125801    notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
125802    pWInfo->iContinue = pLevel->addrCont;
125803    if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_ONETABLE_ONLY)==0 ){
125804      sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
125805    }
125806  }
125807
125808  /* Done. */
125809  VdbeModuleComment((v, "Begin WHERE-core"));
125810  return pWInfo;
125811
125812  /* Jump here if malloc fails */
125813whereBeginError:
125814  if( pWInfo ){
125815    pParse->nQueryLoop = pWInfo->savedNQueryLoop;
125816    whereInfoFree(db, pWInfo);
125817  }
125818  return 0;
125819}
125820
125821/*
125822** Generate the end of the WHERE loop.  See comments on
125823** sqlite3WhereBegin() for additional information.
125824*/
125825SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
125826  Parse *pParse = pWInfo->pParse;
125827  Vdbe *v = pParse->pVdbe;
125828  int i;
125829  WhereLevel *pLevel;
125830  WhereLoop *pLoop;
125831  SrcList *pTabList = pWInfo->pTabList;
125832  sqlite3 *db = pParse->db;
125833
125834  /* Generate loop termination code.
125835  */
125836  VdbeModuleComment((v, "End WHERE-core"));
125837  sqlite3ExprCacheClear(pParse);
125838  for(i=pWInfo->nLevel-1; i>=0; i--){
125839    int addr;
125840    pLevel = &pWInfo->a[i];
125841    pLoop = pLevel->pWLoop;
125842    sqlite3VdbeResolveLabel(v, pLevel->addrCont);
125843    if( pLevel->op!=OP_Noop ){
125844      sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
125845      sqlite3VdbeChangeP5(v, pLevel->p5);
125846      VdbeCoverage(v);
125847      VdbeCoverageIf(v, pLevel->op==OP_Next);
125848      VdbeCoverageIf(v, pLevel->op==OP_Prev);
125849      VdbeCoverageIf(v, pLevel->op==OP_VNext);
125850    }
125851    if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
125852      struct InLoop *pIn;
125853      int j;
125854      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
125855      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
125856        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
125857        sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
125858        VdbeCoverage(v);
125859        VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
125860        VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
125861        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
125862      }
125863    }
125864    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
125865    if( pLevel->addrSkip ){
125866      sqlite3VdbeGoto(v, pLevel->addrSkip);
125867      VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
125868      sqlite3VdbeJumpHere(v, pLevel->addrSkip);
125869      sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
125870    }
125871    if( pLevel->addrLikeRep ){
125872      int op;
125873      if( sqlite3VdbeGetOp(v, pLevel->addrLikeRep-1)->p1 ){
125874        op = OP_DecrJumpZero;
125875      }else{
125876        op = OP_JumpZeroIncr;
125877      }
125878      sqlite3VdbeAddOp2(v, op, pLevel->iLikeRepCntr, pLevel->addrLikeRep);
125879      VdbeCoverage(v);
125880    }
125881    if( pLevel->iLeftJoin ){
125882      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
125883      assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
125884           || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
125885      if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
125886        sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
125887      }
125888      if( pLoop->wsFlags & WHERE_INDEXED ){
125889        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
125890      }
125891      if( pLevel->op==OP_Return ){
125892        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
125893      }else{
125894        sqlite3VdbeGoto(v, pLevel->addrFirst);
125895      }
125896      sqlite3VdbeJumpHere(v, addr);
125897    }
125898    VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
125899                     pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
125900  }
125901
125902  /* The "break" point is here, just past the end of the outer loop.
125903  ** Set it.
125904  */
125905  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
125906
125907  assert( pWInfo->nLevel<=pTabList->nSrc );
125908  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
125909    int k, last;
125910    VdbeOp *pOp;
125911    Index *pIdx = 0;
125912    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
125913    Table *pTab = pTabItem->pTab;
125914    assert( pTab!=0 );
125915    pLoop = pLevel->pWLoop;
125916
125917    /* For a co-routine, change all OP_Column references to the table of
125918    ** the co-routine into OP_Copy of result contained in a register.
125919    ** OP_Rowid becomes OP_Null.
125920    */
125921    if( pTabItem->fg.viaCoroutine && !db->mallocFailed ){
125922      translateColumnToCopy(v, pLevel->addrBody, pLevel->iTabCur,
125923                            pTabItem->regResult, 0);
125924      continue;
125925    }
125926
125927    /* Close all of the cursors that were opened by sqlite3WhereBegin.
125928    ** Except, do not close cursors that will be reused by the OR optimization
125929    ** (WHERE_OMIT_OPEN_CLOSE).  And do not close the OP_OpenWrite cursors
125930    ** created for the ONEPASS optimization.
125931    */
125932    if( (pTab->tabFlags & TF_Ephemeral)==0
125933     && pTab->pSelect==0
125934     && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
125935    ){
125936      int ws = pLoop->wsFlags;
125937      if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){
125938        sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
125939      }
125940      if( (ws & WHERE_INDEXED)!=0
125941       && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
125942       && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
125943      ){
125944        sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
125945      }
125946    }
125947
125948    /* If this scan uses an index, make VDBE code substitutions to read data
125949    ** from the index instead of from the table where possible.  In some cases
125950    ** this optimization prevents the table from ever being read, which can
125951    ** yield a significant performance boost.
125952    **
125953    ** Calls to the code generator in between sqlite3WhereBegin and
125954    ** sqlite3WhereEnd will have created code that references the table
125955    ** directly.  This loop scans all that code looking for opcodes
125956    ** that reference the table and converts them into opcodes that
125957    ** reference the index.
125958    */
125959    if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
125960      pIdx = pLoop->u.btree.pIndex;
125961    }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
125962      pIdx = pLevel->u.pCovidx;
125963    }
125964    if( pIdx
125965     && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
125966     && !db->mallocFailed
125967    ){
125968      last = sqlite3VdbeCurrentAddr(v);
125969      k = pLevel->addrBody;
125970      pOp = sqlite3VdbeGetOp(v, k);
125971      for(; k<last; k++, pOp++){
125972        if( pOp->p1!=pLevel->iTabCur ) continue;
125973        if( pOp->opcode==OP_Column ){
125974          int x = pOp->p2;
125975          assert( pIdx->pTable==pTab );
125976          if( !HasRowid(pTab) ){
125977            Index *pPk = sqlite3PrimaryKeyIndex(pTab);
125978            x = pPk->aiColumn[x];
125979            assert( x>=0 );
125980          }
125981          x = sqlite3ColumnOfIndex(pIdx, x);
125982          if( x>=0 ){
125983            pOp->p2 = x;
125984            pOp->p1 = pLevel->iIdxCur;
125985          }
125986          assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
125987        }else if( pOp->opcode==OP_Rowid ){
125988          pOp->p1 = pLevel->iIdxCur;
125989          pOp->opcode = OP_IdxRowid;
125990        }
125991      }
125992    }
125993  }
125994
125995  /* Final cleanup
125996  */
125997  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
125998  whereInfoFree(db, pWInfo);
125999  return;
126000}
126001
126002/************** End of where.c ***********************************************/
126003/************** Begin file parse.c *******************************************/
126004/* Driver template for the LEMON parser generator.
126005** The author disclaims copyright to this source code.
126006**
126007** This version of "lempar.c" is modified, slightly, for use by SQLite.
126008** The only modifications are the addition of a couple of NEVER()
126009** macros to disable tests that are needed in the case of a general
126010** LALR(1) grammar but which are always false in the
126011** specific grammar used by SQLite.
126012*/
126013/* First off, code is included that follows the "include" declaration
126014** in the input grammar file. */
126015/* #include <stdio.h> */
126016
126017/* #include "sqliteInt.h" */
126018
126019/*
126020** Disable all error recovery processing in the parser push-down
126021** automaton.
126022*/
126023#define YYNOERRORRECOVERY 1
126024
126025/*
126026** Make yytestcase() the same as testcase()
126027*/
126028#define yytestcase(X) testcase(X)
126029
126030/*
126031** An instance of this structure holds information about the
126032** LIMIT clause of a SELECT statement.
126033*/
126034struct LimitVal {
126035  Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
126036  Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
126037};
126038
126039/*
126040** An instance of this structure is used to store the LIKE,
126041** GLOB, NOT LIKE, and NOT GLOB operators.
126042*/
126043struct LikeOp {
126044  Token eOperator;  /* "like" or "glob" or "regexp" */
126045  int bNot;         /* True if the NOT keyword is present */
126046};
126047
126048/*
126049** An instance of the following structure describes the event of a
126050** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
126051** TK_DELETE, or TK_INSTEAD.  If the event is of the form
126052**
126053**      UPDATE ON (a,b,c)
126054**
126055** Then the "b" IdList records the list "a,b,c".
126056*/
126057struct TrigEvent { int a; IdList * b; };
126058
126059/*
126060** An instance of this structure holds the ATTACH key and the key type.
126061*/
126062struct AttachKey { int type;  Token key; };
126063
126064
126065  /*
126066  ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
126067  ** all elements in the list.  And make sure list length does not exceed
126068  ** SQLITE_LIMIT_COMPOUND_SELECT.
126069  */
126070  static void parserDoubleLinkSelect(Parse *pParse, Select *p){
126071    if( p->pPrior ){
126072      Select *pNext = 0, *pLoop;
126073      int mxSelect, cnt = 0;
126074      for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
126075        pLoop->pNext = pNext;
126076        pLoop->selFlags |= SF_Compound;
126077      }
126078      if( (p->selFlags & SF_MultiValue)==0 &&
126079        (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
126080        cnt>mxSelect
126081      ){
126082        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
126083      }
126084    }
126085  }
126086
126087  /* This is a utility routine used to set the ExprSpan.zStart and
126088  ** ExprSpan.zEnd values of pOut so that the span covers the complete
126089  ** range of text beginning with pStart and going to the end of pEnd.
126090  */
126091  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
126092    pOut->zStart = pStart->z;
126093    pOut->zEnd = &pEnd->z[pEnd->n];
126094  }
126095
126096  /* Construct a new Expr object from a single identifier.  Use the
126097  ** new Expr to populate pOut.  Set the span of pOut to be the identifier
126098  ** that created the expression.
126099  */
126100  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
126101    pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
126102    pOut->zStart = pValue->z;
126103    pOut->zEnd = &pValue->z[pValue->n];
126104  }
126105
126106  /* This routine constructs a binary expression node out of two ExprSpan
126107  ** objects and uses the result to populate a new ExprSpan object.
126108  */
126109  static void spanBinaryExpr(
126110    ExprSpan *pOut,     /* Write the result here */
126111    Parse *pParse,      /* The parsing context.  Errors accumulate here */
126112    int op,             /* The binary operation */
126113    ExprSpan *pLeft,    /* The left operand */
126114    ExprSpan *pRight    /* The right operand */
126115  ){
126116    pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
126117    pOut->zStart = pLeft->zStart;
126118    pOut->zEnd = pRight->zEnd;
126119  }
126120
126121  /* Construct an expression node for a unary postfix operator
126122  */
126123  static void spanUnaryPostfix(
126124    ExprSpan *pOut,        /* Write the new expression node here */
126125    Parse *pParse,         /* Parsing context to record errors */
126126    int op,                /* The operator */
126127    ExprSpan *pOperand,    /* The operand */
126128    Token *pPostOp         /* The operand token for setting the span */
126129  ){
126130    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
126131    pOut->zStart = pOperand->zStart;
126132    pOut->zEnd = &pPostOp->z[pPostOp->n];
126133  }
126134
126135  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
126136  ** unary TK_ISNULL or TK_NOTNULL expression. */
126137  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
126138    sqlite3 *db = pParse->db;
126139    if( pY && pA && pY->op==TK_NULL ){
126140      pA->op = (u8)op;
126141      sqlite3ExprDelete(db, pA->pRight);
126142      pA->pRight = 0;
126143    }
126144  }
126145
126146  /* Construct an expression node for a unary prefix operator
126147  */
126148  static void spanUnaryPrefix(
126149    ExprSpan *pOut,        /* Write the new expression node here */
126150    Parse *pParse,         /* Parsing context to record errors */
126151    int op,                /* The operator */
126152    ExprSpan *pOperand,    /* The operand */
126153    Token *pPreOp         /* The operand token for setting the span */
126154  ){
126155    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
126156    pOut->zStart = pPreOp->z;
126157    pOut->zEnd = pOperand->zEnd;
126158  }
126159
126160  /* Add a single new term to an ExprList that is used to store a
126161  ** list of identifiers.  Report an error if the ID list contains
126162  ** a COLLATE clause or an ASC or DESC keyword, except ignore the
126163  ** error while parsing a legacy schema.
126164  */
126165  static ExprList *parserAddExprIdListTerm(
126166    Parse *pParse,
126167    ExprList *pPrior,
126168    Token *pIdToken,
126169    int hasCollate,
126170    int sortOrder
126171  ){
126172    ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
126173    if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
126174        && pParse->db->init.busy==0
126175    ){
126176      sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
126177                         pIdToken->n, pIdToken->z);
126178    }
126179    sqlite3ExprListSetName(pParse, p, pIdToken, 1);
126180    return p;
126181  }
126182/* Next is all token values, in a form suitable for use by makeheaders.
126183** This section will be null unless lemon is run with the -m switch.
126184*/
126185/*
126186** These constants (all generated automatically by the parser generator)
126187** specify the various kinds of tokens (terminals) that the parser
126188** understands.
126189**
126190** Each symbol here is a terminal symbol in the grammar.
126191*/
126192/* Make sure the INTERFACE macro is defined.
126193*/
126194#ifndef INTERFACE
126195# define INTERFACE 1
126196#endif
126197/* The next thing included is series of defines which control
126198** various aspects of the generated parser.
126199**    YYCODETYPE         is the data type used for storing terminal
126200**                       and nonterminal numbers.  "unsigned char" is
126201**                       used if there are fewer than 250 terminals
126202**                       and nonterminals.  "int" is used otherwise.
126203**    YYNOCODE           is a number of type YYCODETYPE which corresponds
126204**                       to no legal terminal or nonterminal number.  This
126205**                       number is used to fill in empty slots of the hash
126206**                       table.
126207**    YYFALLBACK         If defined, this indicates that one or more tokens
126208**                       have fall-back values which should be used if the
126209**                       original value of the token will not parse.
126210**    YYACTIONTYPE       is the data type used for storing terminal
126211**                       and nonterminal numbers.  "unsigned char" is
126212**                       used if there are fewer than 250 rules and
126213**                       states combined.  "int" is used otherwise.
126214**    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
126215**                       directly to the parser from the tokenizer.
126216**    YYMINORTYPE        is the data type used for all minor tokens.
126217**                       This is typically a union of many types, one of
126218**                       which is sqlite3ParserTOKENTYPE.  The entry in the union
126219**                       for base tokens is called "yy0".
126220**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
126221**                       zero the stack is dynamically sized using realloc()
126222**    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
126223**    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
126224**    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
126225**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
126226**    YYERRORSYMBOL      is the code number of the error symbol.  If not
126227**                       defined, then do no error processing.
126228**    YYNSTATE           the combined number of states.
126229**    YYNRULE            the number of rules in the grammar
126230**    YY_MAX_SHIFT       Maximum value for shift actions
126231**    YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
126232**    YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
126233**    YY_MIN_REDUCE      Maximum value for reduce actions
126234**    YY_ERROR_ACTION    The yy_action[] code for syntax error
126235**    YY_ACCEPT_ACTION   The yy_action[] code for accept
126236**    YY_NO_ACTION       The yy_action[] code for no-op
126237*/
126238#define YYCODETYPE unsigned char
126239#define YYNOCODE 254
126240#define YYACTIONTYPE unsigned short int
126241#define YYWILDCARD 70
126242#define sqlite3ParserTOKENTYPE Token
126243typedef union {
126244  int yyinit;
126245  sqlite3ParserTOKENTYPE yy0;
126246  Select* yy3;
126247  ExprList* yy14;
126248  With* yy59;
126249  SrcList* yy65;
126250  struct LikeOp yy96;
126251  Expr* yy132;
126252  u8 yy186;
126253  int yy328;
126254  ExprSpan yy346;
126255  struct TrigEvent yy378;
126256  u16 yy381;
126257  IdList* yy408;
126258  struct {int value; int mask;} yy429;
126259  TriggerStep* yy473;
126260  struct LimitVal yy476;
126261} YYMINORTYPE;
126262#ifndef YYSTACKDEPTH
126263#define YYSTACKDEPTH 100
126264#endif
126265#define sqlite3ParserARG_SDECL Parse *pParse;
126266#define sqlite3ParserARG_PDECL ,Parse *pParse
126267#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
126268#define sqlite3ParserARG_STORE yypParser->pParse = pParse
126269#define YYFALLBACK 1
126270#define YYNSTATE             436
126271#define YYNRULE              328
126272#define YY_MAX_SHIFT         435
126273#define YY_MIN_SHIFTREDUCE   649
126274#define YY_MAX_SHIFTREDUCE   976
126275#define YY_MIN_REDUCE        977
126276#define YY_MAX_REDUCE        1304
126277#define YY_ERROR_ACTION      1305
126278#define YY_ACCEPT_ACTION     1306
126279#define YY_NO_ACTION         1307
126280
126281/* The yyzerominor constant is used to initialize instances of
126282** YYMINORTYPE objects to zero. */
126283static const YYMINORTYPE yyzerominor = { 0 };
126284
126285/* Define the yytestcase() macro to be a no-op if is not already defined
126286** otherwise.
126287**
126288** Applications can choose to define yytestcase() in the %include section
126289** to a macro that can assist in verifying code coverage.  For production
126290** code the yytestcase() macro should be turned off.  But it is useful
126291** for testing.
126292*/
126293#ifndef yytestcase
126294# define yytestcase(X)
126295#endif
126296
126297
126298/* Next are the tables used to determine what action to take based on the
126299** current state and lookahead token.  These tables are used to implement
126300** functions that take a state number and lookahead value and return an
126301** action integer.
126302**
126303** Suppose the action integer is N.  Then the action is determined as
126304** follows
126305**
126306**   0 <= N <= YY_MAX_SHIFT             Shift N.  That is, push the lookahead
126307**                                      token onto the stack and goto state N.
126308**
126309**   N between YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
126310**     and YY_MAX_SHIFTREDUCE           reduce by rule N-YY_MIN_SHIFTREDUCE.
126311**
126312**   N between YY_MIN_REDUCE            Reduce by rule N-YY_MIN_REDUCE
126313**     and YY_MAX_REDUCE
126314
126315**   N == YY_ERROR_ACTION               A syntax error has occurred.
126316**
126317**   N == YY_ACCEPT_ACTION              The parser accepts its input.
126318**
126319**   N == YY_NO_ACTION                  No such action.  Denotes unused
126320**                                      slots in the yy_action[] table.
126321**
126322** The action table is constructed as a single large table named yy_action[].
126323** Given state S and lookahead X, the action is computed as
126324**
126325**      yy_action[ yy_shift_ofst[S] + X ]
126326**
126327** If the index value yy_shift_ofst[S]+X is out of range or if the value
126328** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
126329** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
126330** and that yy_default[S] should be used instead.
126331**
126332** The formula above is for computing the action when the lookahead is
126333** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
126334** a reduce action) then the yy_reduce_ofst[] array is used in place of
126335** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
126336** YY_SHIFT_USE_DFLT.
126337**
126338** The following are the tables generated in this section:
126339**
126340**  yy_action[]        A single table containing all actions.
126341**  yy_lookahead[]     A table containing the lookahead for each entry in
126342**                     yy_action.  Used to detect hash collisions.
126343**  yy_shift_ofst[]    For each state, the offset into yy_action for
126344**                     shifting terminals.
126345**  yy_reduce_ofst[]   For each state, the offset into yy_action for
126346**                     shifting non-terminals after a reduce.
126347**  yy_default[]       Default action for each state.
126348*/
126349#define YY_ACTTAB_COUNT (1501)
126350static const YYACTIONTYPE yy_action[] = {
126351 /*     0 */   311, 1306,  145,  651,    2,  192,  652,  338,  780,   92,
126352 /*    10 */    92,   92,   92,   85,   90,   90,   90,   90,   89,   89,
126353 /*    20 */    88,   88,   88,   87,  335,   88,   88,   88,   87,  335,
126354 /*    30 */   327,  856,  856,   92,   92,   92,   92,  776,   90,   90,
126355 /*    40 */    90,   90,   89,   89,   88,   88,   88,   87,  335,   86,
126356 /*    50 */    83,  166,   93,   94,   84,  868,  871,  860,  860,   91,
126357 /*    60 */    91,   92,   92,   92,   92,  335,   90,   90,   90,   90,
126358 /*    70 */    89,   89,   88,   88,   88,   87,  335,  311,  780,   90,
126359 /*    80 */    90,   90,   90,   89,   89,   88,   88,   88,   87,  335,
126360 /*    90 */   123,  808,  689,  689,  689,  689,  112,  230,  430,  257,
126361 /*   100 */   809,  698,  430,   86,   83,  166,  324,   55,  856,  856,
126362 /*   110 */   201,  158,  276,  387,  271,  386,  188,  689,  689,  828,
126363 /*   120 */   833,   49,  944,  269,  833,   49,  123,   87,  335,   93,
126364 /*   130 */    94,   84,  868,  871,  860,  860,   91,   91,   92,   92,
126365 /*   140 */    92,   92,  342,   90,   90,   90,   90,   89,   89,   88,
126366 /*   150 */    88,   88,   87,  335,  311,  328,  333,  332,  701,  408,
126367 /*   160 */   394,   69,  690,  691,  690,  691,  715,  910,  251,  354,
126368 /*   170 */   250,  698,  704,  430,  908,  430,  909,   89,   89,   88,
126369 /*   180 */    88,   88,   87,  335,  391,  856,  856,  690,  691,  183,
126370 /*   190 */    95,  340,  384,  381,  380,  833,   31,  833,   49,  912,
126371 /*   200 */   912,  333,  332,  379,  123,  311,   93,   94,   84,  868,
126372 /*   210 */   871,  860,  860,   91,   91,   92,   92,   92,   92,  114,
126373 /*   220 */    90,   90,   90,   90,   89,   89,   88,   88,   88,   87,
126374 /*   230 */   335,  430,  408,  399,  435,  657,  856,  856,  346,   57,
126375 /*   240 */   232,  828,  109,   20,  912,  912,  231,  393,  937,  760,
126376 /*   250 */    97,  751,  752,  833,   49,  708,  708,   93,   94,   84,
126377 /*   260 */   868,  871,  860,  860,   91,   91,   92,   92,   92,   92,
126378 /*   270 */   707,   90,   90,   90,   90,   89,   89,   88,   88,   88,
126379 /*   280 */    87,  335,  311,  114,   22,  706,  688,   58,  408,  390,
126380 /*   290 */   251,  349,  240,  749,  752,  689,  689,  847,  685,  115,
126381 /*   300 */    21,  231,  393,  689,  689,  697,  183,  355,  430,  384,
126382 /*   310 */   381,  380,  192,  856,  856,  780,  123,  160,  159,  223,
126383 /*   320 */   379,  738,   25,  315,  362,  841,  143,  689,  689,  835,
126384 /*   330 */   833,   48,  339,  937,   93,   94,   84,  868,  871,  860,
126385 /*   340 */   860,   91,   91,   92,   92,   92,   92,  914,   90,   90,
126386 /*   350 */    90,   90,   89,   89,   88,   88,   88,   87,  335,  311,
126387 /*   360 */   840,  840,  840,  266,  430,  690,  691,  778,  114, 1300,
126388 /*   370 */  1300,  430,    1,  690,  691,  697,  688,  689,  689,  689,
126389 /*   380 */   689,  689,  689,  287,  298,  780,  833,   10,  686,  115,
126390 /*   390 */   856,  856,  355,  833,   10,  828,  366,  690,  691,  363,
126391 /*   400 */   321,   76,  123,   74,   23,  737,  807,  323,  356,  353,
126392 /*   410 */   847,   93,   94,   84,  868,  871,  860,  860,   91,   91,
126393 /*   420 */    92,   92,   92,   92,  940,   90,   90,   90,   90,   89,
126394 /*   430 */    89,   88,   88,   88,   87,  335,  311,  806,  841,  429,
126395 /*   440 */   713,  941,  835,  430,  251,  354,  250,  690,  691,  690,
126396 /*   450 */   691,  690,  691,   86,   83,  166,   24,  942,  151,  753,
126397 /*   460 */   285,  907,  403,  907,  164,  833,   10,  856,  856,  965,
126398 /*   470 */   306,  754,  679,  840,  840,  840,  795,  216,  794,  222,
126399 /*   480 */   906,  344,  906,  904,   86,   83,  166,  286,   93,   94,
126400 /*   490 */    84,  868,  871,  860,  860,   91,   91,   92,   92,   92,
126401 /*   500 */    92,  430,   90,   90,   90,   90,   89,   89,   88,   88,
126402 /*   510 */    88,   87,  335,  311,  430,  724,  352,  705,  427,  699,
126403 /*   520 */   700,  376,  210,  833,   49,  793,  397,  857,  857,  940,
126404 /*   530 */   213,  762,  727,  334,  699,  700,  833,   10,   86,   83,
126405 /*   540 */   166,  345,  396,  902,  856,  856,  941,  385,  833,    9,
126406 /*   550 */   406,  869,  872,  187,  890,  728,  347,  398,  404,  977,
126407 /*   560 */   652,  338,  942,  954,  413,   93,   94,   84,  868,  871,
126408 /*   570 */   860,  860,   91,   91,   92,   92,   92,   92,  861,   90,
126409 /*   580 */    90,   90,   90,   89,   89,   88,   88,   88,   87,  335,
126410 /*   590 */   311, 1219,  114,  430,  834,  430,    5,  165,  192,  688,
126411 /*   600 */   832,  780,  430,  723,  430,  234,  325,  189,  163,  316,
126412 /*   610 */   356,  955,  115,  235,  269,  833,   35,  833,   36,  747,
126413 /*   620 */   720,  856,  856,  793,  833,   12,  833,   27,  745,  174,
126414 /*   630 */   968, 1290,  968, 1291, 1290,  310, 1291,  693,  317,  245,
126415 /*   640 */   264,  311,   93,   94,   84,  868,  871,  860,  860,   91,
126416 /*   650 */    91,   92,   92,   92,   92,  832,   90,   90,   90,   90,
126417 /*   660 */    89,   89,   88,   88,   88,   87,  335,  430,  320,  213,
126418 /*   670 */   762,  780,  856,  856,  920,  920,  369,  257,  966,  220,
126419 /*   680 */   966,  396,  663,  664,  665,  242,  259,  244,  262,  833,
126420 /*   690 */    37,  650,    2,   93,   94,   84,  868,  871,  860,  860,
126421 /*   700 */    91,   91,   92,   92,   92,   92,  430,   90,   90,   90,
126422 /*   710 */    90,   89,   89,   88,   88,   88,   87,  335,  311,  430,
126423 /*   720 */   239,  430,  917,  368,  430,  238,  916,  793,  833,   38,
126424 /*   730 */   430,  825,  430,   66,  430,  392,  430,  766,  766,  430,
126425 /*   740 */   367,  833,   39,  833,   28,  430,  833,   29,   68,  856,
126426 /*   750 */   856,  900,  833,   40,  833,   41,  833,   42,  833,   11,
126427 /*   760 */    72,  833,   43,  243,  305,  970,  114,  833,   99,  961,
126428 /*   770 */    93,   94,   84,  868,  871,  860,  860,   91,   91,   92,
126429 /*   780 */    92,   92,   92,  430,   90,   90,   90,   90,   89,   89,
126430 /*   790 */    88,   88,   88,   87,  335,  311,  430,  361,  430,  165,
126431 /*   800 */   147,  430,  186,  185,  184,  833,   44,  430,  289,  430,
126432 /*   810 */   246,  430,  971,  430,  212,  163,  430,  357,  833,   45,
126433 /*   820 */   833,   32,  932,  833,   46,  793,  856,  856,  718,  833,
126434 /*   830 */    47,  833,   33,  833,  117,  833,  118,   75,  833,  119,
126435 /*   840 */   288,  305,  967,  214,  935,  322,  311,   93,   94,   84,
126436 /*   850 */   868,  871,  860,  860,   91,   91,   92,   92,   92,   92,
126437 /*   860 */   430,   90,   90,   90,   90,   89,   89,   88,   88,   88,
126438 /*   870 */    87,  335,  430,  832,  426,  317,  288,  856,  856,  114,
126439 /*   880 */   763,  257,  833,   53,  930,  219,  364,  257,  257,  971,
126440 /*   890 */   361,  396,  257,  257,  833,   34,  257,  311,   93,   94,
126441 /*   900 */    84,  868,  871,  860,  860,   91,   91,   92,   92,   92,
126442 /*   910 */    92,  430,   90,   90,   90,   90,   89,   89,   88,   88,
126443 /*   920 */    88,   87,  335,  430,  217,  318,  124,  253,  856,  856,
126444 /*   930 */   218,  943,  257,  833,  100,  898,  759,  774,  361,  755,
126445 /*   940 */   423,  329,  758, 1017,  289,  833,   50,  682,  311,   93,
126446 /*   950 */    82,   84,  868,  871,  860,  860,   91,   91,   92,   92,
126447 /*   960 */    92,   92,  430,   90,   90,   90,   90,   89,   89,   88,
126448 /*   970 */    88,   88,   87,  335,  430,  256,  419,  114,  249,  856,
126449 /*   980 */   856,  331,  114,  400,  833,  101,  359,  187, 1064,  726,
126450 /*   990 */   725,  739,  401,  416,  420,  360,  833,  102,  424,  311,
126451 /*  1000 */   258,   94,   84,  868,  871,  860,  860,   91,   91,   92,
126452 /*  1010 */    92,   92,   92,  430,   90,   90,   90,   90,   89,   89,
126453 /*  1020 */    88,   88,   88,   87,  335,  430,  221,  261,  114,  114,
126454 /*  1030 */   856,  856,  808,  114,  156,  833,   98,  772,  733,  734,
126455 /*  1040 */   275,  809,  771,  316,  263,  265,  960,  833,  116,  307,
126456 /*  1050 */   741,  274,  722,   84,  868,  871,  860,  860,   91,   91,
126457 /*  1060 */    92,   92,   92,   92,  430,   90,   90,   90,   90,   89,
126458 /*  1070 */    89,   88,   88,   88,   87,  335,   80,  425,  830,    3,
126459 /*  1080 */  1214,  191,  430,  721,  336,  336,  833,  113,  252,   80,
126460 /*  1090 */   425,   68,    3,  913,  913,  428,  270,  336,  336,  430,
126461 /*  1100 */   377,  784,  430,  197,  833,  106,  430,  716,  428,  430,
126462 /*  1110 */   267,  430,  897,   68,  414,  430,  769,  409,  430,   71,
126463 /*  1120 */   430,  833,  105,  123,  833,  103,  847,  414,  833,   49,
126464 /*  1130 */   843,  833,  104,  833,   52,  800,  123,  833,   54,  847,
126465 /*  1140 */   833,   51,  833,   26,  831,  802,   77,   78,  191,  389,
126466 /*  1150 */   430,  372,  114,   79,  432,  431,  911,  911,  835,   77,
126467 /*  1160 */    78,  779,  893,  408,  410,  197,   79,  432,  431,  791,
126468 /*  1170 */   226,  835,  833,   30,  772,   80,  425,  716,    3,  771,
126469 /*  1180 */   411,  412,  897,  336,  336,  290,  291,  839,  703,  840,
126470 /*  1190 */   840,  840,  842,   19,  428,  695,  684,  672,  111,  671,
126471 /*  1200 */   843,  673,  840,  840,  840,  842,   19,  207,  661,  278,
126472 /*  1210 */   148,  304,  280,  414,  282,    6,  822,  348,  248,  241,
126473 /*  1220 */   358,  934,  720,   80,  425,  847,    3,  161,  382,  273,
126474 /*  1230 */   284,  336,  336,  415,  296,  958,  895,  894,  157,  674,
126475 /*  1240 */   107,  194,  428,  948,  135,   77,   78,  777,  953,  951,
126476 /*  1250 */    56,  319,   79,  432,  431,  121,   66,  835,   59,  128,
126477 /*  1260 */   146,  414,  350,  130,  351,  819,  131,  132,  133,  375,
126478 /*  1270 */   173,  149,  138,  847,  936,  365,  178,   70,  425,  827,
126479 /*  1280 */     3,  889,   62,  371,  915,  336,  336,  792,  840,  840,
126480 /*  1290 */   840,  842,   19,   77,   78,  208,  428,  144,  179,  373,
126481 /*  1300 */    79,  432,  431,  255,  180,  835,  260,  675,  181,  308,
126482 /*  1310 */   388,  744,  326,  743,  742,  414,  731,  718,  712,  402,
126483 /*  1320 */   309,  711,  788,   65,  277,  272,  789,  847,  730,  710,
126484 /*  1330 */   709,  279,  193,  787,  281,  876,  840,  840,  840,  842,
126485 /*  1340 */    19,  786,  283,   73,  418,  330,  422,   77,   78,  227,
126486 /*  1350 */    96,  407,   67,  405,   79,  432,  431,  292,  228,  835,
126487 /*  1360 */   215,  202,  229,  293,  767,  303,  302,  301,  204,  299,
126488 /*  1370 */   294,  295,  676,    7,  681,  433,  669,  206,  110,  224,
126489 /*  1380 */   203,  205,  434,  667,  666,  658,  120,  168,  656,  237,
126490 /*  1390 */   840,  840,  840,  842,   19,  337,  155,  233,  236,  341,
126491 /*  1400 */   167,  905,  108,  313,  903,  826,  314,  125,  126,  127,
126492 /*  1410 */   129,  170,  247,  756,  172,  928,  134,  136,  171,   60,
126493 /*  1420 */    61,  123,  169,  137,  175,  933,  176,  927,    8,   13,
126494 /*  1430 */   177,  254,  191,  918,  139,  370,  924,  140,  678,  150,
126495 /*  1440 */   374,  274,  182,  378,  141,  122,   63,   14,  383,  729,
126496 /*  1450 */   268,   15,   64,  225,  846,  845,  874,   16,  765,  770,
126497 /*  1460 */     4,  162,  209,  395,  211,  142,  878,  796,  801,  312,
126498 /*  1470 */   190,   71,   68,  875,  873,  939,  199,  938,   17,  195,
126499 /*  1480 */    18,  196,  417,  975,  152,  653,  976,  198,  153,  421,
126500 /*  1490 */   877,  154,  200,  844,  696,   81,  343,  297, 1019, 1018,
126501 /*  1500 */   300,
126502};
126503static const YYCODETYPE yy_lookahead[] = {
126504 /*     0 */    19,  144,  145,  146,  147,   24,    1,    2,   27,   80,
126505 /*    10 */    81,   82,   83,   84,   85,   86,   87,   88,   89,   90,
126506 /*    20 */    91,   92,   93,   94,   95,   91,   92,   93,   94,   95,
126507 /*    30 */    19,   50,   51,   80,   81,   82,   83,  212,   85,   86,
126508 /*    40 */    87,   88,   89,   90,   91,   92,   93,   94,   95,  224,
126509 /*    50 */   225,  226,   71,   72,   73,   74,   75,   76,   77,   78,
126510 /*    60 */    79,   80,   81,   82,   83,   95,   85,   86,   87,   88,
126511 /*    70 */    89,   90,   91,   92,   93,   94,   95,   19,   97,   85,
126512 /*    80 */    86,   87,   88,   89,   90,   91,   92,   93,   94,   95,
126513 /*    90 */    66,   33,   27,   28,   27,   28,   22,  201,  152,  152,
126514 /*   100 */    42,   27,  152,  224,  225,  226,   95,  211,   50,   51,
126515 /*   110 */    99,  100,  101,  102,  103,  104,  105,   27,   28,   59,
126516 /*   120 */   174,  175,  243,  112,  174,  175,   66,   94,   95,   71,
126517 /*   130 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
126518 /*   140 */    82,   83,  195,   85,   86,   87,   88,   89,   90,   91,
126519 /*   150 */    92,   93,   94,   95,   19,  209,   89,   90,  173,  209,
126520 /*   160 */   210,   26,   97,   98,   97,   98,  181,  100,  108,  109,
126521 /*   170 */   110,   97,  174,  152,  107,  152,  109,   89,   90,   91,
126522 /*   180 */    92,   93,   94,   95,  163,   50,   51,   97,   98,   99,
126523 /*   190 */    55,  244,  102,  103,  104,  174,  175,  174,  175,  132,
126524 /*   200 */   133,   89,   90,  113,   66,   19,   71,   72,   73,   74,
126525 /*   210 */    75,   76,   77,   78,   79,   80,   81,   82,   83,  198,
126526 /*   220 */    85,   86,   87,   88,   89,   90,   91,   92,   93,   94,
126527 /*   230 */    95,  152,  209,  210,  148,  149,   50,   51,  100,   53,
126528 /*   240 */   154,   59,  156,   22,  132,  133,  119,  120,  163,  163,
126529 /*   250 */    22,  192,  193,  174,  175,   27,   28,   71,   72,   73,
126530 /*   260 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
126531 /*   270 */   174,   85,   86,   87,   88,   89,   90,   91,   92,   93,
126532 /*   280 */    94,   95,   19,  198,  198,  174,  152,   24,  209,  210,
126533 /*   290 */   108,  109,  110,  192,  193,   27,   28,   69,  164,  165,
126534 /*   300 */    79,  119,  120,   27,   28,   27,   99,  222,  152,  102,
126535 /*   310 */   103,  104,   24,   50,   51,   27,   66,   89,   90,  185,
126536 /*   320 */   113,  187,   22,  157,  239,   97,   58,   27,   28,  101,
126537 /*   330 */   174,  175,  246,  163,   71,   72,   73,   74,   75,   76,
126538 /*   340 */    77,   78,   79,   80,   81,   82,   83,   11,   85,   86,
126539 /*   350 */    87,   88,   89,   90,   91,   92,   93,   94,   95,   19,
126540 /*   360 */   132,  133,  134,   23,  152,   97,   98,   91,  198,  119,
126541 /*   370 */   120,  152,   22,   97,   98,   97,  152,   27,   28,   27,
126542 /*   380 */    28,   27,   28,  227,  160,   97,  174,  175,  164,  165,
126543 /*   390 */    50,   51,  222,  174,  175,   59,  230,   97,   98,  233,
126544 /*   400 */   188,  137,   66,  139,  234,  187,  177,  188,  152,  239,
126545 /*   410 */    69,   71,   72,   73,   74,   75,   76,   77,   78,   79,
126546 /*   420 */    80,   81,   82,   83,   12,   85,   86,   87,   88,   89,
126547 /*   430 */    90,   91,   92,   93,   94,   95,   19,  177,   97,  152,
126548 /*   440 */    23,   29,  101,  152,  108,  109,  110,   97,   98,   97,
126549 /*   450 */    98,   97,   98,  224,  225,  226,   22,   45,   24,   47,
126550 /*   460 */   152,  152,  152,  152,  152,  174,  175,   50,   51,  249,
126551 /*   470 */   250,   59,   21,  132,  133,  134,  124,  221,  124,  188,
126552 /*   480 */   171,  172,  171,  172,  224,  225,  226,  152,   71,   72,
126553 /*   490 */    73,   74,   75,   76,   77,   78,   79,   80,   81,   82,
126554 /*   500 */    83,  152,   85,   86,   87,   88,   89,   90,   91,   92,
126555 /*   510 */    93,   94,   95,   19,  152,  183,   65,   23,  170,  171,
126556 /*   520 */   172,   19,   23,  174,  175,   26,  152,   50,   51,   12,
126557 /*   530 */   196,  197,   37,  170,  171,  172,  174,  175,  224,  225,
126558 /*   540 */   226,  232,  208,  232,   50,   51,   29,   52,  174,  175,
126559 /*   550 */   188,   74,   75,   51,  103,   60,  222,  163,  209,    0,
126560 /*   560 */     1,    2,   45,  152,   47,   71,   72,   73,   74,   75,
126561 /*   570 */    76,   77,   78,   79,   80,   81,   82,   83,  101,   85,
126562 /*   580 */    86,   87,   88,   89,   90,   91,   92,   93,   94,   95,
126563 /*   590 */    19,  140,  198,  152,   23,  152,   22,   98,   24,  152,
126564 /*   600 */   152,   27,  152,  183,  152,  152,  111,  213,  214,  107,
126565 /*   610 */   152,  164,  165,  152,  112,  174,  175,  174,  175,  181,
126566 /*   620 */   182,   50,   51,  124,  174,  175,  174,  175,  190,   26,
126567 /*   630 */    22,   23,   22,   23,   26,  166,   26,  168,  169,   16,
126568 /*   640 */    16,   19,   71,   72,   73,   74,   75,   76,   77,   78,
126569 /*   650 */    79,   80,   81,   82,   83,  152,   85,   86,   87,   88,
126570 /*   660 */    89,   90,   91,   92,   93,   94,   95,  152,  220,  196,
126571 /*   670 */   197,   97,   50,   51,  108,  109,  110,  152,   70,  221,
126572 /*   680 */    70,  208,    7,    8,    9,   62,   62,   64,   64,  174,
126573 /*   690 */   175,  146,  147,   71,   72,   73,   74,   75,   76,   77,
126574 /*   700 */    78,   79,   80,   81,   82,   83,  152,   85,   86,   87,
126575 /*   710 */    88,   89,   90,   91,   92,   93,   94,   95,   19,  152,
126576 /*   720 */   195,  152,   31,  220,  152,  152,   35,   26,  174,  175,
126577 /*   730 */   152,  163,  152,  130,  152,  115,  152,  117,  118,  152,
126578 /*   740 */    49,  174,  175,  174,  175,  152,  174,  175,   26,   50,
126579 /*   750 */    51,  152,  174,  175,  174,  175,  174,  175,  174,  175,
126580 /*   760 */   138,  174,  175,  140,   22,   23,  198,  174,  175,  152,
126581 /*   770 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
126582 /*   780 */    81,   82,   83,  152,   85,   86,   87,   88,   89,   90,
126583 /*   790 */    91,   92,   93,   94,   95,   19,  152,  152,  152,   98,
126584 /*   800 */    24,  152,  108,  109,  110,  174,  175,  152,  152,  152,
126585 /*   810 */   152,  152,   70,  152,  213,  214,  152,  152,  174,  175,
126586 /*   820 */   174,  175,  152,  174,  175,  124,   50,   51,  106,  174,
126587 /*   830 */   175,  174,  175,  174,  175,  174,  175,  138,  174,  175,
126588 /*   840 */   152,   22,   23,   22,  163,  189,   19,   71,   72,   73,
126589 /*   850 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
126590 /*   860 */   152,   85,   86,   87,   88,   89,   90,   91,   92,   93,
126591 /*   870 */    94,   95,  152,  152,  168,  169,  152,   50,   51,  198,
126592 /*   880 */   197,  152,  174,  175,  152,  240,  152,  152,  152,   70,
126593 /*   890 */   152,  208,  152,  152,  174,  175,  152,   19,   71,   72,
126594 /*   900 */    73,   74,   75,   76,   77,   78,   79,   80,   81,   82,
126595 /*   910 */    83,  152,   85,   86,   87,   88,   89,   90,   91,   92,
126596 /*   920 */    93,   94,   95,  152,  195,  247,  248,  152,   50,   51,
126597 /*   930 */   195,  195,  152,  174,  175,  195,  195,   26,  152,  195,
126598 /*   940 */   252,  220,  163,  122,  152,  174,  175,  163,   19,   71,
126599 /*   950 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
126600 /*   960 */    82,   83,  152,   85,   86,   87,   88,   89,   90,   91,
126601 /*   970 */    92,   93,   94,   95,  152,  195,  252,  198,  240,   50,
126602 /*   980 */    51,  189,  198,   19,  174,  175,   19,   51,   23,  100,
126603 /*   990 */   101,   26,   28,  163,  163,   28,  174,  175,  163,   19,
126604 /*  1000 */   152,   72,   73,   74,   75,   76,   77,   78,   79,   80,
126605 /*  1010 */    81,   82,   83,  152,   85,   86,   87,   88,   89,   90,
126606 /*  1020 */    91,   92,   93,   94,   95,  152,  240,  152,  198,  198,
126607 /*  1030 */    50,   51,   33,  198,  123,  174,  175,  116,    7,    8,
126608 /*  1040 */   101,   42,  121,  107,  152,  152,   23,  174,  175,   26,
126609 /*  1050 */   152,  112,  183,   73,   74,   75,   76,   77,   78,   79,
126610 /*  1060 */    80,   81,   82,   83,  152,   85,   86,   87,   88,   89,
126611 /*  1070 */    90,   91,   92,   93,   94,   95,   19,   20,   23,   22,
126612 /*  1080 */    23,   26,  152,  152,   27,   28,  174,  175,   23,   19,
126613 /*  1090 */    20,   26,   22,  132,  133,   38,  152,   27,   28,  152,
126614 /*  1100 */    23,  215,  152,   26,  174,  175,  152,   27,   38,  152,
126615 /*  1110 */    23,  152,   27,   26,   57,  152,   23,  163,  152,   26,
126616 /*  1120 */   152,  174,  175,   66,  174,  175,   69,   57,  174,  175,
126617 /*  1130 */    27,  174,  175,  174,  175,  152,   66,  174,  175,   69,
126618 /*  1140 */   174,  175,  174,  175,  152,   23,   89,   90,   26,   91,
126619 /*  1150 */   152,  236,  198,   96,   97,   98,  132,  133,  101,   89,
126620 /*  1160 */    90,  152,   23,  209,  210,   26,   96,   97,   98,  152,
126621 /*  1170 */   212,  101,  174,  175,  116,   19,   20,   97,   22,  121,
126622 /*  1180 */   152,  193,   97,   27,   28,  152,  152,  152,  152,  132,
126623 /*  1190 */   133,  134,  135,  136,   38,   23,  152,  152,   26,  152,
126624 /*  1200 */    97,  152,  132,  133,  134,  135,  136,  235,  152,  212,
126625 /*  1210 */   199,  150,  212,   57,  212,  200,  203,  216,  241,  216,
126626 /*  1220 */   241,  203,  182,   19,   20,   69,   22,  186,  178,  177,
126627 /*  1230 */   216,   27,   28,  229,  202,   39,  177,  177,  200,  155,
126628 /*  1240 */   245,  122,   38,   41,   22,   89,   90,   91,  159,  159,
126629 /*  1250 */   242,  159,   96,   97,   98,   71,  130,  101,  242,  191,
126630 /*  1260 */   223,   57,   18,  194,  159,  203,  194,  194,  194,   18,
126631 /*  1270 */   158,  223,  191,   69,  203,  159,  158,   19,   20,  191,
126632 /*  1280 */    22,  203,  137,   46,  238,   27,   28,  159,  132,  133,
126633 /*  1290 */   134,  135,  136,   89,   90,  159,   38,   22,  158,  179,
126634 /*  1300 */    96,   97,   98,  237,  158,  101,  159,  159,  158,  179,
126635 /*  1310 */   107,  176,   48,  176,  176,   57,  184,  106,  176,  125,
126636 /*  1320 */   179,  178,  218,  107,  217,  176,  218,   69,  184,  176,
126637 /*  1330 */   176,  217,  159,  218,  217,  159,  132,  133,  134,  135,
126638 /*  1340 */   136,  218,  217,  137,  179,   95,  179,   89,   90,  228,
126639 /*  1350 */   129,  126,  128,  127,   96,   97,   98,  206,  231,  101,
126640 /*  1360 */     5,   25,  231,  205,  207,   10,   11,   12,   13,   14,
126641 /*  1370 */   204,  203,   17,   26,  162,  161,   13,    6,  180,  180,
126642 /*  1380 */   153,  153,  151,  151,  151,  151,  167,   32,    4,   34,
126643 /*  1390 */   132,  133,  134,  135,  136,    3,   22,  142,   43,   68,
126644 /*  1400 */    15,   23,   16,  251,   23,  120,  251,  248,  131,  111,
126645 /*  1410 */   123,   56,   16,   20,  125,    1,  123,  131,   63,   79,
126646 /*  1420 */    79,   66,   67,  111,   36,   28,  122,    1,    5,   22,
126647 /*  1430 */   107,  140,   26,   54,   54,   44,   61,  107,   20,   24,
126648 /*  1440 */    19,  112,  105,   53,   22,   40,   22,   22,   53,   30,
126649 /*  1450 */    23,   22,   22,   53,   23,   23,   23,   22,  116,   23,
126650 /*  1460 */    22,  122,   23,   26,   23,   22,   11,  124,   28,  114,
126651 /*  1470 */    36,   26,   26,   23,   23,   23,  122,   23,   36,   26,
126652 /*  1480 */    36,   22,   24,   23,   22,    1,   23,   26,   22,   24,
126653 /*  1490 */    23,   22,  122,   23,   23,   22,  141,   23,  122,  122,
126654 /*  1500 */    15,
126655};
126656#define YY_SHIFT_USE_DFLT (-72)
126657#define YY_SHIFT_COUNT (435)
126658#define YY_SHIFT_MIN   (-71)
126659#define YY_SHIFT_MAX   (1485)
126660static const short yy_shift_ofst[] = {
126661 /*     0 */     5, 1057, 1355, 1070, 1204, 1204, 1204,   90,   60,  -19,
126662 /*    10 */    58,   58,  186, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
126663 /*    20 */    67,   67,  182,  336,   65,  250,  135,  263,  340,  417,
126664 /*    30 */   494,  571,  622,  699,  776,  827,  827,  827,  827,  827,
126665 /*    40 */   827,  827,  827,  827,  827,  827,  827,  827,  827,  827,
126666 /*    50 */   878,  827,  929,  980,  980, 1156, 1204, 1204, 1204, 1204,
126667 /*    60 */  1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
126668 /*    70 */  1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
126669 /*    80 */  1204, 1204, 1204, 1204, 1258, 1204, 1204, 1204, 1204, 1204,
126670 /*    90 */  1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,  -71,  -47,
126671 /*   100 */   -47,  -47,  -47,  -47,   -6,   88,  -66,   65,   65,  451,
126672 /*   110 */   502,  112,  112,   33,  127,  278,  -30,  -72,  -72,  -72,
126673 /*   120 */    11,  412,  412,  268,  608,  610,   65,   65,   65,   65,
126674 /*   130 */    65,   65,   65,   65,   65,   65,   65,   65,   65,   65,
126675 /*   140 */    65,   65,   65,   65,   65,  559,  138,  278,  127,   24,
126676 /*   150 */    24,   24,   24,   24,   24,  -72,  -72,  -72,  228,  341,
126677 /*   160 */   341,  207,  276,  300,  352,  354,  350,   65,   65,   65,
126678 /*   170 */    65,   65,   65,   65,   65,   65,   65,   65,   65,   65,
126679 /*   180 */    65,   65,   65,   65,  495,  495,  495,   65,   65,  499,
126680 /*   190 */    65,   65,   65,  574,   65,   65,  517,   65,   65,   65,
126681 /*   200 */    65,   65,   65,   65,   65,   65,   65,  566,  691,  288,
126682 /*   210 */   288,  288,  701,  620, 1058,  675,  603,  964,  964,  967,
126683 /*   220 */   603,  967,  722,  965,  936,  999,  964,  264,  999,  999,
126684 /*   230 */   911,  921,  434, 1196, 1119, 1119, 1202, 1202, 1119, 1222,
126685 /*   240 */  1184, 1126, 1244, 1244, 1244, 1244, 1119, 1251, 1126, 1222,
126686 /*   250 */  1184, 1184, 1126, 1119, 1251, 1145, 1237, 1119, 1119, 1251,
126687 /*   260 */  1275, 1119, 1251, 1119, 1251, 1275, 1203, 1203, 1203, 1264,
126688 /*   270 */  1275, 1203, 1211, 1203, 1264, 1203, 1203, 1194, 1216, 1194,
126689 /*   280 */  1216, 1194, 1216, 1194, 1216, 1119, 1119, 1206, 1275, 1250,
126690 /*   290 */  1250, 1275, 1221, 1225, 1224, 1226, 1126, 1336, 1347, 1363,
126691 /*   300 */  1363, 1371, 1371, 1371, 1371,  -72,  -72,  -72,  -72,  -72,
126692 /*   310 */   -72,  477,  623,  742,  819,  624,  694,   74, 1023,  221,
126693 /*   320 */  1055, 1065, 1077, 1087, 1080,  889, 1031,  939, 1093, 1122,
126694 /*   330 */  1085, 1139,  961, 1024, 1172, 1103,  821, 1384, 1392, 1374,
126695 /*   340 */  1255, 1385, 1331, 1386, 1378, 1381, 1285, 1277, 1298, 1287,
126696 /*   350 */  1393, 1289, 1396, 1414, 1293, 1286, 1340, 1341, 1312, 1397,
126697 /*   360 */  1388, 1304, 1426, 1423, 1407, 1323, 1291, 1379, 1406, 1380,
126698 /*   370 */  1375, 1391, 1330, 1415, 1418, 1421, 1329, 1337, 1422, 1390,
126699 /*   380 */  1424, 1425, 1427, 1429, 1395, 1419, 1430, 1400, 1405, 1431,
126700 /*   390 */  1432, 1433, 1342, 1435, 1436, 1438, 1437, 1339, 1439, 1441,
126701 /*   400 */  1440, 1434, 1443, 1343, 1445, 1442, 1446, 1444, 1445, 1450,
126702 /*   410 */  1451, 1452, 1453, 1454, 1459, 1455, 1460, 1462, 1458, 1461,
126703 /*   420 */  1463, 1466, 1465, 1461, 1467, 1469, 1470, 1471, 1473, 1354,
126704 /*   430 */  1370, 1376, 1377, 1474, 1485, 1484,
126705};
126706#define YY_REDUCE_USE_DFLT (-176)
126707#define YY_REDUCE_COUNT (310)
126708#define YY_REDUCE_MIN   (-175)
126709#define YY_REDUCE_MAX   (1234)
126710static const short yy_reduce_ofst[] = {
126711 /*     0 */  -143,  954,   86,   21,  -50,   23,   79,  134,  170, -175,
126712 /*    10 */   229,  260, -121,  212,  219,  291,  -54,  349,  362,  156,
126713 /*    20 */   309,  311,  334,   85,  224,  394,  314,  314,  314,  314,
126714 /*    30 */   314,  314,  314,  314,  314,  314,  314,  314,  314,  314,
126715 /*    40 */   314,  314,  314,  314,  314,  314,  314,  314,  314,  314,
126716 /*    50 */   314,  314,  314,  314,  314,  374,  441,  443,  450,  452,
126717 /*    60 */   515,  554,  567,  569,  572,  578,  580,  582,  584,  587,
126718 /*    70 */   593,  631,  644,  646,  649,  655,  657,  659,  661,  664,
126719 /*    80 */   708,  720,  759,  771,  810,  822,  861,  873,  912,  930,
126720 /*    90 */   947,  950,  957,  959,  963,  966,  968,  998,  314,  314,
126721 /*   100 */   314,  314,  314,  314,  314,  314,  314,  447,  -53,  166,
126722 /*   110 */   438,  348,  363,  314,  473,  469,  314,  314,  314,  314,
126723 /*   120 */   -15,   59,  101,  688,  220,  220,  525,  256,  729,  735,
126724 /*   130 */   736,  740,  741,  744,  645,  448,  738,  458,  786,  503,
126725 /*   140 */   780,  656,  721,  724,  792,  545,  568,  706,  683,  681,
126726 /*   150 */   779,  784,  830,  831,  835,  678,  601, -104,   -2,   96,
126727 /*   160 */   111,  218,  287,  308,  310,  312,  335,  411,  453,  461,
126728 /*   170 */   573,  599,  617,  658,  665,  670,  732,  734,  775,  848,
126729 /*   180 */   875,  892,  893,  898,  332,  420,  869,  931,  944,  886,
126730 /*   190 */   983,  992, 1009,  958, 1017, 1028,  988, 1033, 1034, 1035,
126731 /*   200 */   287, 1036, 1044, 1045, 1047, 1049, 1056,  915,  972,  997,
126732 /*   210 */  1000, 1002,  886, 1011, 1015, 1061, 1013, 1001, 1003,  977,
126733 /*   220 */  1018,  979, 1050, 1041, 1040, 1052, 1014, 1004, 1059, 1060,
126734 /*   230 */  1032, 1038, 1084,  995, 1089, 1090, 1008, 1016, 1092, 1037,
126735 /*   240 */  1068, 1062, 1069, 1072, 1073, 1074, 1105, 1112, 1071, 1048,
126736 /*   250 */  1081, 1088, 1078, 1116, 1118, 1046, 1066, 1128, 1136, 1140,
126737 /*   260 */  1120, 1147, 1146, 1148, 1150, 1130, 1135, 1137, 1138, 1132,
126738 /*   270 */  1141, 1142, 1143, 1149, 1144, 1153, 1154, 1104, 1107, 1108,
126739 /*   280 */  1114, 1115, 1117, 1123, 1125, 1173, 1176, 1121, 1165, 1127,
126740 /*   290 */  1131, 1167, 1157, 1151, 1158, 1166, 1168, 1212, 1214, 1227,
126741 /*   300 */  1228, 1231, 1232, 1233, 1234, 1152, 1155, 1159, 1198, 1199,
126742 /*   310 */  1219,
126743};
126744static const YYACTIONTYPE yy_default[] = {
126745 /*     0 */   982, 1300, 1300, 1300, 1214, 1214, 1214, 1305, 1300, 1109,
126746 /*    10 */  1138, 1138, 1274, 1305, 1305, 1305, 1305, 1305, 1305, 1212,
126747 /*    20 */  1305, 1305, 1305, 1300, 1305, 1113, 1144, 1305, 1305, 1305,
126748 /*    30 */  1305, 1305, 1305, 1305, 1305, 1273, 1275, 1152, 1151, 1254,
126749 /*    40 */  1125, 1149, 1142, 1146, 1215, 1208, 1209, 1207, 1211, 1216,
126750 /*    50 */  1305, 1145, 1177, 1192, 1176, 1305, 1305, 1305, 1305, 1305,
126751 /*    60 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126752 /*    70 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126753 /*    80 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126754 /*    90 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1186, 1191,
126755 /*   100 */  1198, 1190, 1187, 1179, 1178, 1180, 1181, 1305, 1305, 1008,
126756 /*   110 */  1074, 1305, 1305, 1182, 1305, 1020, 1183, 1195, 1194, 1193,
126757 /*   120 */  1015, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126758 /*   130 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126759 /*   140 */  1305, 1305, 1305, 1305, 1305,  982, 1300, 1305, 1305, 1300,
126760 /*   150 */  1300, 1300, 1300, 1300, 1300, 1292, 1113, 1103, 1305, 1305,
126761 /*   160 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1280, 1278,
126762 /*   170 */  1305, 1227, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126763 /*   180 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126764 /*   190 */  1305, 1305, 1305, 1109, 1305, 1305, 1305, 1305, 1305, 1305,
126765 /*   200 */  1305, 1305, 1305, 1305, 1305, 1305,  988, 1305, 1247, 1109,
126766 /*   210 */  1109, 1109, 1111, 1089, 1101,  990, 1148, 1127, 1127, 1259,
126767 /*   220 */  1148, 1259, 1045, 1068, 1042, 1138, 1127, 1210, 1138, 1138,
126768 /*   230 */  1110, 1101, 1305, 1285, 1118, 1118, 1277, 1277, 1118, 1157,
126769 /*   240 */  1078, 1148, 1085, 1085, 1085, 1085, 1118, 1005, 1148, 1157,
126770 /*   250 */  1078, 1078, 1148, 1118, 1005, 1253, 1251, 1118, 1118, 1005,
126771 /*   260 */  1220, 1118, 1005, 1118, 1005, 1220, 1076, 1076, 1076, 1060,
126772 /*   270 */  1220, 1076, 1045, 1076, 1060, 1076, 1076, 1131, 1126, 1131,
126773 /*   280 */  1126, 1131, 1126, 1131, 1126, 1118, 1118, 1305, 1220, 1224,
126774 /*   290 */  1224, 1220, 1143, 1132, 1141, 1139, 1148, 1011, 1063,  998,
126775 /*   300 */   998,  987,  987,  987,  987, 1297, 1297, 1292, 1047, 1047,
126776 /*   310 */  1030, 1305, 1305, 1305, 1305, 1305, 1305, 1022, 1305, 1229,
126777 /*   320 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126778 /*   330 */  1305, 1305, 1305, 1305, 1305, 1305, 1164, 1305,  983, 1287,
126779 /*   340 */  1305, 1305, 1284, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126780 /*   350 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126781 /*   360 */  1305, 1257, 1305, 1305, 1305, 1305, 1305, 1305, 1250, 1249,
126782 /*   370 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126783 /*   380 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
126784 /*   390 */  1305, 1305, 1092, 1305, 1305, 1305, 1096, 1305, 1305, 1305,
126785 /*   400 */  1305, 1305, 1305, 1305, 1140, 1305, 1133, 1305, 1213, 1305,
126786 /*   410 */  1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1302,
126787 /*   420 */  1305, 1305, 1305, 1301, 1305, 1305, 1305, 1305, 1305, 1166,
126788 /*   430 */  1305, 1165, 1169, 1305,  996, 1305,
126789};
126790
126791/* The next table maps tokens into fallback tokens.  If a construct
126792** like the following:
126793**
126794**      %fallback ID X Y Z.
126795**
126796** appears in the grammar, then ID becomes a fallback token for X, Y,
126797** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
126798** but it does not parse, the type of the token is changed to ID and
126799** the parse is retried before an error is thrown.
126800*/
126801#ifdef YYFALLBACK
126802static const YYCODETYPE yyFallback[] = {
126803    0,  /*          $ => nothing */
126804    0,  /*       SEMI => nothing */
126805   27,  /*    EXPLAIN => ID */
126806   27,  /*      QUERY => ID */
126807   27,  /*       PLAN => ID */
126808   27,  /*      BEGIN => ID */
126809    0,  /* TRANSACTION => nothing */
126810   27,  /*   DEFERRED => ID */
126811   27,  /*  IMMEDIATE => ID */
126812   27,  /*  EXCLUSIVE => ID */
126813    0,  /*     COMMIT => nothing */
126814   27,  /*        END => ID */
126815   27,  /*   ROLLBACK => ID */
126816   27,  /*  SAVEPOINT => ID */
126817   27,  /*    RELEASE => ID */
126818    0,  /*         TO => nothing */
126819    0,  /*      TABLE => nothing */
126820    0,  /*     CREATE => nothing */
126821   27,  /*         IF => ID */
126822    0,  /*        NOT => nothing */
126823    0,  /*     EXISTS => nothing */
126824   27,  /*       TEMP => ID */
126825    0,  /*         LP => nothing */
126826    0,  /*         RP => nothing */
126827    0,  /*         AS => nothing */
126828   27,  /*    WITHOUT => ID */
126829    0,  /*      COMMA => nothing */
126830    0,  /*         ID => nothing */
126831    0,  /*    INDEXED => nothing */
126832   27,  /*      ABORT => ID */
126833   27,  /*     ACTION => ID */
126834   27,  /*      AFTER => ID */
126835   27,  /*    ANALYZE => ID */
126836   27,  /*        ASC => ID */
126837   27,  /*     ATTACH => ID */
126838   27,  /*     BEFORE => ID */
126839   27,  /*         BY => ID */
126840   27,  /*    CASCADE => ID */
126841   27,  /*       CAST => ID */
126842   27,  /*   COLUMNKW => ID */
126843   27,  /*   CONFLICT => ID */
126844   27,  /*   DATABASE => ID */
126845   27,  /*       DESC => ID */
126846   27,  /*     DETACH => ID */
126847   27,  /*       EACH => ID */
126848   27,  /*       FAIL => ID */
126849   27,  /*        FOR => ID */
126850   27,  /*     IGNORE => ID */
126851   27,  /*  INITIALLY => ID */
126852   27,  /*    INSTEAD => ID */
126853   27,  /*    LIKE_KW => ID */
126854   27,  /*      MATCH => ID */
126855   27,  /*         NO => ID */
126856   27,  /*        KEY => ID */
126857   27,  /*         OF => ID */
126858   27,  /*     OFFSET => ID */
126859   27,  /*     PRAGMA => ID */
126860   27,  /*      RAISE => ID */
126861   27,  /*  RECURSIVE => ID */
126862   27,  /*    REPLACE => ID */
126863   27,  /*   RESTRICT => ID */
126864   27,  /*        ROW => ID */
126865   27,  /*    TRIGGER => ID */
126866   27,  /*     VACUUM => ID */
126867   27,  /*       VIEW => ID */
126868   27,  /*    VIRTUAL => ID */
126869   27,  /*       WITH => ID */
126870   27,  /*    REINDEX => ID */
126871   27,  /*     RENAME => ID */
126872   27,  /*   CTIME_KW => ID */
126873};
126874#endif /* YYFALLBACK */
126875
126876/* The following structure represents a single element of the
126877** parser's stack.  Information stored includes:
126878**
126879**   +  The state number for the parser at this level of the stack.
126880**
126881**   +  The value of the token stored at this level of the stack.
126882**      (In other words, the "major" token.)
126883**
126884**   +  The semantic value stored at this level of the stack.  This is
126885**      the information used by the action routines in the grammar.
126886**      It is sometimes called the "minor" token.
126887**
126888** After the "shift" half of a SHIFTREDUCE action, the stateno field
126889** actually contains the reduce action for the second half of the
126890** SHIFTREDUCE.
126891*/
126892struct yyStackEntry {
126893  YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
126894  YYCODETYPE major;      /* The major token value.  This is the code
126895                         ** number for the token at this stack level */
126896  YYMINORTYPE minor;     /* The user-supplied minor token value.  This
126897                         ** is the value of the token  */
126898};
126899typedef struct yyStackEntry yyStackEntry;
126900
126901/* The state of the parser is completely contained in an instance of
126902** the following structure */
126903struct yyParser {
126904  int yyidx;                    /* Index of top element in stack */
126905#ifdef YYTRACKMAXSTACKDEPTH
126906  int yyidxMax;                 /* Maximum value of yyidx */
126907#endif
126908  int yyerrcnt;                 /* Shifts left before out of the error */
126909  sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
126910#if YYSTACKDEPTH<=0
126911  int yystksz;                  /* Current side of the stack */
126912  yyStackEntry *yystack;        /* The parser's stack */
126913#else
126914  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
126915#endif
126916};
126917typedef struct yyParser yyParser;
126918
126919#ifndef NDEBUG
126920/* #include <stdio.h> */
126921static FILE *yyTraceFILE = 0;
126922static char *yyTracePrompt = 0;
126923#endif /* NDEBUG */
126924
126925#ifndef NDEBUG
126926/*
126927** Turn parser tracing on by giving a stream to which to write the trace
126928** and a prompt to preface each trace message.  Tracing is turned off
126929** by making either argument NULL
126930**
126931** Inputs:
126932** <ul>
126933** <li> A FILE* to which trace output should be written.
126934**      If NULL, then tracing is turned off.
126935** <li> A prefix string written at the beginning of every
126936**      line of trace output.  If NULL, then tracing is
126937**      turned off.
126938** </ul>
126939**
126940** Outputs:
126941** None.
126942*/
126943SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
126944  yyTraceFILE = TraceFILE;
126945  yyTracePrompt = zTracePrompt;
126946  if( yyTraceFILE==0 ) yyTracePrompt = 0;
126947  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
126948}
126949#endif /* NDEBUG */
126950
126951#ifndef NDEBUG
126952/* For tracing shifts, the names of all terminals and nonterminals
126953** are required.  The following table supplies these names */
126954static const char *const yyTokenName[] = {
126955  "$",             "SEMI",          "EXPLAIN",       "QUERY",
126956  "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
126957  "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
126958  "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
126959  "TABLE",         "CREATE",        "IF",            "NOT",
126960  "EXISTS",        "TEMP",          "LP",            "RP",
126961  "AS",            "WITHOUT",       "COMMA",         "ID",
126962  "INDEXED",       "ABORT",         "ACTION",        "AFTER",
126963  "ANALYZE",       "ASC",           "ATTACH",        "BEFORE",
126964  "BY",            "CASCADE",       "CAST",          "COLUMNKW",
126965  "CONFLICT",      "DATABASE",      "DESC",          "DETACH",
126966  "EACH",          "FAIL",          "FOR",           "IGNORE",
126967  "INITIALLY",     "INSTEAD",       "LIKE_KW",       "MATCH",
126968  "NO",            "KEY",           "OF",            "OFFSET",
126969  "PRAGMA",        "RAISE",         "RECURSIVE",     "REPLACE",
126970  "RESTRICT",      "ROW",           "TRIGGER",       "VACUUM",
126971  "VIEW",          "VIRTUAL",       "WITH",          "REINDEX",
126972  "RENAME",        "CTIME_KW",      "ANY",           "OR",
126973  "AND",           "IS",            "BETWEEN",       "IN",
126974  "ISNULL",        "NOTNULL",       "NE",            "EQ",
126975  "GT",            "LE",            "LT",            "GE",
126976  "ESCAPE",        "BITAND",        "BITOR",         "LSHIFT",
126977  "RSHIFT",        "PLUS",          "MINUS",         "STAR",
126978  "SLASH",         "REM",           "CONCAT",        "COLLATE",
126979  "BITNOT",        "STRING",        "JOIN_KW",       "CONSTRAINT",
126980  "DEFAULT",       "NULL",          "PRIMARY",       "UNIQUE",
126981  "CHECK",         "REFERENCES",    "AUTOINCR",      "ON",
126982  "INSERT",        "DELETE",        "UPDATE",        "SET",
126983  "DEFERRABLE",    "FOREIGN",       "DROP",          "UNION",
126984  "ALL",           "EXCEPT",        "INTERSECT",     "SELECT",
126985  "VALUES",        "DISTINCT",      "DOT",           "FROM",
126986  "JOIN",          "USING",         "ORDER",         "GROUP",
126987  "HAVING",        "LIMIT",         "WHERE",         "INTO",
126988  "INTEGER",       "FLOAT",         "BLOB",          "VARIABLE",
126989  "CASE",          "WHEN",          "THEN",          "ELSE",
126990  "INDEX",         "ALTER",         "ADD",           "error",
126991  "input",         "cmdlist",       "ecmd",          "explain",
126992  "cmdx",          "cmd",           "transtype",     "trans_opt",
126993  "nm",            "savepoint_opt",  "create_table",  "create_table_args",
126994  "createkw",      "temp",          "ifnotexists",   "dbnm",
126995  "columnlist",    "conslist_opt",  "table_options",  "select",
126996  "column",        "columnid",      "type",          "carglist",
126997  "typetoken",     "typename",      "signed",        "plus_num",
126998  "minus_num",     "ccons",         "term",          "expr",
126999  "onconf",        "sortorder",     "autoinc",       "eidlist_opt",
127000  "refargs",       "defer_subclause",  "refarg",        "refact",
127001  "init_deferred_pred_opt",  "conslist",      "tconscomma",    "tcons",
127002  "sortlist",      "eidlist",       "defer_subclause_opt",  "orconf",
127003  "resolvetype",   "raisetype",     "ifexists",      "fullname",
127004  "selectnowith",  "oneselect",     "with",          "multiselect_op",
127005  "distinct",      "selcollist",    "from",          "where_opt",
127006  "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",
127007  "values",        "nexprlist",     "exprlist",      "sclp",
127008  "as",            "seltablist",    "stl_prefix",    "joinop",
127009  "indexed_opt",   "on_opt",        "using_opt",     "joinop2",
127010  "idlist",        "setlist",       "insert_cmd",    "idlist_opt",
127011  "likeop",        "between_op",    "in_op",         "case_operand",
127012  "case_exprlist",  "case_else",     "uniqueflag",    "collate",
127013  "nmnum",         "trigger_decl",  "trigger_cmd_list",  "trigger_time",
127014  "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd",
127015  "trnm",          "tridxby",       "database_kw_opt",  "key_opt",
127016  "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist",
127017  "vtabarg",       "vtabargtoken",  "lp",            "anylist",
127018  "wqlist",
127019};
127020#endif /* NDEBUG */
127021
127022#ifndef NDEBUG
127023/* For tracing reduce actions, the names of all rules are required.
127024*/
127025static const char *const yyRuleName[] = {
127026 /*   0 */ "input ::= cmdlist",
127027 /*   1 */ "cmdlist ::= cmdlist ecmd",
127028 /*   2 */ "cmdlist ::= ecmd",
127029 /*   3 */ "ecmd ::= SEMI",
127030 /*   4 */ "ecmd ::= explain cmdx SEMI",
127031 /*   5 */ "explain ::=",
127032 /*   6 */ "explain ::= EXPLAIN",
127033 /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
127034 /*   8 */ "cmdx ::= cmd",
127035 /*   9 */ "cmd ::= BEGIN transtype trans_opt",
127036 /*  10 */ "trans_opt ::=",
127037 /*  11 */ "trans_opt ::= TRANSACTION",
127038 /*  12 */ "trans_opt ::= TRANSACTION nm",
127039 /*  13 */ "transtype ::=",
127040 /*  14 */ "transtype ::= DEFERRED",
127041 /*  15 */ "transtype ::= IMMEDIATE",
127042 /*  16 */ "transtype ::= EXCLUSIVE",
127043 /*  17 */ "cmd ::= COMMIT trans_opt",
127044 /*  18 */ "cmd ::= END trans_opt",
127045 /*  19 */ "cmd ::= ROLLBACK trans_opt",
127046 /*  20 */ "savepoint_opt ::= SAVEPOINT",
127047 /*  21 */ "savepoint_opt ::=",
127048 /*  22 */ "cmd ::= SAVEPOINT nm",
127049 /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
127050 /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
127051 /*  25 */ "cmd ::= create_table create_table_args",
127052 /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
127053 /*  27 */ "createkw ::= CREATE",
127054 /*  28 */ "ifnotexists ::=",
127055 /*  29 */ "ifnotexists ::= IF NOT EXISTS",
127056 /*  30 */ "temp ::= TEMP",
127057 /*  31 */ "temp ::=",
127058 /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
127059 /*  33 */ "create_table_args ::= AS select",
127060 /*  34 */ "table_options ::=",
127061 /*  35 */ "table_options ::= WITHOUT nm",
127062 /*  36 */ "columnlist ::= columnlist COMMA column",
127063 /*  37 */ "columnlist ::= column",
127064 /*  38 */ "column ::= columnid type carglist",
127065 /*  39 */ "columnid ::= nm",
127066 /*  40 */ "nm ::= ID|INDEXED",
127067 /*  41 */ "nm ::= STRING",
127068 /*  42 */ "nm ::= JOIN_KW",
127069 /*  43 */ "type ::=",
127070 /*  44 */ "type ::= typetoken",
127071 /*  45 */ "typetoken ::= typename",
127072 /*  46 */ "typetoken ::= typename LP signed RP",
127073 /*  47 */ "typetoken ::= typename LP signed COMMA signed RP",
127074 /*  48 */ "typename ::= ID|STRING",
127075 /*  49 */ "typename ::= typename ID|STRING",
127076 /*  50 */ "signed ::= plus_num",
127077 /*  51 */ "signed ::= minus_num",
127078 /*  52 */ "carglist ::= carglist ccons",
127079 /*  53 */ "carglist ::=",
127080 /*  54 */ "ccons ::= CONSTRAINT nm",
127081 /*  55 */ "ccons ::= DEFAULT term",
127082 /*  56 */ "ccons ::= DEFAULT LP expr RP",
127083 /*  57 */ "ccons ::= DEFAULT PLUS term",
127084 /*  58 */ "ccons ::= DEFAULT MINUS term",
127085 /*  59 */ "ccons ::= DEFAULT ID|INDEXED",
127086 /*  60 */ "ccons ::= NULL onconf",
127087 /*  61 */ "ccons ::= NOT NULL onconf",
127088 /*  62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
127089 /*  63 */ "ccons ::= UNIQUE onconf",
127090 /*  64 */ "ccons ::= CHECK LP expr RP",
127091 /*  65 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
127092 /*  66 */ "ccons ::= defer_subclause",
127093 /*  67 */ "ccons ::= COLLATE ID|STRING",
127094 /*  68 */ "autoinc ::=",
127095 /*  69 */ "autoinc ::= AUTOINCR",
127096 /*  70 */ "refargs ::=",
127097 /*  71 */ "refargs ::= refargs refarg",
127098 /*  72 */ "refarg ::= MATCH nm",
127099 /*  73 */ "refarg ::= ON INSERT refact",
127100 /*  74 */ "refarg ::= ON DELETE refact",
127101 /*  75 */ "refarg ::= ON UPDATE refact",
127102 /*  76 */ "refact ::= SET NULL",
127103 /*  77 */ "refact ::= SET DEFAULT",
127104 /*  78 */ "refact ::= CASCADE",
127105 /*  79 */ "refact ::= RESTRICT",
127106 /*  80 */ "refact ::= NO ACTION",
127107 /*  81 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
127108 /*  82 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
127109 /*  83 */ "init_deferred_pred_opt ::=",
127110 /*  84 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
127111 /*  85 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
127112 /*  86 */ "conslist_opt ::=",
127113 /*  87 */ "conslist_opt ::= COMMA conslist",
127114 /*  88 */ "conslist ::= conslist tconscomma tcons",
127115 /*  89 */ "conslist ::= tcons",
127116 /*  90 */ "tconscomma ::= COMMA",
127117 /*  91 */ "tconscomma ::=",
127118 /*  92 */ "tcons ::= CONSTRAINT nm",
127119 /*  93 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
127120 /*  94 */ "tcons ::= UNIQUE LP sortlist RP onconf",
127121 /*  95 */ "tcons ::= CHECK LP expr RP onconf",
127122 /*  96 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
127123 /*  97 */ "defer_subclause_opt ::=",
127124 /*  98 */ "defer_subclause_opt ::= defer_subclause",
127125 /*  99 */ "onconf ::=",
127126 /* 100 */ "onconf ::= ON CONFLICT resolvetype",
127127 /* 101 */ "orconf ::=",
127128 /* 102 */ "orconf ::= OR resolvetype",
127129 /* 103 */ "resolvetype ::= raisetype",
127130 /* 104 */ "resolvetype ::= IGNORE",
127131 /* 105 */ "resolvetype ::= REPLACE",
127132 /* 106 */ "cmd ::= DROP TABLE ifexists fullname",
127133 /* 107 */ "ifexists ::= IF EXISTS",
127134 /* 108 */ "ifexists ::=",
127135 /* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
127136 /* 110 */ "cmd ::= DROP VIEW ifexists fullname",
127137 /* 111 */ "cmd ::= select",
127138 /* 112 */ "select ::= with selectnowith",
127139 /* 113 */ "selectnowith ::= oneselect",
127140 /* 114 */ "selectnowith ::= selectnowith multiselect_op oneselect",
127141 /* 115 */ "multiselect_op ::= UNION",
127142 /* 116 */ "multiselect_op ::= UNION ALL",
127143 /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
127144 /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
127145 /* 119 */ "oneselect ::= values",
127146 /* 120 */ "values ::= VALUES LP nexprlist RP",
127147 /* 121 */ "values ::= values COMMA LP exprlist RP",
127148 /* 122 */ "distinct ::= DISTINCT",
127149 /* 123 */ "distinct ::= ALL",
127150 /* 124 */ "distinct ::=",
127151 /* 125 */ "sclp ::= selcollist COMMA",
127152 /* 126 */ "sclp ::=",
127153 /* 127 */ "selcollist ::= sclp expr as",
127154 /* 128 */ "selcollist ::= sclp STAR",
127155 /* 129 */ "selcollist ::= sclp nm DOT STAR",
127156 /* 130 */ "as ::= AS nm",
127157 /* 131 */ "as ::= ID|STRING",
127158 /* 132 */ "as ::=",
127159 /* 133 */ "from ::=",
127160 /* 134 */ "from ::= FROM seltablist",
127161 /* 135 */ "stl_prefix ::= seltablist joinop",
127162 /* 136 */ "stl_prefix ::=",
127163 /* 137 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
127164 /* 138 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
127165 /* 139 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
127166 /* 140 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
127167 /* 141 */ "dbnm ::=",
127168 /* 142 */ "dbnm ::= DOT nm",
127169 /* 143 */ "fullname ::= nm dbnm",
127170 /* 144 */ "joinop ::= COMMA|JOIN",
127171 /* 145 */ "joinop ::= JOIN_KW JOIN",
127172 /* 146 */ "joinop ::= JOIN_KW nm JOIN",
127173 /* 147 */ "joinop ::= JOIN_KW nm nm JOIN",
127174 /* 148 */ "on_opt ::= ON expr",
127175 /* 149 */ "on_opt ::=",
127176 /* 150 */ "indexed_opt ::=",
127177 /* 151 */ "indexed_opt ::= INDEXED BY nm",
127178 /* 152 */ "indexed_opt ::= NOT INDEXED",
127179 /* 153 */ "using_opt ::= USING LP idlist RP",
127180 /* 154 */ "using_opt ::=",
127181 /* 155 */ "orderby_opt ::=",
127182 /* 156 */ "orderby_opt ::= ORDER BY sortlist",
127183 /* 157 */ "sortlist ::= sortlist COMMA expr sortorder",
127184 /* 158 */ "sortlist ::= expr sortorder",
127185 /* 159 */ "sortorder ::= ASC",
127186 /* 160 */ "sortorder ::= DESC",
127187 /* 161 */ "sortorder ::=",
127188 /* 162 */ "groupby_opt ::=",
127189 /* 163 */ "groupby_opt ::= GROUP BY nexprlist",
127190 /* 164 */ "having_opt ::=",
127191 /* 165 */ "having_opt ::= HAVING expr",
127192 /* 166 */ "limit_opt ::=",
127193 /* 167 */ "limit_opt ::= LIMIT expr",
127194 /* 168 */ "limit_opt ::= LIMIT expr OFFSET expr",
127195 /* 169 */ "limit_opt ::= LIMIT expr COMMA expr",
127196 /* 170 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
127197 /* 171 */ "where_opt ::=",
127198 /* 172 */ "where_opt ::= WHERE expr",
127199 /* 173 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
127200 /* 174 */ "setlist ::= setlist COMMA nm EQ expr",
127201 /* 175 */ "setlist ::= nm EQ expr",
127202 /* 176 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select",
127203 /* 177 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES",
127204 /* 178 */ "insert_cmd ::= INSERT orconf",
127205 /* 179 */ "insert_cmd ::= REPLACE",
127206 /* 180 */ "idlist_opt ::=",
127207 /* 181 */ "idlist_opt ::= LP idlist RP",
127208 /* 182 */ "idlist ::= idlist COMMA nm",
127209 /* 183 */ "idlist ::= nm",
127210 /* 184 */ "expr ::= term",
127211 /* 185 */ "expr ::= LP expr RP",
127212 /* 186 */ "term ::= NULL",
127213 /* 187 */ "expr ::= ID|INDEXED",
127214 /* 188 */ "expr ::= JOIN_KW",
127215 /* 189 */ "expr ::= nm DOT nm",
127216 /* 190 */ "expr ::= nm DOT nm DOT nm",
127217 /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
127218 /* 192 */ "term ::= STRING",
127219 /* 193 */ "expr ::= VARIABLE",
127220 /* 194 */ "expr ::= expr COLLATE ID|STRING",
127221 /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
127222 /* 196 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
127223 /* 197 */ "expr ::= ID|INDEXED LP STAR RP",
127224 /* 198 */ "term ::= CTIME_KW",
127225 /* 199 */ "expr ::= expr AND expr",
127226 /* 200 */ "expr ::= expr OR expr",
127227 /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
127228 /* 202 */ "expr ::= expr EQ|NE expr",
127229 /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
127230 /* 204 */ "expr ::= expr PLUS|MINUS expr",
127231 /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
127232 /* 206 */ "expr ::= expr CONCAT expr",
127233 /* 207 */ "likeop ::= LIKE_KW|MATCH",
127234 /* 208 */ "likeop ::= NOT LIKE_KW|MATCH",
127235 /* 209 */ "expr ::= expr likeop expr",
127236 /* 210 */ "expr ::= expr likeop expr ESCAPE expr",
127237 /* 211 */ "expr ::= expr ISNULL|NOTNULL",
127238 /* 212 */ "expr ::= expr NOT NULL",
127239 /* 213 */ "expr ::= expr IS expr",
127240 /* 214 */ "expr ::= expr IS NOT expr",
127241 /* 215 */ "expr ::= NOT expr",
127242 /* 216 */ "expr ::= BITNOT expr",
127243 /* 217 */ "expr ::= MINUS expr",
127244 /* 218 */ "expr ::= PLUS expr",
127245 /* 219 */ "between_op ::= BETWEEN",
127246 /* 220 */ "between_op ::= NOT BETWEEN",
127247 /* 221 */ "expr ::= expr between_op expr AND expr",
127248 /* 222 */ "in_op ::= IN",
127249 /* 223 */ "in_op ::= NOT IN",
127250 /* 224 */ "expr ::= expr in_op LP exprlist RP",
127251 /* 225 */ "expr ::= LP select RP",
127252 /* 226 */ "expr ::= expr in_op LP select RP",
127253 /* 227 */ "expr ::= expr in_op nm dbnm",
127254 /* 228 */ "expr ::= EXISTS LP select RP",
127255 /* 229 */ "expr ::= CASE case_operand case_exprlist case_else END",
127256 /* 230 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
127257 /* 231 */ "case_exprlist ::= WHEN expr THEN expr",
127258 /* 232 */ "case_else ::= ELSE expr",
127259 /* 233 */ "case_else ::=",
127260 /* 234 */ "case_operand ::= expr",
127261 /* 235 */ "case_operand ::=",
127262 /* 236 */ "exprlist ::= nexprlist",
127263 /* 237 */ "exprlist ::=",
127264 /* 238 */ "nexprlist ::= nexprlist COMMA expr",
127265 /* 239 */ "nexprlist ::= expr",
127266 /* 240 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
127267 /* 241 */ "uniqueflag ::= UNIQUE",
127268 /* 242 */ "uniqueflag ::=",
127269 /* 243 */ "eidlist_opt ::=",
127270 /* 244 */ "eidlist_opt ::= LP eidlist RP",
127271 /* 245 */ "eidlist ::= eidlist COMMA nm collate sortorder",
127272 /* 246 */ "eidlist ::= nm collate sortorder",
127273 /* 247 */ "collate ::=",
127274 /* 248 */ "collate ::= COLLATE ID|STRING",
127275 /* 249 */ "cmd ::= DROP INDEX ifexists fullname",
127276 /* 250 */ "cmd ::= VACUUM",
127277 /* 251 */ "cmd ::= VACUUM nm",
127278 /* 252 */ "cmd ::= PRAGMA nm dbnm",
127279 /* 253 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
127280 /* 254 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
127281 /* 255 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
127282 /* 256 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
127283 /* 257 */ "nmnum ::= plus_num",
127284 /* 258 */ "nmnum ::= nm",
127285 /* 259 */ "nmnum ::= ON",
127286 /* 260 */ "nmnum ::= DELETE",
127287 /* 261 */ "nmnum ::= DEFAULT",
127288 /* 262 */ "plus_num ::= PLUS INTEGER|FLOAT",
127289 /* 263 */ "plus_num ::= INTEGER|FLOAT",
127290 /* 264 */ "minus_num ::= MINUS INTEGER|FLOAT",
127291 /* 265 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
127292 /* 266 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
127293 /* 267 */ "trigger_time ::= BEFORE",
127294 /* 268 */ "trigger_time ::= AFTER",
127295 /* 269 */ "trigger_time ::= INSTEAD OF",
127296 /* 270 */ "trigger_time ::=",
127297 /* 271 */ "trigger_event ::= DELETE|INSERT",
127298 /* 272 */ "trigger_event ::= UPDATE",
127299 /* 273 */ "trigger_event ::= UPDATE OF idlist",
127300 /* 274 */ "foreach_clause ::=",
127301 /* 275 */ "foreach_clause ::= FOR EACH ROW",
127302 /* 276 */ "when_clause ::=",
127303 /* 277 */ "when_clause ::= WHEN expr",
127304 /* 278 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
127305 /* 279 */ "trigger_cmd_list ::= trigger_cmd SEMI",
127306 /* 280 */ "trnm ::= nm",
127307 /* 281 */ "trnm ::= nm DOT nm",
127308 /* 282 */ "tridxby ::=",
127309 /* 283 */ "tridxby ::= INDEXED BY nm",
127310 /* 284 */ "tridxby ::= NOT INDEXED",
127311 /* 285 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
127312 /* 286 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select",
127313 /* 287 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
127314 /* 288 */ "trigger_cmd ::= select",
127315 /* 289 */ "expr ::= RAISE LP IGNORE RP",
127316 /* 290 */ "expr ::= RAISE LP raisetype COMMA nm RP",
127317 /* 291 */ "raisetype ::= ROLLBACK",
127318 /* 292 */ "raisetype ::= ABORT",
127319 /* 293 */ "raisetype ::= FAIL",
127320 /* 294 */ "cmd ::= DROP TRIGGER ifexists fullname",
127321 /* 295 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
127322 /* 296 */ "cmd ::= DETACH database_kw_opt expr",
127323 /* 297 */ "key_opt ::=",
127324 /* 298 */ "key_opt ::= KEY expr",
127325 /* 299 */ "database_kw_opt ::= DATABASE",
127326 /* 300 */ "database_kw_opt ::=",
127327 /* 301 */ "cmd ::= REINDEX",
127328 /* 302 */ "cmd ::= REINDEX nm dbnm",
127329 /* 303 */ "cmd ::= ANALYZE",
127330 /* 304 */ "cmd ::= ANALYZE nm dbnm",
127331 /* 305 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
127332 /* 306 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
127333 /* 307 */ "add_column_fullname ::= fullname",
127334 /* 308 */ "kwcolumn_opt ::=",
127335 /* 309 */ "kwcolumn_opt ::= COLUMNKW",
127336 /* 310 */ "cmd ::= create_vtab",
127337 /* 311 */ "cmd ::= create_vtab LP vtabarglist RP",
127338 /* 312 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
127339 /* 313 */ "vtabarglist ::= vtabarg",
127340 /* 314 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
127341 /* 315 */ "vtabarg ::=",
127342 /* 316 */ "vtabarg ::= vtabarg vtabargtoken",
127343 /* 317 */ "vtabargtoken ::= ANY",
127344 /* 318 */ "vtabargtoken ::= lp anylist RP",
127345 /* 319 */ "lp ::= LP",
127346 /* 320 */ "anylist ::=",
127347 /* 321 */ "anylist ::= anylist LP anylist RP",
127348 /* 322 */ "anylist ::= anylist ANY",
127349 /* 323 */ "with ::=",
127350 /* 324 */ "with ::= WITH wqlist",
127351 /* 325 */ "with ::= WITH RECURSIVE wqlist",
127352 /* 326 */ "wqlist ::= nm eidlist_opt AS LP select RP",
127353 /* 327 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
127354};
127355#endif /* NDEBUG */
127356
127357
127358#if YYSTACKDEPTH<=0
127359/*
127360** Try to increase the size of the parser stack.
127361*/
127362static void yyGrowStack(yyParser *p){
127363  int newSize;
127364  yyStackEntry *pNew;
127365
127366  newSize = p->yystksz*2 + 100;
127367  pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
127368  if( pNew ){
127369    p->yystack = pNew;
127370    p->yystksz = newSize;
127371#ifndef NDEBUG
127372    if( yyTraceFILE ){
127373      fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
127374              yyTracePrompt, p->yystksz);
127375    }
127376#endif
127377  }
127378}
127379#endif
127380
127381/*
127382** This function allocates a new parser.
127383** The only argument is a pointer to a function which works like
127384** malloc.
127385**
127386** Inputs:
127387** A pointer to the function used to allocate memory.
127388**
127389** Outputs:
127390** A pointer to a parser.  This pointer is used in subsequent calls
127391** to sqlite3Parser and sqlite3ParserFree.
127392*/
127393SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(u64)){
127394  yyParser *pParser;
127395  pParser = (yyParser*)(*mallocProc)( (u64)sizeof(yyParser) );
127396  if( pParser ){
127397    pParser->yyidx = -1;
127398#ifdef YYTRACKMAXSTACKDEPTH
127399    pParser->yyidxMax = 0;
127400#endif
127401#if YYSTACKDEPTH<=0
127402    pParser->yystack = NULL;
127403    pParser->yystksz = 0;
127404    yyGrowStack(pParser);
127405#endif
127406  }
127407  return pParser;
127408}
127409
127410/* The following function deletes the value associated with a
127411** symbol.  The symbol can be either a terminal or nonterminal.
127412** "yymajor" is the symbol code, and "yypminor" is a pointer to
127413** the value.
127414*/
127415static void yy_destructor(
127416  yyParser *yypParser,    /* The parser */
127417  YYCODETYPE yymajor,     /* Type code for object to destroy */
127418  YYMINORTYPE *yypminor   /* The object to be destroyed */
127419){
127420  sqlite3ParserARG_FETCH;
127421  switch( yymajor ){
127422    /* Here is inserted the actions which take place when a
127423    ** terminal or non-terminal is destroyed.  This can happen
127424    ** when the symbol is popped from the stack during a
127425    ** reduce or during error processing or when a parser is
127426    ** being destroyed before it is finished parsing.
127427    **
127428    ** Note: during a reduce, the only symbols destroyed are those
127429    ** which appear on the RHS of the rule, but which are not used
127430    ** inside the C code.
127431    */
127432    case 163: /* select */
127433    case 196: /* selectnowith */
127434    case 197: /* oneselect */
127435    case 208: /* values */
127436{
127437sqlite3SelectDelete(pParse->db, (yypminor->yy3));
127438}
127439      break;
127440    case 174: /* term */
127441    case 175: /* expr */
127442{
127443sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
127444}
127445      break;
127446    case 179: /* eidlist_opt */
127447    case 188: /* sortlist */
127448    case 189: /* eidlist */
127449    case 201: /* selcollist */
127450    case 204: /* groupby_opt */
127451    case 206: /* orderby_opt */
127452    case 209: /* nexprlist */
127453    case 210: /* exprlist */
127454    case 211: /* sclp */
127455    case 221: /* setlist */
127456    case 228: /* case_exprlist */
127457{
127458sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
127459}
127460      break;
127461    case 195: /* fullname */
127462    case 202: /* from */
127463    case 213: /* seltablist */
127464    case 214: /* stl_prefix */
127465{
127466sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
127467}
127468      break;
127469    case 198: /* with */
127470    case 252: /* wqlist */
127471{
127472sqlite3WithDelete(pParse->db, (yypminor->yy59));
127473}
127474      break;
127475    case 203: /* where_opt */
127476    case 205: /* having_opt */
127477    case 217: /* on_opt */
127478    case 227: /* case_operand */
127479    case 229: /* case_else */
127480    case 238: /* when_clause */
127481    case 243: /* key_opt */
127482{
127483sqlite3ExprDelete(pParse->db, (yypminor->yy132));
127484}
127485      break;
127486    case 218: /* using_opt */
127487    case 220: /* idlist */
127488    case 223: /* idlist_opt */
127489{
127490sqlite3IdListDelete(pParse->db, (yypminor->yy408));
127491}
127492      break;
127493    case 234: /* trigger_cmd_list */
127494    case 239: /* trigger_cmd */
127495{
127496sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
127497}
127498      break;
127499    case 236: /* trigger_event */
127500{
127501sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
127502}
127503      break;
127504    default:  break;   /* If no destructor action specified: do nothing */
127505  }
127506}
127507
127508/*
127509** Pop the parser's stack once.
127510**
127511** If there is a destructor routine associated with the token which
127512** is popped from the stack, then call it.
127513**
127514** Return the major token number for the symbol popped.
127515*/
127516static int yy_pop_parser_stack(yyParser *pParser){
127517  YYCODETYPE yymajor;
127518  yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
127519
127520  /* There is no mechanism by which the parser stack can be popped below
127521  ** empty in SQLite.  */
127522  assert( pParser->yyidx>=0 );
127523#ifndef NDEBUG
127524  if( yyTraceFILE && pParser->yyidx>=0 ){
127525    fprintf(yyTraceFILE,"%sPopping %s\n",
127526      yyTracePrompt,
127527      yyTokenName[yytos->major]);
127528  }
127529#endif
127530  yymajor = yytos->major;
127531  yy_destructor(pParser, yymajor, &yytos->minor);
127532  pParser->yyidx--;
127533  return yymajor;
127534}
127535
127536/*
127537** Deallocate and destroy a parser.  Destructors are all called for
127538** all stack elements before shutting the parser down.
127539**
127540** Inputs:
127541** <ul>
127542** <li>  A pointer to the parser.  This should be a pointer
127543**       obtained from sqlite3ParserAlloc.
127544** <li>  A pointer to a function used to reclaim memory obtained
127545**       from malloc.
127546** </ul>
127547*/
127548SQLITE_PRIVATE void sqlite3ParserFree(
127549  void *p,                    /* The parser to be deleted */
127550  void (*freeProc)(void*)     /* Function used to reclaim memory */
127551){
127552  yyParser *pParser = (yyParser*)p;
127553  /* In SQLite, we never try to destroy a parser that was not successfully
127554  ** created in the first place. */
127555  if( NEVER(pParser==0) ) return;
127556  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
127557#if YYSTACKDEPTH<=0
127558  free(pParser->yystack);
127559#endif
127560  (*freeProc)((void*)pParser);
127561}
127562
127563/*
127564** Return the peak depth of the stack for a parser.
127565*/
127566#ifdef YYTRACKMAXSTACKDEPTH
127567SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
127568  yyParser *pParser = (yyParser*)p;
127569  return pParser->yyidxMax;
127570}
127571#endif
127572
127573/*
127574** Find the appropriate action for a parser given the terminal
127575** look-ahead token iLookAhead.
127576**
127577** If the look-ahead token is YYNOCODE, then check to see if the action is
127578** independent of the look-ahead.  If it is, return the action, otherwise
127579** return YY_NO_ACTION.
127580*/
127581static int yy_find_shift_action(
127582  yyParser *pParser,        /* The parser */
127583  YYCODETYPE iLookAhead     /* The look-ahead token */
127584){
127585  int i;
127586  int stateno = pParser->yystack[pParser->yyidx].stateno;
127587
127588  if( stateno>=YY_MIN_REDUCE ) return stateno;
127589  assert( stateno <= YY_SHIFT_COUNT );
127590  i = yy_shift_ofst[stateno];
127591  if( i==YY_SHIFT_USE_DFLT ) return yy_default[stateno];
127592  assert( iLookAhead!=YYNOCODE );
127593  i += iLookAhead;
127594  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
127595    if( iLookAhead>0 ){
127596#ifdef YYFALLBACK
127597      YYCODETYPE iFallback;            /* Fallback token */
127598      if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
127599             && (iFallback = yyFallback[iLookAhead])!=0 ){
127600#ifndef NDEBUG
127601        if( yyTraceFILE ){
127602          fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
127603             yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
127604        }
127605#endif
127606        return yy_find_shift_action(pParser, iFallback);
127607      }
127608#endif
127609#ifdef YYWILDCARD
127610      {
127611        int j = i - iLookAhead + YYWILDCARD;
127612        if(
127613#if YY_SHIFT_MIN+YYWILDCARD<0
127614          j>=0 &&
127615#endif
127616#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
127617          j<YY_ACTTAB_COUNT &&
127618#endif
127619          yy_lookahead[j]==YYWILDCARD
127620        ){
127621#ifndef NDEBUG
127622          if( yyTraceFILE ){
127623            fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
127624               yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
127625          }
127626#endif /* NDEBUG */
127627          return yy_action[j];
127628        }
127629      }
127630#endif /* YYWILDCARD */
127631    }
127632    return yy_default[stateno];
127633  }else{
127634    return yy_action[i];
127635  }
127636}
127637
127638/*
127639** Find the appropriate action for a parser given the non-terminal
127640** look-ahead token iLookAhead.
127641**
127642** If the look-ahead token is YYNOCODE, then check to see if the action is
127643** independent of the look-ahead.  If it is, return the action, otherwise
127644** return YY_NO_ACTION.
127645*/
127646static int yy_find_reduce_action(
127647  int stateno,              /* Current state number */
127648  YYCODETYPE iLookAhead     /* The look-ahead token */
127649){
127650  int i;
127651#ifdef YYERRORSYMBOL
127652  if( stateno>YY_REDUCE_COUNT ){
127653    return yy_default[stateno];
127654  }
127655#else
127656  assert( stateno<=YY_REDUCE_COUNT );
127657#endif
127658  i = yy_reduce_ofst[stateno];
127659  assert( i!=YY_REDUCE_USE_DFLT );
127660  assert( iLookAhead!=YYNOCODE );
127661  i += iLookAhead;
127662#ifdef YYERRORSYMBOL
127663  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
127664    return yy_default[stateno];
127665  }
127666#else
127667  assert( i>=0 && i<YY_ACTTAB_COUNT );
127668  assert( yy_lookahead[i]==iLookAhead );
127669#endif
127670  return yy_action[i];
127671}
127672
127673/*
127674** The following routine is called if the stack overflows.
127675*/
127676static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
127677   sqlite3ParserARG_FETCH;
127678   yypParser->yyidx--;
127679#ifndef NDEBUG
127680   if( yyTraceFILE ){
127681     fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
127682   }
127683#endif
127684   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
127685   /* Here code is inserted which will execute if the parser
127686   ** stack every overflows */
127687
127688  UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
127689  sqlite3ErrorMsg(pParse, "parser stack overflow");
127690   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
127691}
127692
127693/*
127694** Print tracing information for a SHIFT action
127695*/
127696#ifndef NDEBUG
127697static void yyTraceShift(yyParser *yypParser, int yyNewState){
127698  if( yyTraceFILE ){
127699    int i;
127700    if( yyNewState<YYNSTATE ){
127701      fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
127702      fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
127703      for(i=1; i<=yypParser->yyidx; i++)
127704        fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
127705      fprintf(yyTraceFILE,"\n");
127706    }else{
127707      fprintf(yyTraceFILE,"%sShift *\n",yyTracePrompt);
127708    }
127709  }
127710}
127711#else
127712# define yyTraceShift(X,Y)
127713#endif
127714
127715/*
127716** Perform a shift action.  Return the number of errors.
127717*/
127718static void yy_shift(
127719  yyParser *yypParser,          /* The parser to be shifted */
127720  int yyNewState,               /* The new state to shift in */
127721  int yyMajor,                  /* The major token to shift in */
127722  YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
127723){
127724  yyStackEntry *yytos;
127725  yypParser->yyidx++;
127726#ifdef YYTRACKMAXSTACKDEPTH
127727  if( yypParser->yyidx>yypParser->yyidxMax ){
127728    yypParser->yyidxMax = yypParser->yyidx;
127729  }
127730#endif
127731#if YYSTACKDEPTH>0
127732  if( yypParser->yyidx>=YYSTACKDEPTH ){
127733    yyStackOverflow(yypParser, yypMinor);
127734    return;
127735  }
127736#else
127737  if( yypParser->yyidx>=yypParser->yystksz ){
127738    yyGrowStack(yypParser);
127739    if( yypParser->yyidx>=yypParser->yystksz ){
127740      yyStackOverflow(yypParser, yypMinor);
127741      return;
127742    }
127743  }
127744#endif
127745  yytos = &yypParser->yystack[yypParser->yyidx];
127746  yytos->stateno = (YYACTIONTYPE)yyNewState;
127747  yytos->major = (YYCODETYPE)yyMajor;
127748  yytos->minor = *yypMinor;
127749  yyTraceShift(yypParser, yyNewState);
127750}
127751
127752/* The following table contains information about every rule that
127753** is used during the reduce.
127754*/
127755static const struct {
127756  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
127757  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
127758} yyRuleInfo[] = {
127759  { 144, 1 },
127760  { 145, 2 },
127761  { 145, 1 },
127762  { 146, 1 },
127763  { 146, 3 },
127764  { 147, 0 },
127765  { 147, 1 },
127766  { 147, 3 },
127767  { 148, 1 },
127768  { 149, 3 },
127769  { 151, 0 },
127770  { 151, 1 },
127771  { 151, 2 },
127772  { 150, 0 },
127773  { 150, 1 },
127774  { 150, 1 },
127775  { 150, 1 },
127776  { 149, 2 },
127777  { 149, 2 },
127778  { 149, 2 },
127779  { 153, 1 },
127780  { 153, 0 },
127781  { 149, 2 },
127782  { 149, 3 },
127783  { 149, 5 },
127784  { 149, 2 },
127785  { 154, 6 },
127786  { 156, 1 },
127787  { 158, 0 },
127788  { 158, 3 },
127789  { 157, 1 },
127790  { 157, 0 },
127791  { 155, 5 },
127792  { 155, 2 },
127793  { 162, 0 },
127794  { 162, 2 },
127795  { 160, 3 },
127796  { 160, 1 },
127797  { 164, 3 },
127798  { 165, 1 },
127799  { 152, 1 },
127800  { 152, 1 },
127801  { 152, 1 },
127802  { 166, 0 },
127803  { 166, 1 },
127804  { 168, 1 },
127805  { 168, 4 },
127806  { 168, 6 },
127807  { 169, 1 },
127808  { 169, 2 },
127809  { 170, 1 },
127810  { 170, 1 },
127811  { 167, 2 },
127812  { 167, 0 },
127813  { 173, 2 },
127814  { 173, 2 },
127815  { 173, 4 },
127816  { 173, 3 },
127817  { 173, 3 },
127818  { 173, 2 },
127819  { 173, 2 },
127820  { 173, 3 },
127821  { 173, 5 },
127822  { 173, 2 },
127823  { 173, 4 },
127824  { 173, 4 },
127825  { 173, 1 },
127826  { 173, 2 },
127827  { 178, 0 },
127828  { 178, 1 },
127829  { 180, 0 },
127830  { 180, 2 },
127831  { 182, 2 },
127832  { 182, 3 },
127833  { 182, 3 },
127834  { 182, 3 },
127835  { 183, 2 },
127836  { 183, 2 },
127837  { 183, 1 },
127838  { 183, 1 },
127839  { 183, 2 },
127840  { 181, 3 },
127841  { 181, 2 },
127842  { 184, 0 },
127843  { 184, 2 },
127844  { 184, 2 },
127845  { 161, 0 },
127846  { 161, 2 },
127847  { 185, 3 },
127848  { 185, 1 },
127849  { 186, 1 },
127850  { 186, 0 },
127851  { 187, 2 },
127852  { 187, 7 },
127853  { 187, 5 },
127854  { 187, 5 },
127855  { 187, 10 },
127856  { 190, 0 },
127857  { 190, 1 },
127858  { 176, 0 },
127859  { 176, 3 },
127860  { 191, 0 },
127861  { 191, 2 },
127862  { 192, 1 },
127863  { 192, 1 },
127864  { 192, 1 },
127865  { 149, 4 },
127866  { 194, 2 },
127867  { 194, 0 },
127868  { 149, 9 },
127869  { 149, 4 },
127870  { 149, 1 },
127871  { 163, 2 },
127872  { 196, 1 },
127873  { 196, 3 },
127874  { 199, 1 },
127875  { 199, 2 },
127876  { 199, 1 },
127877  { 197, 9 },
127878  { 197, 1 },
127879  { 208, 4 },
127880  { 208, 5 },
127881  { 200, 1 },
127882  { 200, 1 },
127883  { 200, 0 },
127884  { 211, 2 },
127885  { 211, 0 },
127886  { 201, 3 },
127887  { 201, 2 },
127888  { 201, 4 },
127889  { 212, 2 },
127890  { 212, 1 },
127891  { 212, 0 },
127892  { 202, 0 },
127893  { 202, 2 },
127894  { 214, 2 },
127895  { 214, 0 },
127896  { 213, 7 },
127897  { 213, 9 },
127898  { 213, 7 },
127899  { 213, 7 },
127900  { 159, 0 },
127901  { 159, 2 },
127902  { 195, 2 },
127903  { 215, 1 },
127904  { 215, 2 },
127905  { 215, 3 },
127906  { 215, 4 },
127907  { 217, 2 },
127908  { 217, 0 },
127909  { 216, 0 },
127910  { 216, 3 },
127911  { 216, 2 },
127912  { 218, 4 },
127913  { 218, 0 },
127914  { 206, 0 },
127915  { 206, 3 },
127916  { 188, 4 },
127917  { 188, 2 },
127918  { 177, 1 },
127919  { 177, 1 },
127920  { 177, 0 },
127921  { 204, 0 },
127922  { 204, 3 },
127923  { 205, 0 },
127924  { 205, 2 },
127925  { 207, 0 },
127926  { 207, 2 },
127927  { 207, 4 },
127928  { 207, 4 },
127929  { 149, 6 },
127930  { 203, 0 },
127931  { 203, 2 },
127932  { 149, 8 },
127933  { 221, 5 },
127934  { 221, 3 },
127935  { 149, 6 },
127936  { 149, 7 },
127937  { 222, 2 },
127938  { 222, 1 },
127939  { 223, 0 },
127940  { 223, 3 },
127941  { 220, 3 },
127942  { 220, 1 },
127943  { 175, 1 },
127944  { 175, 3 },
127945  { 174, 1 },
127946  { 175, 1 },
127947  { 175, 1 },
127948  { 175, 3 },
127949  { 175, 5 },
127950  { 174, 1 },
127951  { 174, 1 },
127952  { 175, 1 },
127953  { 175, 3 },
127954  { 175, 6 },
127955  { 175, 5 },
127956  { 175, 4 },
127957  { 174, 1 },
127958  { 175, 3 },
127959  { 175, 3 },
127960  { 175, 3 },
127961  { 175, 3 },
127962  { 175, 3 },
127963  { 175, 3 },
127964  { 175, 3 },
127965  { 175, 3 },
127966  { 224, 1 },
127967  { 224, 2 },
127968  { 175, 3 },
127969  { 175, 5 },
127970  { 175, 2 },
127971  { 175, 3 },
127972  { 175, 3 },
127973  { 175, 4 },
127974  { 175, 2 },
127975  { 175, 2 },
127976  { 175, 2 },
127977  { 175, 2 },
127978  { 225, 1 },
127979  { 225, 2 },
127980  { 175, 5 },
127981  { 226, 1 },
127982  { 226, 2 },
127983  { 175, 5 },
127984  { 175, 3 },
127985  { 175, 5 },
127986  { 175, 4 },
127987  { 175, 4 },
127988  { 175, 5 },
127989  { 228, 5 },
127990  { 228, 4 },
127991  { 229, 2 },
127992  { 229, 0 },
127993  { 227, 1 },
127994  { 227, 0 },
127995  { 210, 1 },
127996  { 210, 0 },
127997  { 209, 3 },
127998  { 209, 1 },
127999  { 149, 12 },
128000  { 230, 1 },
128001  { 230, 0 },
128002  { 179, 0 },
128003  { 179, 3 },
128004  { 189, 5 },
128005  { 189, 3 },
128006  { 231, 0 },
128007  { 231, 2 },
128008  { 149, 4 },
128009  { 149, 1 },
128010  { 149, 2 },
128011  { 149, 3 },
128012  { 149, 5 },
128013  { 149, 6 },
128014  { 149, 5 },
128015  { 149, 6 },
128016  { 232, 1 },
128017  { 232, 1 },
128018  { 232, 1 },
128019  { 232, 1 },
128020  { 232, 1 },
128021  { 171, 2 },
128022  { 171, 1 },
128023  { 172, 2 },
128024  { 149, 5 },
128025  { 233, 11 },
128026  { 235, 1 },
128027  { 235, 1 },
128028  { 235, 2 },
128029  { 235, 0 },
128030  { 236, 1 },
128031  { 236, 1 },
128032  { 236, 3 },
128033  { 237, 0 },
128034  { 237, 3 },
128035  { 238, 0 },
128036  { 238, 2 },
128037  { 234, 3 },
128038  { 234, 2 },
128039  { 240, 1 },
128040  { 240, 3 },
128041  { 241, 0 },
128042  { 241, 3 },
128043  { 241, 2 },
128044  { 239, 7 },
128045  { 239, 5 },
128046  { 239, 5 },
128047  { 239, 1 },
128048  { 175, 4 },
128049  { 175, 6 },
128050  { 193, 1 },
128051  { 193, 1 },
128052  { 193, 1 },
128053  { 149, 4 },
128054  { 149, 6 },
128055  { 149, 3 },
128056  { 243, 0 },
128057  { 243, 2 },
128058  { 242, 1 },
128059  { 242, 0 },
128060  { 149, 1 },
128061  { 149, 3 },
128062  { 149, 1 },
128063  { 149, 3 },
128064  { 149, 6 },
128065  { 149, 6 },
128066  { 244, 1 },
128067  { 245, 0 },
128068  { 245, 1 },
128069  { 149, 1 },
128070  { 149, 4 },
128071  { 246, 8 },
128072  { 247, 1 },
128073  { 247, 3 },
128074  { 248, 0 },
128075  { 248, 2 },
128076  { 249, 1 },
128077  { 249, 3 },
128078  { 250, 1 },
128079  { 251, 0 },
128080  { 251, 4 },
128081  { 251, 2 },
128082  { 198, 0 },
128083  { 198, 2 },
128084  { 198, 3 },
128085  { 252, 6 },
128086  { 252, 8 },
128087};
128088
128089static void yy_accept(yyParser*);  /* Forward Declaration */
128090
128091/*
128092** Perform a reduce action and the shift that must immediately
128093** follow the reduce.
128094*/
128095static void yy_reduce(
128096  yyParser *yypParser,         /* The parser */
128097  int yyruleno                 /* Number of the rule by which to reduce */
128098){
128099  int yygoto;                     /* The next state */
128100  int yyact;                      /* The next action */
128101  YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
128102  yyStackEntry *yymsp;            /* The top of the parser's stack */
128103  int yysize;                     /* Amount to pop the stack */
128104  sqlite3ParserARG_FETCH;
128105  yymsp = &yypParser->yystack[yypParser->yyidx];
128106#ifndef NDEBUG
128107  if( yyTraceFILE && yyruleno>=0
128108        && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
128109    yysize = yyRuleInfo[yyruleno].nrhs;
128110    fprintf(yyTraceFILE, "%sReduce [%s] -> state %d.\n", yyTracePrompt,
128111      yyRuleName[yyruleno], yymsp[-yysize].stateno);
128112  }
128113#endif /* NDEBUG */
128114
128115  /* Silence complaints from purify about yygotominor being uninitialized
128116  ** in some cases when it is copied into the stack after the following
128117  ** switch.  yygotominor is uninitialized when a rule reduces that does
128118  ** not set the value of its left-hand side nonterminal.  Leaving the
128119  ** value of the nonterminal uninitialized is utterly harmless as long
128120  ** as the value is never used.  So really the only thing this code
128121  ** accomplishes is to quieten purify.
128122  **
128123  ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
128124  ** without this code, their parser segfaults.  I'm not sure what there
128125  ** parser is doing to make this happen.  This is the second bug report
128126  ** from wireshark this week.  Clearly they are stressing Lemon in ways
128127  ** that it has not been previously stressed...  (SQLite ticket #2172)
128128  */
128129  /*memset(&yygotominor, 0, sizeof(yygotominor));*/
128130  yygotominor = yyzerominor;
128131
128132
128133  switch( yyruleno ){
128134  /* Beginning here are the reduction cases.  A typical example
128135  ** follows:
128136  **   case 0:
128137  **  #line <lineno> <grammarfile>
128138  **     { ... }           // User supplied code
128139  **  #line <lineno> <thisfile>
128140  **     break;
128141  */
128142      case 5: /* explain ::= */
128143{ sqlite3BeginParse(pParse, 0); }
128144        break;
128145      case 6: /* explain ::= EXPLAIN */
128146{ sqlite3BeginParse(pParse, 1); }
128147        break;
128148      case 7: /* explain ::= EXPLAIN QUERY PLAN */
128149{ sqlite3BeginParse(pParse, 2); }
128150        break;
128151      case 8: /* cmdx ::= cmd */
128152{ sqlite3FinishCoding(pParse); }
128153        break;
128154      case 9: /* cmd ::= BEGIN transtype trans_opt */
128155{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
128156        break;
128157      case 13: /* transtype ::= */
128158{yygotominor.yy328 = TK_DEFERRED;}
128159        break;
128160      case 14: /* transtype ::= DEFERRED */
128161      case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
128162      case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
128163      case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
128164      case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
128165{yygotominor.yy328 = yymsp[0].major;}
128166        break;
128167      case 17: /* cmd ::= COMMIT trans_opt */
128168      case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
128169{sqlite3CommitTransaction(pParse);}
128170        break;
128171      case 19: /* cmd ::= ROLLBACK trans_opt */
128172{sqlite3RollbackTransaction(pParse);}
128173        break;
128174      case 22: /* cmd ::= SAVEPOINT nm */
128175{
128176  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
128177}
128178        break;
128179      case 23: /* cmd ::= RELEASE savepoint_opt nm */
128180{
128181  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
128182}
128183        break;
128184      case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
128185{
128186  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
128187}
128188        break;
128189      case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
128190{
128191   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
128192}
128193        break;
128194      case 27: /* createkw ::= CREATE */
128195{
128196  pParse->db->lookaside.bEnabled = 0;
128197  yygotominor.yy0 = yymsp[0].minor.yy0;
128198}
128199        break;
128200      case 28: /* ifnotexists ::= */
128201      case 31: /* temp ::= */ yytestcase(yyruleno==31);
128202      case 68: /* autoinc ::= */ yytestcase(yyruleno==68);
128203      case 81: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==81);
128204      case 83: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==83);
128205      case 85: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==85);
128206      case 97: /* defer_subclause_opt ::= */ yytestcase(yyruleno==97);
128207      case 108: /* ifexists ::= */ yytestcase(yyruleno==108);
128208      case 219: /* between_op ::= BETWEEN */ yytestcase(yyruleno==219);
128209      case 222: /* in_op ::= IN */ yytestcase(yyruleno==222);
128210      case 247: /* collate ::= */ yytestcase(yyruleno==247);
128211{yygotominor.yy328 = 0;}
128212        break;
128213      case 29: /* ifnotexists ::= IF NOT EXISTS */
128214      case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
128215      case 69: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==69);
128216      case 84: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==84);
128217      case 107: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==107);
128218      case 220: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==220);
128219      case 223: /* in_op ::= NOT IN */ yytestcase(yyruleno==223);
128220      case 248: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==248);
128221{yygotominor.yy328 = 1;}
128222        break;
128223      case 32: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
128224{
128225  sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy186,0);
128226}
128227        break;
128228      case 33: /* create_table_args ::= AS select */
128229{
128230  sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy3);
128231  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
128232}
128233        break;
128234      case 34: /* table_options ::= */
128235{yygotominor.yy186 = 0;}
128236        break;
128237      case 35: /* table_options ::= WITHOUT nm */
128238{
128239  if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
128240    yygotominor.yy186 = TF_WithoutRowid | TF_NoVisibleRowid;
128241  }else{
128242    yygotominor.yy186 = 0;
128243    sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
128244  }
128245}
128246        break;
128247      case 38: /* column ::= columnid type carglist */
128248{
128249  yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
128250  yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
128251}
128252        break;
128253      case 39: /* columnid ::= nm */
128254{
128255  sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
128256  yygotominor.yy0 = yymsp[0].minor.yy0;
128257  pParse->constraintName.n = 0;
128258}
128259        break;
128260      case 40: /* nm ::= ID|INDEXED */
128261      case 41: /* nm ::= STRING */ yytestcase(yyruleno==41);
128262      case 42: /* nm ::= JOIN_KW */ yytestcase(yyruleno==42);
128263      case 45: /* typetoken ::= typename */ yytestcase(yyruleno==45);
128264      case 48: /* typename ::= ID|STRING */ yytestcase(yyruleno==48);
128265      case 130: /* as ::= AS nm */ yytestcase(yyruleno==130);
128266      case 131: /* as ::= ID|STRING */ yytestcase(yyruleno==131);
128267      case 142: /* dbnm ::= DOT nm */ yytestcase(yyruleno==142);
128268      case 151: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==151);
128269      case 257: /* nmnum ::= plus_num */ yytestcase(yyruleno==257);
128270      case 258: /* nmnum ::= nm */ yytestcase(yyruleno==258);
128271      case 259: /* nmnum ::= ON */ yytestcase(yyruleno==259);
128272      case 260: /* nmnum ::= DELETE */ yytestcase(yyruleno==260);
128273      case 261: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==261);
128274      case 262: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==262);
128275      case 263: /* plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==263);
128276      case 264: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==264);
128277      case 280: /* trnm ::= nm */ yytestcase(yyruleno==280);
128278{yygotominor.yy0 = yymsp[0].minor.yy0;}
128279        break;
128280      case 44: /* type ::= typetoken */
128281{sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
128282        break;
128283      case 46: /* typetoken ::= typename LP signed RP */
128284{
128285  yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
128286  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
128287}
128288        break;
128289      case 47: /* typetoken ::= typename LP signed COMMA signed RP */
128290{
128291  yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
128292  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
128293}
128294        break;
128295      case 49: /* typename ::= typename ID|STRING */
128296{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);}
128297        break;
128298      case 54: /* ccons ::= CONSTRAINT nm */
128299      case 92: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==92);
128300{pParse->constraintName = yymsp[0].minor.yy0;}
128301        break;
128302      case 55: /* ccons ::= DEFAULT term */
128303      case 57: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==57);
128304{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
128305        break;
128306      case 56: /* ccons ::= DEFAULT LP expr RP */
128307{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
128308        break;
128309      case 58: /* ccons ::= DEFAULT MINUS term */
128310{
128311  ExprSpan v;
128312  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
128313  v.zStart = yymsp[-1].minor.yy0.z;
128314  v.zEnd = yymsp[0].minor.yy346.zEnd;
128315  sqlite3AddDefaultValue(pParse,&v);
128316}
128317        break;
128318      case 59: /* ccons ::= DEFAULT ID|INDEXED */
128319{
128320  ExprSpan v;
128321  spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
128322  sqlite3AddDefaultValue(pParse,&v);
128323}
128324        break;
128325      case 61: /* ccons ::= NOT NULL onconf */
128326{sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
128327        break;
128328      case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
128329{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
128330        break;
128331      case 63: /* ccons ::= UNIQUE onconf */
128332{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
128333        break;
128334      case 64: /* ccons ::= CHECK LP expr RP */
128335{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
128336        break;
128337      case 65: /* ccons ::= REFERENCES nm eidlist_opt refargs */
128338{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
128339        break;
128340      case 66: /* ccons ::= defer_subclause */
128341{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
128342        break;
128343      case 67: /* ccons ::= COLLATE ID|STRING */
128344{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
128345        break;
128346      case 70: /* refargs ::= */
128347{ yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
128348        break;
128349      case 71: /* refargs ::= refargs refarg */
128350{ yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
128351        break;
128352      case 72: /* refarg ::= MATCH nm */
128353      case 73: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==73);
128354{ yygotominor.yy429.value = 0;     yygotominor.yy429.mask = 0x000000; }
128355        break;
128356      case 74: /* refarg ::= ON DELETE refact */
128357{ yygotominor.yy429.value = yymsp[0].minor.yy328;     yygotominor.yy429.mask = 0x0000ff; }
128358        break;
128359      case 75: /* refarg ::= ON UPDATE refact */
128360{ yygotominor.yy429.value = yymsp[0].minor.yy328<<8;  yygotominor.yy429.mask = 0x00ff00; }
128361        break;
128362      case 76: /* refact ::= SET NULL */
128363{ yygotominor.yy328 = OE_SetNull;  /* EV: R-33326-45252 */}
128364        break;
128365      case 77: /* refact ::= SET DEFAULT */
128366{ yygotominor.yy328 = OE_SetDflt;  /* EV: R-33326-45252 */}
128367        break;
128368      case 78: /* refact ::= CASCADE */
128369{ yygotominor.yy328 = OE_Cascade;  /* EV: R-33326-45252 */}
128370        break;
128371      case 79: /* refact ::= RESTRICT */
128372{ yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
128373        break;
128374      case 80: /* refact ::= NO ACTION */
128375{ yygotominor.yy328 = OE_None;     /* EV: R-33326-45252 */}
128376        break;
128377      case 82: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
128378      case 98: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==98);
128379      case 100: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==100);
128380      case 103: /* resolvetype ::= raisetype */ yytestcase(yyruleno==103);
128381{yygotominor.yy328 = yymsp[0].minor.yy328;}
128382        break;
128383      case 86: /* conslist_opt ::= */
128384{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
128385        break;
128386      case 87: /* conslist_opt ::= COMMA conslist */
128387{yygotominor.yy0 = yymsp[-1].minor.yy0;}
128388        break;
128389      case 90: /* tconscomma ::= COMMA */
128390{pParse->constraintName.n = 0;}
128391        break;
128392      case 93: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
128393{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
128394        break;
128395      case 94: /* tcons ::= UNIQUE LP sortlist RP onconf */
128396{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
128397        break;
128398      case 95: /* tcons ::= CHECK LP expr RP onconf */
128399{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
128400        break;
128401      case 96: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
128402{
128403    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
128404    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
128405}
128406        break;
128407      case 99: /* onconf ::= */
128408{yygotominor.yy328 = OE_Default;}
128409        break;
128410      case 101: /* orconf ::= */
128411{yygotominor.yy186 = OE_Default;}
128412        break;
128413      case 102: /* orconf ::= OR resolvetype */
128414{yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
128415        break;
128416      case 104: /* resolvetype ::= IGNORE */
128417{yygotominor.yy328 = OE_Ignore;}
128418        break;
128419      case 105: /* resolvetype ::= REPLACE */
128420{yygotominor.yy328 = OE_Replace;}
128421        break;
128422      case 106: /* cmd ::= DROP TABLE ifexists fullname */
128423{
128424  sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
128425}
128426        break;
128427      case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
128428{
128429  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);
128430}
128431        break;
128432      case 110: /* cmd ::= DROP VIEW ifexists fullname */
128433{
128434  sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
128435}
128436        break;
128437      case 111: /* cmd ::= select */
128438{
128439  SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
128440  sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
128441  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
128442}
128443        break;
128444      case 112: /* select ::= with selectnowith */
128445{
128446  Select *p = yymsp[0].minor.yy3;
128447  if( p ){
128448    p->pWith = yymsp[-1].minor.yy59;
128449    parserDoubleLinkSelect(pParse, p);
128450  }else{
128451    sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy59);
128452  }
128453  yygotominor.yy3 = p;
128454}
128455        break;
128456      case 113: /* selectnowith ::= oneselect */
128457      case 119: /* oneselect ::= values */ yytestcase(yyruleno==119);
128458{yygotominor.yy3 = yymsp[0].minor.yy3;}
128459        break;
128460      case 114: /* selectnowith ::= selectnowith multiselect_op oneselect */
128461{
128462  Select *pRhs = yymsp[0].minor.yy3;
128463  Select *pLhs = yymsp[-2].minor.yy3;
128464  if( pRhs && pRhs->pPrior ){
128465    SrcList *pFrom;
128466    Token x;
128467    x.n = 0;
128468    parserDoubleLinkSelect(pParse, pRhs);
128469    pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
128470    pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
128471  }
128472  if( pRhs ){
128473    pRhs->op = (u8)yymsp[-1].minor.yy328;
128474    pRhs->pPrior = pLhs;
128475    if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
128476    pRhs->selFlags &= ~SF_MultiValue;
128477    if( yymsp[-1].minor.yy328!=TK_ALL ) pParse->hasCompound = 1;
128478  }else{
128479    sqlite3SelectDelete(pParse->db, pLhs);
128480  }
128481  yygotominor.yy3 = pRhs;
128482}
128483        break;
128484      case 116: /* multiselect_op ::= UNION ALL */
128485{yygotominor.yy328 = TK_ALL;}
128486        break;
128487      case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
128488{
128489  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);
128490#if SELECTTRACE_ENABLED
128491  /* Populate the Select.zSelName[] string that is used to help with
128492  ** query planner debugging, to differentiate between multiple Select
128493  ** objects in a complex query.
128494  **
128495  ** If the SELECT keyword is immediately followed by a C-style comment
128496  ** then extract the first few alphanumeric characters from within that
128497  ** comment to be the zSelName value.  Otherwise, the label is #N where
128498  ** is an integer that is incremented with each SELECT statement seen.
128499  */
128500  if( yygotominor.yy3!=0 ){
128501    const char *z = yymsp[-8].minor.yy0.z+6;
128502    int i;
128503    sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "#%d",
128504                     ++pParse->nSelect);
128505    while( z[0]==' ' ) z++;
128506    if( z[0]=='/' && z[1]=='*' ){
128507      z += 2;
128508      while( z[0]==' ' ) z++;
128509      for(i=0; sqlite3Isalnum(z[i]); i++){}
128510      sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "%.*s", i, z);
128511    }
128512  }
128513#endif /* SELECTRACE_ENABLED */
128514}
128515        break;
128516      case 120: /* values ::= VALUES LP nexprlist RP */
128517{
128518  yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
128519}
128520        break;
128521      case 121: /* values ::= values COMMA LP exprlist RP */
128522{
128523  Select *pRight, *pLeft = yymsp[-4].minor.yy3;
128524  pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
128525  if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
128526  if( pRight ){
128527    pRight->op = TK_ALL;
128528    pLeft = yymsp[-4].minor.yy3;
128529    pRight->pPrior = pLeft;
128530    yygotominor.yy3 = pRight;
128531  }else{
128532    yygotominor.yy3 = pLeft;
128533  }
128534}
128535        break;
128536      case 122: /* distinct ::= DISTINCT */
128537{yygotominor.yy381 = SF_Distinct;}
128538        break;
128539      case 123: /* distinct ::= ALL */
128540{yygotominor.yy381 = SF_All;}
128541        break;
128542      case 124: /* distinct ::= */
128543{yygotominor.yy381 = 0;}
128544        break;
128545      case 125: /* sclp ::= selcollist COMMA */
128546      case 244: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==244);
128547{yygotominor.yy14 = yymsp[-1].minor.yy14;}
128548        break;
128549      case 126: /* sclp ::= */
128550      case 155: /* orderby_opt ::= */ yytestcase(yyruleno==155);
128551      case 162: /* groupby_opt ::= */ yytestcase(yyruleno==162);
128552      case 237: /* exprlist ::= */ yytestcase(yyruleno==237);
128553      case 243: /* eidlist_opt ::= */ yytestcase(yyruleno==243);
128554{yygotominor.yy14 = 0;}
128555        break;
128556      case 127: /* selcollist ::= sclp expr as */
128557{
128558   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
128559   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
128560   sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
128561}
128562        break;
128563      case 128: /* selcollist ::= sclp STAR */
128564{
128565  Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
128566  yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
128567}
128568        break;
128569      case 129: /* selcollist ::= sclp nm DOT STAR */
128570{
128571  Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
128572  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
128573  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
128574  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
128575}
128576        break;
128577      case 132: /* as ::= */
128578{yygotominor.yy0.n = 0;}
128579        break;
128580      case 133: /* from ::= */
128581{yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
128582        break;
128583      case 134: /* from ::= FROM seltablist */
128584{
128585  yygotominor.yy65 = yymsp[0].minor.yy65;
128586  sqlite3SrcListShiftJoinType(yygotominor.yy65);
128587}
128588        break;
128589      case 135: /* stl_prefix ::= seltablist joinop */
128590{
128591   yygotominor.yy65 = yymsp[-1].minor.yy65;
128592   if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy328;
128593}
128594        break;
128595      case 136: /* stl_prefix ::= */
128596{yygotominor.yy65 = 0;}
128597        break;
128598      case 137: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
128599{
128600  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);
128601  sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
128602}
128603        break;
128604      case 138: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
128605{
128606  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);
128607  sqlite3SrcListFuncArgs(pParse, yygotominor.yy65, yymsp[-4].minor.yy14);
128608}
128609        break;
128610      case 139: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
128611{
128612    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);
128613  }
128614        break;
128615      case 140: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
128616{
128617    if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
128618      yygotominor.yy65 = yymsp[-4].minor.yy65;
128619    }else if( yymsp[-4].minor.yy65->nSrc==1 ){
128620      yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
128621      if( yygotominor.yy65 ){
128622        struct SrcList_item *pNew = &yygotominor.yy65->a[yygotominor.yy65->nSrc-1];
128623        struct SrcList_item *pOld = yymsp[-4].minor.yy65->a;
128624        pNew->zName = pOld->zName;
128625        pNew->zDatabase = pOld->zDatabase;
128626        pNew->pSelect = pOld->pSelect;
128627        pOld->zName = pOld->zDatabase = 0;
128628        pOld->pSelect = 0;
128629      }
128630      sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy65);
128631    }else{
128632      Select *pSubquery;
128633      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
128634      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,SF_NestedFrom,0,0);
128635      yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
128636    }
128637  }
128638        break;
128639      case 141: /* dbnm ::= */
128640      case 150: /* indexed_opt ::= */ yytestcase(yyruleno==150);
128641{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
128642        break;
128643      case 143: /* fullname ::= nm dbnm */
128644{yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
128645        break;
128646      case 144: /* joinop ::= COMMA|JOIN */
128647{ yygotominor.yy328 = JT_INNER; }
128648        break;
128649      case 145: /* joinop ::= JOIN_KW JOIN */
128650{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
128651        break;
128652      case 146: /* joinop ::= JOIN_KW nm JOIN */
128653{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
128654        break;
128655      case 147: /* joinop ::= JOIN_KW nm nm JOIN */
128656{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
128657        break;
128658      case 148: /* on_opt ::= ON expr */
128659      case 165: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==165);
128660      case 172: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==172);
128661      case 232: /* case_else ::= ELSE expr */ yytestcase(yyruleno==232);
128662      case 234: /* case_operand ::= expr */ yytestcase(yyruleno==234);
128663{yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
128664        break;
128665      case 149: /* on_opt ::= */
128666      case 164: /* having_opt ::= */ yytestcase(yyruleno==164);
128667      case 171: /* where_opt ::= */ yytestcase(yyruleno==171);
128668      case 233: /* case_else ::= */ yytestcase(yyruleno==233);
128669      case 235: /* case_operand ::= */ yytestcase(yyruleno==235);
128670{yygotominor.yy132 = 0;}
128671        break;
128672      case 152: /* indexed_opt ::= NOT INDEXED */
128673{yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
128674        break;
128675      case 153: /* using_opt ::= USING LP idlist RP */
128676      case 181: /* idlist_opt ::= LP idlist RP */ yytestcase(yyruleno==181);
128677{yygotominor.yy408 = yymsp[-1].minor.yy408;}
128678        break;
128679      case 154: /* using_opt ::= */
128680      case 180: /* idlist_opt ::= */ yytestcase(yyruleno==180);
128681{yygotominor.yy408 = 0;}
128682        break;
128683      case 156: /* orderby_opt ::= ORDER BY sortlist */
128684      case 163: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==163);
128685      case 236: /* exprlist ::= nexprlist */ yytestcase(yyruleno==236);
128686{yygotominor.yy14 = yymsp[0].minor.yy14;}
128687        break;
128688      case 157: /* sortlist ::= sortlist COMMA expr sortorder */
128689{
128690  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy346.pExpr);
128691  sqlite3ExprListSetSortOrder(yygotominor.yy14,yymsp[0].minor.yy328);
128692}
128693        break;
128694      case 158: /* sortlist ::= expr sortorder */
128695{
128696  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy346.pExpr);
128697  sqlite3ExprListSetSortOrder(yygotominor.yy14,yymsp[0].minor.yy328);
128698}
128699        break;
128700      case 159: /* sortorder ::= ASC */
128701{yygotominor.yy328 = SQLITE_SO_ASC;}
128702        break;
128703      case 160: /* sortorder ::= DESC */
128704{yygotominor.yy328 = SQLITE_SO_DESC;}
128705        break;
128706      case 161: /* sortorder ::= */
128707{yygotominor.yy328 = SQLITE_SO_UNDEFINED;}
128708        break;
128709      case 166: /* limit_opt ::= */
128710{yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
128711        break;
128712      case 167: /* limit_opt ::= LIMIT expr */
128713{yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
128714        break;
128715      case 168: /* limit_opt ::= LIMIT expr OFFSET expr */
128716{yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
128717        break;
128718      case 169: /* limit_opt ::= LIMIT expr COMMA expr */
128719{yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
128720        break;
128721      case 170: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
128722{
128723  sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
128724  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
128725  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
128726}
128727        break;
128728      case 173: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
128729{
128730  sqlite3WithPush(pParse, yymsp[-7].minor.yy59, 1);
128731  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
128732  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
128733  sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
128734}
128735        break;
128736      case 174: /* setlist ::= setlist COMMA nm EQ expr */
128737{
128738  yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
128739  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
128740}
128741        break;
128742      case 175: /* setlist ::= nm EQ expr */
128743{
128744  yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
128745  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
128746}
128747        break;
128748      case 176: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */
128749{
128750  sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
128751  sqlite3Insert(pParse, yymsp[-2].minor.yy65, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);
128752}
128753        break;
128754      case 177: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
128755{
128756  sqlite3WithPush(pParse, yymsp[-6].minor.yy59, 1);
128757  sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);
128758}
128759        break;
128760      case 178: /* insert_cmd ::= INSERT orconf */
128761{yygotominor.yy186 = yymsp[0].minor.yy186;}
128762        break;
128763      case 179: /* insert_cmd ::= REPLACE */
128764{yygotominor.yy186 = OE_Replace;}
128765        break;
128766      case 182: /* idlist ::= idlist COMMA nm */
128767{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
128768        break;
128769      case 183: /* idlist ::= nm */
128770{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
128771        break;
128772      case 184: /* expr ::= term */
128773{yygotominor.yy346 = yymsp[0].minor.yy346;}
128774        break;
128775      case 185: /* expr ::= LP expr RP */
128776{yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
128777        break;
128778      case 186: /* term ::= NULL */
128779      case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
128780      case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
128781{spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
128782        break;
128783      case 187: /* expr ::= ID|INDEXED */
128784      case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
128785{spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
128786        break;
128787      case 189: /* expr ::= nm DOT nm */
128788{
128789  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
128790  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
128791  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
128792  spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
128793}
128794        break;
128795      case 190: /* expr ::= nm DOT nm DOT nm */
128796{
128797  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
128798  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
128799  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
128800  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
128801  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
128802  spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
128803}
128804        break;
128805      case 193: /* expr ::= VARIABLE */
128806{
128807  if( yymsp[0].minor.yy0.n>=2 && yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1]) ){
128808    /* When doing a nested parse, one can include terms in an expression
128809    ** that look like this:   #1 #2 ...  These terms refer to registers
128810    ** in the virtual machine.  #N is the N-th register. */
128811    if( pParse->nested==0 ){
128812      sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
128813      yygotominor.yy346.pExpr = 0;
128814    }else{
128815      yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
128816      if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
128817    }
128818  }else{
128819    spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
128820    sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
128821  }
128822  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
128823}
128824        break;
128825      case 194: /* expr ::= expr COLLATE ID|STRING */
128826{
128827  yygotominor.yy346.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0, 1);
128828  yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
128829  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
128830}
128831        break;
128832      case 195: /* expr ::= CAST LP expr AS typetoken RP */
128833{
128834  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
128835  spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
128836}
128837        break;
128838      case 196: /* expr ::= ID|INDEXED LP distinct exprlist RP */
128839{
128840  if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
128841    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
128842  }
128843  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
128844  spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
128845  if( yymsp[-2].minor.yy381==SF_Distinct && yygotominor.yy346.pExpr ){
128846    yygotominor.yy346.pExpr->flags |= EP_Distinct;
128847  }
128848}
128849        break;
128850      case 197: /* expr ::= ID|INDEXED LP STAR RP */
128851{
128852  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
128853  spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
128854}
128855        break;
128856      case 198: /* term ::= CTIME_KW */
128857{
128858  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
128859  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
128860}
128861        break;
128862      case 199: /* expr ::= expr AND expr */
128863      case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
128864      case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
128865      case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
128866      case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
128867      case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
128868      case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
128869      case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
128870{spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
128871        break;
128872      case 207: /* likeop ::= LIKE_KW|MATCH */
128873{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 0;}
128874        break;
128875      case 208: /* likeop ::= NOT LIKE_KW|MATCH */
128876{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 1;}
128877        break;
128878      case 209: /* expr ::= expr likeop expr */
128879{
128880  ExprList *pList;
128881  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy346.pExpr);
128882  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy346.pExpr);
128883  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy96.eOperator);
128884  if( yymsp[-1].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
128885  yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
128886  yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
128887  if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
128888}
128889        break;
128890      case 210: /* expr ::= expr likeop expr ESCAPE expr */
128891{
128892  ExprList *pList;
128893  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
128894  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy346.pExpr);
128895  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
128896  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy96.eOperator);
128897  if( yymsp[-3].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
128898  yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
128899  yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
128900  if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
128901}
128902        break;
128903      case 211: /* expr ::= expr ISNULL|NOTNULL */
128904{spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
128905        break;
128906      case 212: /* expr ::= expr NOT NULL */
128907{spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
128908        break;
128909      case 213: /* expr ::= expr IS expr */
128910{
128911  spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
128912  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
128913}
128914        break;
128915      case 214: /* expr ::= expr IS NOT expr */
128916{
128917  spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
128918  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
128919}
128920        break;
128921      case 215: /* expr ::= NOT expr */
128922      case 216: /* expr ::= BITNOT expr */ yytestcase(yyruleno==216);
128923{spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
128924        break;
128925      case 217: /* expr ::= MINUS expr */
128926{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
128927        break;
128928      case 218: /* expr ::= PLUS expr */
128929{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
128930        break;
128931      case 221: /* expr ::= expr between_op expr AND expr */
128932{
128933  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
128934  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
128935  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
128936  if( yygotominor.yy346.pExpr ){
128937    yygotominor.yy346.pExpr->x.pList = pList;
128938  }else{
128939    sqlite3ExprListDelete(pParse->db, pList);
128940  }
128941  if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
128942  yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
128943  yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
128944}
128945        break;
128946      case 224: /* expr ::= expr in_op LP exprlist RP */
128947{
128948    if( yymsp[-1].minor.yy14==0 ){
128949      /* Expressions of the form
128950      **
128951      **      expr1 IN ()
128952      **      expr1 NOT IN ()
128953      **
128954      ** simplify to constants 0 (false) and 1 (true), respectively,
128955      ** regardless of the value of expr1.
128956      */
128957      yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy328]);
128958      sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy346.pExpr);
128959    }else if( yymsp[-1].minor.yy14->nExpr==1 ){
128960      /* Expressions of the form:
128961      **
128962      **      expr1 IN (?1)
128963      **      expr1 NOT IN (?2)
128964      **
128965      ** with exactly one value on the RHS can be simplified to something
128966      ** like this:
128967      **
128968      **      expr1 == ?1
128969      **      expr1 <> ?2
128970      **
128971      ** But, the RHS of the == or <> is marked with the EP_Generic flag
128972      ** so that it may not contribute to the computation of comparison
128973      ** affinity or the collating sequence to use for comparison.  Otherwise,
128974      ** the semantics would be subtly different from IN or NOT IN.
128975      */
128976      Expr *pRHS = yymsp[-1].minor.yy14->a[0].pExpr;
128977      yymsp[-1].minor.yy14->a[0].pExpr = 0;
128978      sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
128979      /* pRHS cannot be NULL because a malloc error would have been detected
128980      ** before now and control would have never reached this point */
128981      if( ALWAYS(pRHS) ){
128982        pRHS->flags &= ~EP_Collate;
128983        pRHS->flags |= EP_Generic;
128984      }
128985      yygotominor.yy346.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy328 ? TK_NE : TK_EQ, yymsp[-4].minor.yy346.pExpr, pRHS, 0);
128986    }else{
128987      yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
128988      if( yygotominor.yy346.pExpr ){
128989        yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
128990        sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
128991      }else{
128992        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
128993      }
128994      if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
128995    }
128996    yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
128997    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
128998  }
128999        break;
129000      case 225: /* expr ::= LP select RP */
129001{
129002    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
129003    if( yygotominor.yy346.pExpr ){
129004      yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
129005      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
129006      sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
129007    }else{
129008      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
129009    }
129010    yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
129011    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
129012  }
129013        break;
129014      case 226: /* expr ::= expr in_op LP select RP */
129015{
129016    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
129017    if( yygotominor.yy346.pExpr ){
129018      yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
129019      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
129020      sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
129021    }else{
129022      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
129023    }
129024    if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
129025    yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
129026    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
129027  }
129028        break;
129029      case 227: /* expr ::= expr in_op nm dbnm */
129030{
129031    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
129032    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
129033    if( yygotominor.yy346.pExpr ){
129034      yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
129035      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
129036      sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
129037    }else{
129038      sqlite3SrcListDelete(pParse->db, pSrc);
129039    }
129040    if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
129041    yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
129042    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];
129043  }
129044        break;
129045      case 228: /* expr ::= EXISTS LP select RP */
129046{
129047    Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
129048    if( p ){
129049      p->x.pSelect = yymsp[-1].minor.yy3;
129050      ExprSetProperty(p, EP_xIsSelect|EP_Subquery);
129051      sqlite3ExprSetHeightAndFlags(pParse, p);
129052    }else{
129053      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
129054    }
129055    yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
129056    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
129057  }
129058        break;
129059      case 229: /* expr ::= CASE case_operand case_exprlist case_else END */
129060{
129061  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, 0, 0);
129062  if( yygotominor.yy346.pExpr ){
129063    yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy132 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[-1].minor.yy132) : yymsp[-2].minor.yy14;
129064    sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
129065  }else{
129066    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
129067    sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy132);
129068  }
129069  yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
129070  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
129071}
129072        break;
129073      case 230: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
129074{
129075  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
129076  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
129077}
129078        break;
129079      case 231: /* case_exprlist ::= WHEN expr THEN expr */
129080{
129081  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
129082  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
129083}
129084        break;
129085      case 238: /* nexprlist ::= nexprlist COMMA expr */
129086{yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
129087        break;
129088      case 239: /* nexprlist ::= expr */
129089{yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
129090        break;
129091      case 240: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
129092{
129093  sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
129094                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy14, yymsp[-10].minor.yy328,
129095                      &yymsp[-11].minor.yy0, yymsp[0].minor.yy132, SQLITE_SO_ASC, yymsp[-8].minor.yy328);
129096}
129097        break;
129098      case 241: /* uniqueflag ::= UNIQUE */
129099      case 292: /* raisetype ::= ABORT */ yytestcase(yyruleno==292);
129100{yygotominor.yy328 = OE_Abort;}
129101        break;
129102      case 242: /* uniqueflag ::= */
129103{yygotominor.yy328 = OE_None;}
129104        break;
129105      case 245: /* eidlist ::= eidlist COMMA nm collate sortorder */
129106{
129107  yygotominor.yy14 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy14, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy328, yymsp[0].minor.yy328);
129108}
129109        break;
129110      case 246: /* eidlist ::= nm collate sortorder */
129111{
129112  yygotominor.yy14 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy328, yymsp[0].minor.yy328);
129113}
129114        break;
129115      case 249: /* cmd ::= DROP INDEX ifexists fullname */
129116{sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
129117        break;
129118      case 250: /* cmd ::= VACUUM */
129119      case 251: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==251);
129120{sqlite3Vacuum(pParse);}
129121        break;
129122      case 252: /* cmd ::= PRAGMA nm dbnm */
129123{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
129124        break;
129125      case 253: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
129126{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
129127        break;
129128      case 254: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
129129{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
129130        break;
129131      case 255: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
129132{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
129133        break;
129134      case 256: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
129135{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
129136        break;
129137      case 265: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
129138{
129139  Token all;
129140  all.z = yymsp[-3].minor.yy0.z;
129141  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
129142  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
129143}
129144        break;
129145      case 266: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
129146{
129147  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);
129148  yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
129149}
129150        break;
129151      case 267: /* trigger_time ::= BEFORE */
129152      case 270: /* trigger_time ::= */ yytestcase(yyruleno==270);
129153{ yygotominor.yy328 = TK_BEFORE; }
129154        break;
129155      case 268: /* trigger_time ::= AFTER */
129156{ yygotominor.yy328 = TK_AFTER;  }
129157        break;
129158      case 269: /* trigger_time ::= INSTEAD OF */
129159{ yygotominor.yy328 = TK_INSTEAD;}
129160        break;
129161      case 271: /* trigger_event ::= DELETE|INSERT */
129162      case 272: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==272);
129163{yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
129164        break;
129165      case 273: /* trigger_event ::= UPDATE OF idlist */
129166{yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
129167        break;
129168      case 276: /* when_clause ::= */
129169      case 297: /* key_opt ::= */ yytestcase(yyruleno==297);
129170{ yygotominor.yy132 = 0; }
129171        break;
129172      case 277: /* when_clause ::= WHEN expr */
129173      case 298: /* key_opt ::= KEY expr */ yytestcase(yyruleno==298);
129174{ yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
129175        break;
129176      case 278: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
129177{
129178  assert( yymsp[-2].minor.yy473!=0 );
129179  yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
129180  yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
129181  yygotominor.yy473 = yymsp[-2].minor.yy473;
129182}
129183        break;
129184      case 279: /* trigger_cmd_list ::= trigger_cmd SEMI */
129185{
129186  assert( yymsp[-1].minor.yy473!=0 );
129187  yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
129188  yygotominor.yy473 = yymsp[-1].minor.yy473;
129189}
129190        break;
129191      case 281: /* trnm ::= nm DOT nm */
129192{
129193  yygotominor.yy0 = yymsp[0].minor.yy0;
129194  sqlite3ErrorMsg(pParse,
129195        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
129196        "statements within triggers");
129197}
129198        break;
129199      case 283: /* tridxby ::= INDEXED BY nm */
129200{
129201  sqlite3ErrorMsg(pParse,
129202        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
129203        "within triggers");
129204}
129205        break;
129206      case 284: /* tridxby ::= NOT INDEXED */
129207{
129208  sqlite3ErrorMsg(pParse,
129209        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
129210        "within triggers");
129211}
129212        break;
129213      case 285: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
129214{ yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
129215        break;
129216      case 286: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */
129217{yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
129218        break;
129219      case 287: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
129220{yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
129221        break;
129222      case 288: /* trigger_cmd ::= select */
129223{yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
129224        break;
129225      case 289: /* expr ::= RAISE LP IGNORE RP */
129226{
129227  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
129228  if( yygotominor.yy346.pExpr ){
129229    yygotominor.yy346.pExpr->affinity = OE_Ignore;
129230  }
129231  yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
129232  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
129233}
129234        break;
129235      case 290: /* expr ::= RAISE LP raisetype COMMA nm RP */
129236{
129237  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
129238  if( yygotominor.yy346.pExpr ) {
129239    yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
129240  }
129241  yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
129242  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
129243}
129244        break;
129245      case 291: /* raisetype ::= ROLLBACK */
129246{yygotominor.yy328 = OE_Rollback;}
129247        break;
129248      case 293: /* raisetype ::= FAIL */
129249{yygotominor.yy328 = OE_Fail;}
129250        break;
129251      case 294: /* cmd ::= DROP TRIGGER ifexists fullname */
129252{
129253  sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
129254}
129255        break;
129256      case 295: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
129257{
129258  sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
129259}
129260        break;
129261      case 296: /* cmd ::= DETACH database_kw_opt expr */
129262{
129263  sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
129264}
129265        break;
129266      case 301: /* cmd ::= REINDEX */
129267{sqlite3Reindex(pParse, 0, 0);}
129268        break;
129269      case 302: /* cmd ::= REINDEX nm dbnm */
129270{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
129271        break;
129272      case 303: /* cmd ::= ANALYZE */
129273{sqlite3Analyze(pParse, 0, 0);}
129274        break;
129275      case 304: /* cmd ::= ANALYZE nm dbnm */
129276{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
129277        break;
129278      case 305: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
129279{
129280  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
129281}
129282        break;
129283      case 306: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
129284{
129285  sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
129286}
129287        break;
129288      case 307: /* add_column_fullname ::= fullname */
129289{
129290  pParse->db->lookaside.bEnabled = 0;
129291  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
129292}
129293        break;
129294      case 310: /* cmd ::= create_vtab */
129295{sqlite3VtabFinishParse(pParse,0);}
129296        break;
129297      case 311: /* cmd ::= create_vtab LP vtabarglist RP */
129298{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
129299        break;
129300      case 312: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
129301{
129302    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy328);
129303}
129304        break;
129305      case 315: /* vtabarg ::= */
129306{sqlite3VtabArgInit(pParse);}
129307        break;
129308      case 317: /* vtabargtoken ::= ANY */
129309      case 318: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==318);
129310      case 319: /* lp ::= LP */ yytestcase(yyruleno==319);
129311{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
129312        break;
129313      case 323: /* with ::= */
129314{yygotominor.yy59 = 0;}
129315        break;
129316      case 324: /* with ::= WITH wqlist */
129317      case 325: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==325);
129318{ yygotominor.yy59 = yymsp[0].minor.yy59; }
129319        break;
129320      case 326: /* wqlist ::= nm eidlist_opt AS LP select RP */
129321{
129322  yygotominor.yy59 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
129323}
129324        break;
129325      case 327: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
129326{
129327  yygotominor.yy59 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy59, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
129328}
129329        break;
129330      default:
129331      /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
129332      /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
129333      /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
129334      /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
129335      /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
129336      /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
129337      /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
129338      /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
129339      /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
129340      /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
129341      /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
129342      /* (36) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==36);
129343      /* (37) columnlist ::= column */ yytestcase(yyruleno==37);
129344      /* (43) type ::= */ yytestcase(yyruleno==43);
129345      /* (50) signed ::= plus_num */ yytestcase(yyruleno==50);
129346      /* (51) signed ::= minus_num */ yytestcase(yyruleno==51);
129347      /* (52) carglist ::= carglist ccons */ yytestcase(yyruleno==52);
129348      /* (53) carglist ::= */ yytestcase(yyruleno==53);
129349      /* (60) ccons ::= NULL onconf */ yytestcase(yyruleno==60);
129350      /* (88) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==88);
129351      /* (89) conslist ::= tcons */ yytestcase(yyruleno==89);
129352      /* (91) tconscomma ::= */ yytestcase(yyruleno==91);
129353      /* (274) foreach_clause ::= */ yytestcase(yyruleno==274);
129354      /* (275) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==275);
129355      /* (282) tridxby ::= */ yytestcase(yyruleno==282);
129356      /* (299) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==299);
129357      /* (300) database_kw_opt ::= */ yytestcase(yyruleno==300);
129358      /* (308) kwcolumn_opt ::= */ yytestcase(yyruleno==308);
129359      /* (309) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==309);
129360      /* (313) vtabarglist ::= vtabarg */ yytestcase(yyruleno==313);
129361      /* (314) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==314);
129362      /* (316) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==316);
129363      /* (320) anylist ::= */ yytestcase(yyruleno==320);
129364      /* (321) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==321);
129365      /* (322) anylist ::= anylist ANY */ yytestcase(yyruleno==322);
129366        break;
129367  };
129368  assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
129369  yygoto = yyRuleInfo[yyruleno].lhs;
129370  yysize = yyRuleInfo[yyruleno].nrhs;
129371  yypParser->yyidx -= yysize;
129372  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
129373  if( yyact <= YY_MAX_SHIFTREDUCE ){
129374    if( yyact>YY_MAX_SHIFT ) yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
129375    /* If the reduce action popped at least
129376    ** one element off the stack, then we can push the new element back
129377    ** onto the stack here, and skip the stack overflow test in yy_shift().
129378    ** That gives a significant speed improvement. */
129379    if( yysize ){
129380      yypParser->yyidx++;
129381      yymsp -= yysize-1;
129382      yymsp->stateno = (YYACTIONTYPE)yyact;
129383      yymsp->major = (YYCODETYPE)yygoto;
129384      yymsp->minor = yygotominor;
129385      yyTraceShift(yypParser, yyact);
129386    }else{
129387      yy_shift(yypParser,yyact,yygoto,&yygotominor);
129388    }
129389  }else{
129390    assert( yyact == YY_ACCEPT_ACTION );
129391    yy_accept(yypParser);
129392  }
129393}
129394
129395/*
129396** The following code executes when the parse fails
129397*/
129398#ifndef YYNOERRORRECOVERY
129399static void yy_parse_failed(
129400  yyParser *yypParser           /* The parser */
129401){
129402  sqlite3ParserARG_FETCH;
129403#ifndef NDEBUG
129404  if( yyTraceFILE ){
129405    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
129406  }
129407#endif
129408  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
129409  /* Here code is inserted which will be executed whenever the
129410  ** parser fails */
129411  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
129412}
129413#endif /* YYNOERRORRECOVERY */
129414
129415/*
129416** The following code executes when a syntax error first occurs.
129417*/
129418static void yy_syntax_error(
129419  yyParser *yypParser,           /* The parser */
129420  int yymajor,                   /* The major type of the error token */
129421  YYMINORTYPE yyminor            /* The minor type of the error token */
129422){
129423  sqlite3ParserARG_FETCH;
129424#define TOKEN (yyminor.yy0)
129425
129426  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
129427  assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
129428  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
129429  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
129430}
129431
129432/*
129433** The following is executed when the parser accepts
129434*/
129435static void yy_accept(
129436  yyParser *yypParser           /* The parser */
129437){
129438  sqlite3ParserARG_FETCH;
129439#ifndef NDEBUG
129440  if( yyTraceFILE ){
129441    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
129442  }
129443#endif
129444  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
129445  /* Here code is inserted which will be executed whenever the
129446  ** parser accepts */
129447  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
129448}
129449
129450/* The main parser program.
129451** The first argument is a pointer to a structure obtained from
129452** "sqlite3ParserAlloc" which describes the current state of the parser.
129453** The second argument is the major token number.  The third is
129454** the minor token.  The fourth optional argument is whatever the
129455** user wants (and specified in the grammar) and is available for
129456** use by the action routines.
129457**
129458** Inputs:
129459** <ul>
129460** <li> A pointer to the parser (an opaque structure.)
129461** <li> The major token number.
129462** <li> The minor token number.
129463** <li> An option argument of a grammar-specified type.
129464** </ul>
129465**
129466** Outputs:
129467** None.
129468*/
129469SQLITE_PRIVATE void sqlite3Parser(
129470  void *yyp,                   /* The parser */
129471  int yymajor,                 /* The major token code number */
129472  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
129473  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
129474){
129475  YYMINORTYPE yyminorunion;
129476  int yyact;            /* The parser action. */
129477#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
129478  int yyendofinput;     /* True if we are at the end of input */
129479#endif
129480#ifdef YYERRORSYMBOL
129481  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
129482#endif
129483  yyParser *yypParser;  /* The parser */
129484
129485  /* (re)initialize the parser, if necessary */
129486  yypParser = (yyParser*)yyp;
129487  if( yypParser->yyidx<0 ){
129488#if YYSTACKDEPTH<=0
129489    if( yypParser->yystksz <=0 ){
129490      /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
129491      yyminorunion = yyzerominor;
129492      yyStackOverflow(yypParser, &yyminorunion);
129493      return;
129494    }
129495#endif
129496    yypParser->yyidx = 0;
129497    yypParser->yyerrcnt = -1;
129498    yypParser->yystack[0].stateno = 0;
129499    yypParser->yystack[0].major = 0;
129500  }
129501  yyminorunion.yy0 = yyminor;
129502#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
129503  yyendofinput = (yymajor==0);
129504#endif
129505  sqlite3ParserARG_STORE;
129506
129507#ifndef NDEBUG
129508  if( yyTraceFILE ){
129509    fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
129510  }
129511#endif
129512
129513  do{
129514    yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
129515    if( yyact <= YY_MAX_SHIFTREDUCE ){
129516      if( yyact > YY_MAX_SHIFT ) yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
129517      yy_shift(yypParser,yyact,yymajor,&yyminorunion);
129518      yypParser->yyerrcnt--;
129519      yymajor = YYNOCODE;
129520    }else if( yyact <= YY_MAX_REDUCE ){
129521      yy_reduce(yypParser,yyact-YY_MIN_REDUCE);
129522    }else{
129523      assert( yyact == YY_ERROR_ACTION );
129524#ifdef YYERRORSYMBOL
129525      int yymx;
129526#endif
129527#ifndef NDEBUG
129528      if( yyTraceFILE ){
129529        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
129530      }
129531#endif
129532#ifdef YYERRORSYMBOL
129533      /* A syntax error has occurred.
129534      ** The response to an error depends upon whether or not the
129535      ** grammar defines an error token "ERROR".
129536      **
129537      ** This is what we do if the grammar does define ERROR:
129538      **
129539      **  * Call the %syntax_error function.
129540      **
129541      **  * Begin popping the stack until we enter a state where
129542      **    it is legal to shift the error symbol, then shift
129543      **    the error symbol.
129544      **
129545      **  * Set the error count to three.
129546      **
129547      **  * Begin accepting and shifting new tokens.  No new error
129548      **    processing will occur until three tokens have been
129549      **    shifted successfully.
129550      **
129551      */
129552      if( yypParser->yyerrcnt<0 ){
129553        yy_syntax_error(yypParser,yymajor,yyminorunion);
129554      }
129555      yymx = yypParser->yystack[yypParser->yyidx].major;
129556      if( yymx==YYERRORSYMBOL || yyerrorhit ){
129557#ifndef NDEBUG
129558        if( yyTraceFILE ){
129559          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
129560             yyTracePrompt,yyTokenName[yymajor]);
129561        }
129562#endif
129563        yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
129564        yymajor = YYNOCODE;
129565      }else{
129566         while(
129567          yypParser->yyidx >= 0 &&
129568          yymx != YYERRORSYMBOL &&
129569          (yyact = yy_find_reduce_action(
129570                        yypParser->yystack[yypParser->yyidx].stateno,
129571                        YYERRORSYMBOL)) >= YY_MIN_REDUCE
129572        ){
129573          yy_pop_parser_stack(yypParser);
129574        }
129575        if( yypParser->yyidx < 0 || yymajor==0 ){
129576          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
129577          yy_parse_failed(yypParser);
129578          yymajor = YYNOCODE;
129579        }else if( yymx!=YYERRORSYMBOL ){
129580          YYMINORTYPE u2;
129581          u2.YYERRSYMDT = 0;
129582          yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
129583        }
129584      }
129585      yypParser->yyerrcnt = 3;
129586      yyerrorhit = 1;
129587#elif defined(YYNOERRORRECOVERY)
129588      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
129589      ** do any kind of error recovery.  Instead, simply invoke the syntax
129590      ** error routine and continue going as if nothing had happened.
129591      **
129592      ** Applications can set this macro (for example inside %include) if
129593      ** they intend to abandon the parse upon the first syntax error seen.
129594      */
129595      yy_syntax_error(yypParser,yymajor,yyminorunion);
129596      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
129597      yymajor = YYNOCODE;
129598
129599#else  /* YYERRORSYMBOL is not defined */
129600      /* This is what we do if the grammar does not define ERROR:
129601      **
129602      **  * Report an error message, and throw away the input token.
129603      **
129604      **  * If the input token is $, then fail the parse.
129605      **
129606      ** As before, subsequent error messages are suppressed until
129607      ** three input tokens have been successfully shifted.
129608      */
129609      if( yypParser->yyerrcnt<=0 ){
129610        yy_syntax_error(yypParser,yymajor,yyminorunion);
129611      }
129612      yypParser->yyerrcnt = 3;
129613      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
129614      if( yyendofinput ){
129615        yy_parse_failed(yypParser);
129616      }
129617      yymajor = YYNOCODE;
129618#endif
129619    }
129620  }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
129621#ifndef NDEBUG
129622  if( yyTraceFILE ){
129623    fprintf(yyTraceFILE,"%sReturn\n",yyTracePrompt);
129624  }
129625#endif
129626  return;
129627}
129628
129629/************** End of parse.c ***********************************************/
129630/************** Begin file tokenize.c ****************************************/
129631/*
129632** 2001 September 15
129633**
129634** The author disclaims copyright to this source code.  In place of
129635** a legal notice, here is a blessing:
129636**
129637**    May you do good and not evil.
129638**    May you find forgiveness for yourself and forgive others.
129639**    May you share freely, never taking more than you give.
129640**
129641*************************************************************************
129642** An tokenizer for SQL
129643**
129644** This file contains C code that splits an SQL input string up into
129645** individual tokens and sends those tokens one-by-one over to the
129646** parser for analysis.
129647*/
129648/* #include "sqliteInt.h" */
129649/* #include <stdlib.h> */
129650
129651/*
129652** The charMap() macro maps alphabetic characters into their
129653** lower-case ASCII equivalent.  On ASCII machines, this is just
129654** an upper-to-lower case map.  On EBCDIC machines we also need
129655** to adjust the encoding.  Only alphabetic characters and underscores
129656** need to be translated.
129657*/
129658#ifdef SQLITE_ASCII
129659# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
129660#endif
129661#ifdef SQLITE_EBCDIC
129662# define charMap(X) ebcdicToAscii[(unsigned char)X]
129663const unsigned char ebcdicToAscii[] = {
129664/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
129665   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
129666   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
129667   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
129668   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
129669   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
129670   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
129671   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
129672   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
129673   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
129674   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
129675   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
129676   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
129677   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
129678   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
129679   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
129680   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
129681};
129682#endif
129683
129684/*
129685** The sqlite3KeywordCode function looks up an identifier to determine if
129686** it is a keyword.  If it is a keyword, the token code of that keyword is
129687** returned.  If the input is not a keyword, TK_ID is returned.
129688**
129689** The implementation of this routine was generated by a program,
129690** mkkeywordhash.h, located in the tool subdirectory of the distribution.
129691** The output of the mkkeywordhash.c program is written into a file
129692** named keywordhash.h and then included into this source file by
129693** the #include below.
129694*/
129695/************** Include keywordhash.h in the middle of tokenize.c ************/
129696/************** Begin file keywordhash.h *************************************/
129697/***** This file contains automatically generated code ******
129698**
129699** The code in this file has been automatically generated by
129700**
129701**   sqlite/tool/mkkeywordhash.c
129702**
129703** The code in this file implements a function that determines whether
129704** or not a given identifier is really an SQL keyword.  The same thing
129705** might be implemented more directly using a hand-written hash table.
129706** But by using this automatically generated code, the size of the code
129707** is substantially reduced.  This is important for embedded applications
129708** on platforms with limited memory.
129709*/
129710/* Hash score: 182 */
129711static int keywordCode(const char *z, int n){
129712  /* zText[] encodes 834 bytes of keywords in 554 bytes */
129713  /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
129714  /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
129715  /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
129716  /*   UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE         */
129717  /*   BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH     */
129718  /*   IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN     */
129719  /*   WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT         */
129720  /*   CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL        */
129721  /*   FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING        */
129722  /*   VACUUMVIEWINITIALLY                                                */
129723  static const char zText[553] = {
129724    'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
129725    'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
129726    'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
129727    'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
129728    'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
129729    'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
129730    'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
129731    'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
129732    'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
129733    'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
129734    'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
129735    'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
129736    'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
129737    'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
129738    'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
129739    'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
129740    'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
129741    'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
129742    'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
129743    'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
129744    'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
129745    'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
129746    'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
129747    'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
129748    'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
129749    'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
129750    'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
129751    'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
129752    'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
129753    'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
129754    'V','I','E','W','I','N','I','T','I','A','L','L','Y',
129755  };
129756  static const unsigned char aHash[127] = {
129757      76, 105, 117,  74,   0,  45,   0,   0,  82,   0,  77,   0,   0,
129758      42,  12,  78,  15,   0, 116,  85,  54, 112,   0,  19,   0,   0,
129759     121,   0, 119, 115,   0,  22,  93,   0,   9,   0,   0,  70,  71,
129760       0,  69,   6,   0,  48,  90, 102,   0, 118, 101,   0,   0,  44,
129761       0, 103,  24,   0,  17,   0, 122,  53,  23,   0,   5, 110,  25,
129762      96,   0,   0, 124, 106,  60, 123,  57,  28,  55,   0,  91,   0,
129763     100,  26,   0,  99,   0,   0,   0,  95,  92,  97,  88, 109,  14,
129764      39, 108,   0,  81,   0,  18,  89, 111,  32,   0, 120,  80, 113,
129765      62,  46,  84,   0,   0,  94,  40,  59, 114,   0,  36,   0,   0,
129766      29,   0,  86,  63,  64,   0,  20,  61,   0,  56,
129767  };
129768  static const unsigned char aNext[124] = {
129769       0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
129770       0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
129771       0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
129772       0,   0,   0,   0,  33,   0,  21,   0,   0,   0,   0,   0,  50,
129773       0,  43,   3,  47,   0,   0,   0,   0,  30,   0,  58,   0,  38,
129774       0,   0,   0,   1,  66,   0,   0,  67,   0,  41,   0,   0,   0,
129775       0,   0,   0,  49,  65,   0,   0,   0,   0,  31,  52,  16,  34,
129776      10,   0,   0,   0,   0,   0,   0,   0,  11,  72,  79,   0,   8,
129777       0, 104,  98,   0, 107,   0,  87,   0,  75,  51,   0,  27,  37,
129778      73,  83,   0,  35,  68,   0,   0,
129779  };
129780  static const unsigned char aLen[124] = {
129781       7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
129782       7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
129783      11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
129784       4,   6,   2,   3,   9,   4,   2,   6,   5,   7,   4,   5,   7,
129785       6,   6,   5,   6,   5,   5,   9,   7,   7,   3,   2,   4,   4,
129786       7,   3,   6,   4,   7,   6,  12,   6,   9,   4,   6,   5,   4,
129787       7,   6,   5,   6,   7,   5,   4,   5,   6,   5,   7,   3,   7,
129788      13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   8,   8,
129789       2,   4,   4,   4,   4,   4,   2,   2,   6,   5,   8,   5,   8,
129790       3,   5,   5,   6,   4,   9,   3,
129791  };
129792  static const unsigned short int aOffset[124] = {
129793       0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
129794      36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
129795      86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
129796     159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
129797     199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
129798     250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
129799     320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
129800     387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
129801     460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
129802     521, 524, 529, 534, 540, 544, 549,
129803  };
129804  static const unsigned char aCode[124] = {
129805    TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
129806    TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
129807    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
129808    TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
129809    TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
129810    TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
129811    TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
129812    TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
129813    TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
129814    TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_WITHOUT,    TK_WITH,
129815    TK_JOIN_KW,    TK_RELEASE,    TK_ATTACH,     TK_HAVING,     TK_GROUP,
129816    TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RECURSIVE,  TK_BETWEEN,
129817    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       TK_LIKE_KW,
129818    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       TK_COLLATE,
129819    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  TK_JOIN,
129820    TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,
129821    TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      TK_WHEN,
129822    TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    TK_AND,
129823    TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         TK_CAST,
129824    TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    TK_CTIME_KW,
129825    TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   TK_IS,
129826    TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    TK_LIKE_KW,
129827    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      TK_RESTRICT,
129828    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        TK_UNION,      TK_USING,
129829    TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  TK_ALL,
129830  };
129831  int h, i;
129832  if( n<2 ) return TK_ID;
129833  h = ((charMap(z[0])*4) ^
129834      (charMap(z[n-1])*3) ^
129835      n) % 127;
129836  for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
129837    if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
129838      testcase( i==0 ); /* REINDEX */
129839      testcase( i==1 ); /* INDEXED */
129840      testcase( i==2 ); /* INDEX */
129841      testcase( i==3 ); /* DESC */
129842      testcase( i==4 ); /* ESCAPE */
129843      testcase( i==5 ); /* EACH */
129844      testcase( i==6 ); /* CHECK */
129845      testcase( i==7 ); /* KEY */
129846      testcase( i==8 ); /* BEFORE */
129847      testcase( i==9 ); /* FOREIGN */
129848      testcase( i==10 ); /* FOR */
129849      testcase( i==11 ); /* IGNORE */
129850      testcase( i==12 ); /* REGEXP */
129851      testcase( i==13 ); /* EXPLAIN */
129852      testcase( i==14 ); /* INSTEAD */
129853      testcase( i==15 ); /* ADD */
129854      testcase( i==16 ); /* DATABASE */
129855      testcase( i==17 ); /* AS */
129856      testcase( i==18 ); /* SELECT */
129857      testcase( i==19 ); /* TABLE */
129858      testcase( i==20 ); /* LEFT */
129859      testcase( i==21 ); /* THEN */
129860      testcase( i==22 ); /* END */
129861      testcase( i==23 ); /* DEFERRABLE */
129862      testcase( i==24 ); /* ELSE */
129863      testcase( i==25 ); /* EXCEPT */
129864      testcase( i==26 ); /* TRANSACTION */
129865      testcase( i==27 ); /* ACTION */
129866      testcase( i==28 ); /* ON */
129867      testcase( i==29 ); /* NATURAL */
129868      testcase( i==30 ); /* ALTER */
129869      testcase( i==31 ); /* RAISE */
129870      testcase( i==32 ); /* EXCLUSIVE */
129871      testcase( i==33 ); /* EXISTS */
129872      testcase( i==34 ); /* SAVEPOINT */
129873      testcase( i==35 ); /* INTERSECT */
129874      testcase( i==36 ); /* TRIGGER */
129875      testcase( i==37 ); /* REFERENCES */
129876      testcase( i==38 ); /* CONSTRAINT */
129877      testcase( i==39 ); /* INTO */
129878      testcase( i==40 ); /* OFFSET */
129879      testcase( i==41 ); /* OF */
129880      testcase( i==42 ); /* SET */
129881      testcase( i==43 ); /* TEMPORARY */
129882      testcase( i==44 ); /* TEMP */
129883      testcase( i==45 ); /* OR */
129884      testcase( i==46 ); /* UNIQUE */
129885      testcase( i==47 ); /* QUERY */
129886      testcase( i==48 ); /* WITHOUT */
129887      testcase( i==49 ); /* WITH */
129888      testcase( i==50 ); /* OUTER */
129889      testcase( i==51 ); /* RELEASE */
129890      testcase( i==52 ); /* ATTACH */
129891      testcase( i==53 ); /* HAVING */
129892      testcase( i==54 ); /* GROUP */
129893      testcase( i==55 ); /* UPDATE */
129894      testcase( i==56 ); /* BEGIN */
129895      testcase( i==57 ); /* INNER */
129896      testcase( i==58 ); /* RECURSIVE */
129897      testcase( i==59 ); /* BETWEEN */
129898      testcase( i==60 ); /* NOTNULL */
129899      testcase( i==61 ); /* NOT */
129900      testcase( i==62 ); /* NO */
129901      testcase( i==63 ); /* NULL */
129902      testcase( i==64 ); /* LIKE */
129903      testcase( i==65 ); /* CASCADE */
129904      testcase( i==66 ); /* ASC */
129905      testcase( i==67 ); /* DELETE */
129906      testcase( i==68 ); /* CASE */
129907      testcase( i==69 ); /* COLLATE */
129908      testcase( i==70 ); /* CREATE */
129909      testcase( i==71 ); /* CURRENT_DATE */
129910      testcase( i==72 ); /* DETACH */
129911      testcase( i==73 ); /* IMMEDIATE */
129912      testcase( i==74 ); /* JOIN */
129913      testcase( i==75 ); /* INSERT */
129914      testcase( i==76 ); /* MATCH */
129915      testcase( i==77 ); /* PLAN */
129916      testcase( i==78 ); /* ANALYZE */
129917      testcase( i==79 ); /* PRAGMA */
129918      testcase( i==80 ); /* ABORT */
129919      testcase( i==81 ); /* VALUES */
129920      testcase( i==82 ); /* VIRTUAL */
129921      testcase( i==83 ); /* LIMIT */
129922      testcase( i==84 ); /* WHEN */
129923      testcase( i==85 ); /* WHERE */
129924      testcase( i==86 ); /* RENAME */
129925      testcase( i==87 ); /* AFTER */
129926      testcase( i==88 ); /* REPLACE */
129927      testcase( i==89 ); /* AND */
129928      testcase( i==90 ); /* DEFAULT */
129929      testcase( i==91 ); /* AUTOINCREMENT */
129930      testcase( i==92 ); /* TO */
129931      testcase( i==93 ); /* IN */
129932      testcase( i==94 ); /* CAST */
129933      testcase( i==95 ); /* COLUMN */
129934      testcase( i==96 ); /* COMMIT */
129935      testcase( i==97 ); /* CONFLICT */
129936      testcase( i==98 ); /* CROSS */
129937      testcase( i==99 ); /* CURRENT_TIMESTAMP */
129938      testcase( i==100 ); /* CURRENT_TIME */
129939      testcase( i==101 ); /* PRIMARY */
129940      testcase( i==102 ); /* DEFERRED */
129941      testcase( i==103 ); /* DISTINCT */
129942      testcase( i==104 ); /* IS */
129943      testcase( i==105 ); /* DROP */
129944      testcase( i==106 ); /* FAIL */
129945      testcase( i==107 ); /* FROM */
129946      testcase( i==108 ); /* FULL */
129947      testcase( i==109 ); /* GLOB */
129948      testcase( i==110 ); /* BY */
129949      testcase( i==111 ); /* IF */
129950      testcase( i==112 ); /* ISNULL */
129951      testcase( i==113 ); /* ORDER */
129952      testcase( i==114 ); /* RESTRICT */
129953      testcase( i==115 ); /* RIGHT */
129954      testcase( i==116 ); /* ROLLBACK */
129955      testcase( i==117 ); /* ROW */
129956      testcase( i==118 ); /* UNION */
129957      testcase( i==119 ); /* USING */
129958      testcase( i==120 ); /* VACUUM */
129959      testcase( i==121 ); /* VIEW */
129960      testcase( i==122 ); /* INITIALLY */
129961      testcase( i==123 ); /* ALL */
129962      return aCode[i];
129963    }
129964  }
129965  return TK_ID;
129966}
129967SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
129968  return keywordCode((char*)z, n);
129969}
129970#define SQLITE_N_KEYWORD 124
129971
129972/************** End of keywordhash.h *****************************************/
129973/************** Continuing where we left off in tokenize.c *******************/
129974
129975
129976/*
129977** If X is a character that can be used in an identifier then
129978** IdChar(X) will be true.  Otherwise it is false.
129979**
129980** For ASCII, any character with the high-order bit set is
129981** allowed in an identifier.  For 7-bit characters,
129982** sqlite3IsIdChar[X] must be 1.
129983**
129984** For EBCDIC, the rules are more complex but have the same
129985** end result.
129986**
129987** Ticket #1066.  the SQL standard does not allow '$' in the
129988** middle of identifiers.  But many SQL implementations do.
129989** SQLite will allow '$' in identifiers for compatibility.
129990** But the feature is undocumented.
129991*/
129992#ifdef SQLITE_ASCII
129993#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
129994#endif
129995#ifdef SQLITE_EBCDIC
129996SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
129997/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
129998    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
129999    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
130000    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
130001    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
130002    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
130003    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
130004    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
130005    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
130006    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
130007    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
130008    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
130009    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
130010};
130011#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
130012#endif
130013
130014/* Make the IdChar function accessible from ctime.c */
130015#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
130016SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
130017#endif
130018
130019
130020/*
130021** Return the length of the token that begins at z[0].
130022** Store the token type in *tokenType before returning.
130023*/
130024SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
130025  int i, c;
130026  switch( *z ){
130027    case ' ': case '\t': case '\n': case '\f': case '\r': {
130028      testcase( z[0]==' ' );
130029      testcase( z[0]=='\t' );
130030      testcase( z[0]=='\n' );
130031      testcase( z[0]=='\f' );
130032      testcase( z[0]=='\r' );
130033      for(i=1; sqlite3Isspace(z[i]); i++){}
130034      *tokenType = TK_SPACE;
130035      return i;
130036    }
130037    case '-': {
130038      if( z[1]=='-' ){
130039        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
130040        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
130041        return i;
130042      }
130043      *tokenType = TK_MINUS;
130044      return 1;
130045    }
130046    case '(': {
130047      *tokenType = TK_LP;
130048      return 1;
130049    }
130050    case ')': {
130051      *tokenType = TK_RP;
130052      return 1;
130053    }
130054    case ';': {
130055      *tokenType = TK_SEMI;
130056      return 1;
130057    }
130058    case '+': {
130059      *tokenType = TK_PLUS;
130060      return 1;
130061    }
130062    case '*': {
130063      *tokenType = TK_STAR;
130064      return 1;
130065    }
130066    case '/': {
130067      if( z[1]!='*' || z[2]==0 ){
130068        *tokenType = TK_SLASH;
130069        return 1;
130070      }
130071      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
130072      if( c ) i++;
130073      *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
130074      return i;
130075    }
130076    case '%': {
130077      *tokenType = TK_REM;
130078      return 1;
130079    }
130080    case '=': {
130081      *tokenType = TK_EQ;
130082      return 1 + (z[1]=='=');
130083    }
130084    case '<': {
130085      if( (c=z[1])=='=' ){
130086        *tokenType = TK_LE;
130087        return 2;
130088      }else if( c=='>' ){
130089        *tokenType = TK_NE;
130090        return 2;
130091      }else if( c=='<' ){
130092        *tokenType = TK_LSHIFT;
130093        return 2;
130094      }else{
130095        *tokenType = TK_LT;
130096        return 1;
130097      }
130098    }
130099    case '>': {
130100      if( (c=z[1])=='=' ){
130101        *tokenType = TK_GE;
130102        return 2;
130103      }else if( c=='>' ){
130104        *tokenType = TK_RSHIFT;
130105        return 2;
130106      }else{
130107        *tokenType = TK_GT;
130108        return 1;
130109      }
130110    }
130111    case '!': {
130112      if( z[1]!='=' ){
130113        *tokenType = TK_ILLEGAL;
130114        return 2;
130115      }else{
130116        *tokenType = TK_NE;
130117        return 2;
130118      }
130119    }
130120    case '|': {
130121      if( z[1]!='|' ){
130122        *tokenType = TK_BITOR;
130123        return 1;
130124      }else{
130125        *tokenType = TK_CONCAT;
130126        return 2;
130127      }
130128    }
130129    case ',': {
130130      *tokenType = TK_COMMA;
130131      return 1;
130132    }
130133    case '&': {
130134      *tokenType = TK_BITAND;
130135      return 1;
130136    }
130137    case '~': {
130138      *tokenType = TK_BITNOT;
130139      return 1;
130140    }
130141    case '`':
130142    case '\'':
130143    case '"': {
130144      int delim = z[0];
130145      testcase( delim=='`' );
130146      testcase( delim=='\'' );
130147      testcase( delim=='"' );
130148      for(i=1; (c=z[i])!=0; i++){
130149        if( c==delim ){
130150          if( z[i+1]==delim ){
130151            i++;
130152          }else{
130153            break;
130154          }
130155        }
130156      }
130157      if( c=='\'' ){
130158        *tokenType = TK_STRING;
130159        return i+1;
130160      }else if( c!=0 ){
130161        *tokenType = TK_ID;
130162        return i+1;
130163      }else{
130164        *tokenType = TK_ILLEGAL;
130165        return i;
130166      }
130167    }
130168    case '.': {
130169#ifndef SQLITE_OMIT_FLOATING_POINT
130170      if( !sqlite3Isdigit(z[1]) )
130171#endif
130172      {
130173        *tokenType = TK_DOT;
130174        return 1;
130175      }
130176      /* If the next character is a digit, this is a floating point
130177      ** number that begins with ".".  Fall thru into the next case */
130178    }
130179    case '0': case '1': case '2': case '3': case '4':
130180    case '5': case '6': case '7': case '8': case '9': {
130181      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
130182      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
130183      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
130184      testcase( z[0]=='9' );
130185      *tokenType = TK_INTEGER;
130186#ifndef SQLITE_OMIT_HEX_INTEGER
130187      if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
130188        for(i=3; sqlite3Isxdigit(z[i]); i++){}
130189        return i;
130190      }
130191#endif
130192      for(i=0; sqlite3Isdigit(z[i]); i++){}
130193#ifndef SQLITE_OMIT_FLOATING_POINT
130194      if( z[i]=='.' ){
130195        i++;
130196        while( sqlite3Isdigit(z[i]) ){ i++; }
130197        *tokenType = TK_FLOAT;
130198      }
130199      if( (z[i]=='e' || z[i]=='E') &&
130200           ( sqlite3Isdigit(z[i+1])
130201            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
130202           )
130203      ){
130204        i += 2;
130205        while( sqlite3Isdigit(z[i]) ){ i++; }
130206        *tokenType = TK_FLOAT;
130207      }
130208#endif
130209      while( IdChar(z[i]) ){
130210        *tokenType = TK_ILLEGAL;
130211        i++;
130212      }
130213      return i;
130214    }
130215    case '[': {
130216      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
130217      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
130218      return i;
130219    }
130220    case '?': {
130221      *tokenType = TK_VARIABLE;
130222      for(i=1; sqlite3Isdigit(z[i]); i++){}
130223      return i;
130224    }
130225#ifndef SQLITE_OMIT_TCL_VARIABLE
130226    case '$':
130227#endif
130228    case '@':  /* For compatibility with MS SQL Server */
130229    case '#':
130230    case ':': {
130231      int n = 0;
130232      testcase( z[0]=='$' );  testcase( z[0]=='@' );
130233      testcase( z[0]==':' );  testcase( z[0]=='#' );
130234      *tokenType = TK_VARIABLE;
130235      for(i=1; (c=z[i])!=0; i++){
130236        if( IdChar(c) ){
130237          n++;
130238#ifndef SQLITE_OMIT_TCL_VARIABLE
130239        }else if( c=='(' && n>0 ){
130240          do{
130241            i++;
130242          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
130243          if( c==')' ){
130244            i++;
130245          }else{
130246            *tokenType = TK_ILLEGAL;
130247          }
130248          break;
130249        }else if( c==':' && z[i+1]==':' ){
130250          i++;
130251#endif
130252        }else{
130253          break;
130254        }
130255      }
130256      if( n==0 ) *tokenType = TK_ILLEGAL;
130257      return i;
130258    }
130259#ifndef SQLITE_OMIT_BLOB_LITERAL
130260    case 'x': case 'X': {
130261      testcase( z[0]=='x' ); testcase( z[0]=='X' );
130262      if( z[1]=='\'' ){
130263        *tokenType = TK_BLOB;
130264        for(i=2; sqlite3Isxdigit(z[i]); i++){}
130265        if( z[i]!='\'' || i%2 ){
130266          *tokenType = TK_ILLEGAL;
130267          while( z[i] && z[i]!='\'' ){ i++; }
130268        }
130269        if( z[i] ) i++;
130270        return i;
130271      }
130272      /* Otherwise fall through to the next case */
130273    }
130274#endif
130275    default: {
130276      if( !IdChar(*z) ){
130277        break;
130278      }
130279      for(i=1; IdChar(z[i]); i++){}
130280      *tokenType = keywordCode((char*)z, i);
130281      return i;
130282    }
130283  }
130284  *tokenType = TK_ILLEGAL;
130285  return 1;
130286}
130287
130288/*
130289** Run the parser on the given SQL string.  The parser structure is
130290** passed in.  An SQLITE_ status code is returned.  If an error occurs
130291** then an and attempt is made to write an error message into
130292** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
130293** error message.
130294*/
130295SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
130296  int nErr = 0;                   /* Number of errors encountered */
130297  int i;                          /* Loop counter */
130298  void *pEngine;                  /* The LEMON-generated LALR(1) parser */
130299  int tokenType;                  /* type of the next token */
130300  int lastTokenParsed = -1;       /* type of the previous token */
130301  u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
130302  sqlite3 *db = pParse->db;       /* The database connection */
130303  int mxSqlLen;                   /* Max length of an SQL string */
130304
130305  assert( zSql!=0 );
130306  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
130307  if( db->nVdbeActive==0 ){
130308    db->u1.isInterrupted = 0;
130309  }
130310  pParse->rc = SQLITE_OK;
130311  pParse->zTail = zSql;
130312  i = 0;
130313  assert( pzErrMsg!=0 );
130314  /* sqlite3ParserTrace(stdout, "parser: "); */
130315  pEngine = sqlite3ParserAlloc(sqlite3Malloc);
130316  if( pEngine==0 ){
130317    db->mallocFailed = 1;
130318    return SQLITE_NOMEM;
130319  }
130320  assert( pParse->pNewTable==0 );
130321  assert( pParse->pNewTrigger==0 );
130322  assert( pParse->nVar==0 );
130323  assert( pParse->nzVar==0 );
130324  assert( pParse->azVar==0 );
130325  enableLookaside = db->lookaside.bEnabled;
130326  if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
130327  while( !db->mallocFailed && zSql[i]!=0 ){
130328    assert( i>=0 );
130329    pParse->sLastToken.z = &zSql[i];
130330    pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
130331    i += pParse->sLastToken.n;
130332    if( i>mxSqlLen ){
130333      pParse->rc = SQLITE_TOOBIG;
130334      break;
130335    }
130336    switch( tokenType ){
130337      case TK_SPACE: {
130338        if( db->u1.isInterrupted ){
130339          sqlite3ErrorMsg(pParse, "interrupt");
130340          pParse->rc = SQLITE_INTERRUPT;
130341          goto abort_parse;
130342        }
130343        break;
130344      }
130345      case TK_ILLEGAL: {
130346        sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"",
130347                        &pParse->sLastToken);
130348        goto abort_parse;
130349      }
130350      case TK_SEMI: {
130351        pParse->zTail = &zSql[i];
130352        /* Fall thru into the default case */
130353      }
130354      default: {
130355        sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
130356        lastTokenParsed = tokenType;
130357        if( pParse->rc!=SQLITE_OK ){
130358          goto abort_parse;
130359        }
130360        break;
130361      }
130362    }
130363  }
130364abort_parse:
130365  assert( nErr==0 );
130366  if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
130367    assert( zSql[i]==0 );
130368    if( lastTokenParsed!=TK_SEMI ){
130369      sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
130370      pParse->zTail = &zSql[i];
130371    }
130372    if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
130373      sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
130374    }
130375  }
130376#ifdef YYTRACKMAXSTACKDEPTH
130377  sqlite3_mutex_enter(sqlite3MallocMutex());
130378  sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
130379      sqlite3ParserStackPeak(pEngine)
130380  );
130381  sqlite3_mutex_leave(sqlite3MallocMutex());
130382#endif /* YYDEBUG */
130383  sqlite3ParserFree(pEngine, sqlite3_free);
130384  db->lookaside.bEnabled = enableLookaside;
130385  if( db->mallocFailed ){
130386    pParse->rc = SQLITE_NOMEM;
130387  }
130388  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
130389    pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
130390  }
130391  assert( pzErrMsg!=0 );
130392  if( pParse->zErrMsg ){
130393    *pzErrMsg = pParse->zErrMsg;
130394    sqlite3_log(pParse->rc, "%s", *pzErrMsg);
130395    pParse->zErrMsg = 0;
130396    nErr++;
130397  }
130398  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
130399    sqlite3VdbeDelete(pParse->pVdbe);
130400    pParse->pVdbe = 0;
130401  }
130402#ifndef SQLITE_OMIT_SHARED_CACHE
130403  if( pParse->nested==0 ){
130404    sqlite3DbFree(db, pParse->aTableLock);
130405    pParse->aTableLock = 0;
130406    pParse->nTableLock = 0;
130407  }
130408#endif
130409#ifndef SQLITE_OMIT_VIRTUALTABLE
130410  sqlite3_free(pParse->apVtabLock);
130411#endif
130412
130413  if( !IN_DECLARE_VTAB ){
130414    /* If the pParse->declareVtab flag is set, do not delete any table
130415    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
130416    ** will take responsibility for freeing the Table structure.
130417    */
130418    sqlite3DeleteTable(db, pParse->pNewTable);
130419  }
130420
130421  if( pParse->bFreeWith ) sqlite3WithDelete(db, pParse->pWith);
130422  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
130423  for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
130424  sqlite3DbFree(db, pParse->azVar);
130425  while( pParse->pAinc ){
130426    AutoincInfo *p = pParse->pAinc;
130427    pParse->pAinc = p->pNext;
130428    sqlite3DbFree(db, p);
130429  }
130430  while( pParse->pZombieTab ){
130431    Table *p = pParse->pZombieTab;
130432    pParse->pZombieTab = p->pNextZombie;
130433    sqlite3DeleteTable(db, p);
130434  }
130435  assert( nErr==0 || pParse->rc!=SQLITE_OK );
130436  return nErr;
130437}
130438
130439/************** End of tokenize.c ********************************************/
130440/************** Begin file complete.c ****************************************/
130441/*
130442** 2001 September 15
130443**
130444** The author disclaims copyright to this source code.  In place of
130445** a legal notice, here is a blessing:
130446**
130447**    May you do good and not evil.
130448**    May you find forgiveness for yourself and forgive others.
130449**    May you share freely, never taking more than you give.
130450**
130451*************************************************************************
130452** An tokenizer for SQL
130453**
130454** This file contains C code that implements the sqlite3_complete() API.
130455** This code used to be part of the tokenizer.c source file.  But by
130456** separating it out, the code will be automatically omitted from
130457** static links that do not use it.
130458*/
130459/* #include "sqliteInt.h" */
130460#ifndef SQLITE_OMIT_COMPLETE
130461
130462/*
130463** This is defined in tokenize.c.  We just have to import the definition.
130464*/
130465#ifndef SQLITE_AMALGAMATION
130466#ifdef SQLITE_ASCII
130467#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
130468#endif
130469#ifdef SQLITE_EBCDIC
130470SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
130471#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
130472#endif
130473#endif /* SQLITE_AMALGAMATION */
130474
130475
130476/*
130477** Token types used by the sqlite3_complete() routine.  See the header
130478** comments on that procedure for additional information.
130479*/
130480#define tkSEMI    0
130481#define tkWS      1
130482#define tkOTHER   2
130483#ifndef SQLITE_OMIT_TRIGGER
130484#define tkEXPLAIN 3
130485#define tkCREATE  4
130486#define tkTEMP    5
130487#define tkTRIGGER 6
130488#define tkEND     7
130489#endif
130490
130491/*
130492** Return TRUE if the given SQL string ends in a semicolon.
130493**
130494** Special handling is require for CREATE TRIGGER statements.
130495** Whenever the CREATE TRIGGER keywords are seen, the statement
130496** must end with ";END;".
130497**
130498** This implementation uses a state machine with 8 states:
130499**
130500**   (0) INVALID   We have not yet seen a non-whitespace character.
130501**
130502**   (1) START     At the beginning or end of an SQL statement.  This routine
130503**                 returns 1 if it ends in the START state and 0 if it ends
130504**                 in any other state.
130505**
130506**   (2) NORMAL    We are in the middle of statement which ends with a single
130507**                 semicolon.
130508**
130509**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
130510**                 a statement.
130511**
130512**   (4) CREATE    The keyword CREATE has been seen at the beginning of a
130513**                 statement, possibly preceded by EXPLAIN and/or followed by
130514**                 TEMP or TEMPORARY
130515**
130516**   (5) TRIGGER   We are in the middle of a trigger definition that must be
130517**                 ended by a semicolon, the keyword END, and another semicolon.
130518**
130519**   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
130520**                 the end of a trigger definition.
130521**
130522**   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
130523**                 of a trigger definition.
130524**
130525** Transitions between states above are determined by tokens extracted
130526** from the input.  The following tokens are significant:
130527**
130528**   (0) tkSEMI      A semicolon.
130529**   (1) tkWS        Whitespace.
130530**   (2) tkOTHER     Any other SQL token.
130531**   (3) tkEXPLAIN   The "explain" keyword.
130532**   (4) tkCREATE    The "create" keyword.
130533**   (5) tkTEMP      The "temp" or "temporary" keyword.
130534**   (6) tkTRIGGER   The "trigger" keyword.
130535**   (7) tkEND       The "end" keyword.
130536**
130537** Whitespace never causes a state transition and is always ignored.
130538** This means that a SQL string of all whitespace is invalid.
130539**
130540** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
130541** to recognize the end of a trigger can be omitted.  All we have to do
130542** is look for a semicolon that is not part of an string or comment.
130543*/
130544SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *zSql){
130545  u8 state = 0;   /* Current state, using numbers defined in header comment */
130546  u8 token;       /* Value of the next token */
130547
130548#ifndef SQLITE_OMIT_TRIGGER
130549  /* A complex statement machine used to detect the end of a CREATE TRIGGER
130550  ** statement.  This is the normal case.
130551  */
130552  static const u8 trans[8][8] = {
130553                     /* Token:                                                */
130554     /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
130555     /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
130556     /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
130557     /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
130558     /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
130559     /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
130560     /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
130561     /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
130562     /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
130563  };
130564#else
130565  /* If triggers are not supported by this compile then the statement machine
130566  ** used to detect the end of a statement is much simpler
130567  */
130568  static const u8 trans[3][3] = {
130569                     /* Token:           */
130570     /* State:       **  SEMI  WS  OTHER */
130571     /* 0 INVALID: */ {    1,  0,     2, },
130572     /* 1   START: */ {    1,  1,     2, },
130573     /* 2  NORMAL: */ {    1,  2,     2, },
130574  };
130575#endif /* SQLITE_OMIT_TRIGGER */
130576
130577#ifdef SQLITE_ENABLE_API_ARMOR
130578  if( zSql==0 ){
130579    (void)SQLITE_MISUSE_BKPT;
130580    return 0;
130581  }
130582#endif
130583
130584  while( *zSql ){
130585    switch( *zSql ){
130586      case ';': {  /* A semicolon */
130587        token = tkSEMI;
130588        break;
130589      }
130590      case ' ':
130591      case '\r':
130592      case '\t':
130593      case '\n':
130594      case '\f': {  /* White space is ignored */
130595        token = tkWS;
130596        break;
130597      }
130598      case '/': {   /* C-style comments */
130599        if( zSql[1]!='*' ){
130600          token = tkOTHER;
130601          break;
130602        }
130603        zSql += 2;
130604        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
130605        if( zSql[0]==0 ) return 0;
130606        zSql++;
130607        token = tkWS;
130608        break;
130609      }
130610      case '-': {   /* SQL-style comments from "--" to end of line */
130611        if( zSql[1]!='-' ){
130612          token = tkOTHER;
130613          break;
130614        }
130615        while( *zSql && *zSql!='\n' ){ zSql++; }
130616        if( *zSql==0 ) return state==1;
130617        token = tkWS;
130618        break;
130619      }
130620      case '[': {   /* Microsoft-style identifiers in [...] */
130621        zSql++;
130622        while( *zSql && *zSql!=']' ){ zSql++; }
130623        if( *zSql==0 ) return 0;
130624        token = tkOTHER;
130625        break;
130626      }
130627      case '`':     /* Grave-accent quoted symbols used by MySQL */
130628      case '"':     /* single- and double-quoted strings */
130629      case '\'': {
130630        int c = *zSql;
130631        zSql++;
130632        while( *zSql && *zSql!=c ){ zSql++; }
130633        if( *zSql==0 ) return 0;
130634        token = tkOTHER;
130635        break;
130636      }
130637      default: {
130638#ifdef SQLITE_EBCDIC
130639        unsigned char c;
130640#endif
130641        if( IdChar((u8)*zSql) ){
130642          /* Keywords and unquoted identifiers */
130643          int nId;
130644          for(nId=1; IdChar(zSql[nId]); nId++){}
130645#ifdef SQLITE_OMIT_TRIGGER
130646          token = tkOTHER;
130647#else
130648          switch( *zSql ){
130649            case 'c': case 'C': {
130650              if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
130651                token = tkCREATE;
130652              }else{
130653                token = tkOTHER;
130654              }
130655              break;
130656            }
130657            case 't': case 'T': {
130658              if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
130659                token = tkTRIGGER;
130660              }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
130661                token = tkTEMP;
130662              }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
130663                token = tkTEMP;
130664              }else{
130665                token = tkOTHER;
130666              }
130667              break;
130668            }
130669            case 'e':  case 'E': {
130670              if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
130671                token = tkEND;
130672              }else
130673#ifndef SQLITE_OMIT_EXPLAIN
130674              if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
130675                token = tkEXPLAIN;
130676              }else
130677#endif
130678              {
130679                token = tkOTHER;
130680              }
130681              break;
130682            }
130683            default: {
130684              token = tkOTHER;
130685              break;
130686            }
130687          }
130688#endif /* SQLITE_OMIT_TRIGGER */
130689          zSql += nId-1;
130690        }else{
130691          /* Operators and special symbols */
130692          token = tkOTHER;
130693        }
130694        break;
130695      }
130696    }
130697    state = trans[state][token];
130698    zSql++;
130699  }
130700  return state==1;
130701}
130702
130703#ifndef SQLITE_OMIT_UTF16
130704/*
130705** This routine is the same as the sqlite3_complete() routine described
130706** above, except that the parameter is required to be UTF-16 encoded, not
130707** UTF-8.
130708*/
130709SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *zSql){
130710  sqlite3_value *pVal;
130711  char const *zSql8;
130712  int rc;
130713
130714#ifndef SQLITE_OMIT_AUTOINIT
130715  rc = sqlite3_initialize();
130716  if( rc ) return rc;
130717#endif
130718  pVal = sqlite3ValueNew(0);
130719  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
130720  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
130721  if( zSql8 ){
130722    rc = sqlite3_complete(zSql8);
130723  }else{
130724    rc = SQLITE_NOMEM;
130725  }
130726  sqlite3ValueFree(pVal);
130727  return rc & 0xff;
130728}
130729#endif /* SQLITE_OMIT_UTF16 */
130730#endif /* SQLITE_OMIT_COMPLETE */
130731
130732/************** End of complete.c ********************************************/
130733/************** Begin file main.c ********************************************/
130734/*
130735** 2001 September 15
130736**
130737** The author disclaims copyright to this source code.  In place of
130738** a legal notice, here is a blessing:
130739**
130740**    May you do good and not evil.
130741**    May you find forgiveness for yourself and forgive others.
130742**    May you share freely, never taking more than you give.
130743**
130744*************************************************************************
130745** Main file for the SQLite library.  The routines in this file
130746** implement the programmer interface to the library.  Routines in
130747** other files are for internal use by SQLite and should not be
130748** accessed by users of the library.
130749*/
130750/* #include "sqliteInt.h" */
130751
130752#ifdef SQLITE_ENABLE_FTS3
130753/************** Include fts3.h in the middle of main.c ***********************/
130754/************** Begin file fts3.h ********************************************/
130755/*
130756** 2006 Oct 10
130757**
130758** The author disclaims copyright to this source code.  In place of
130759** a legal notice, here is a blessing:
130760**
130761**    May you do good and not evil.
130762**    May you find forgiveness for yourself and forgive others.
130763**    May you share freely, never taking more than you give.
130764**
130765******************************************************************************
130766**
130767** This header file is used by programs that want to link against the
130768** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
130769*/
130770/* #include "sqlite3.h" */
130771
130772#if 0
130773extern "C" {
130774#endif  /* __cplusplus */
130775
130776SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
130777
130778#if 0
130779}  /* extern "C" */
130780#endif  /* __cplusplus */
130781
130782/************** End of fts3.h ************************************************/
130783/************** Continuing where we left off in main.c ***********************/
130784#endif
130785#ifdef SQLITE_ENABLE_RTREE
130786/************** Include rtree.h in the middle of main.c **********************/
130787/************** Begin file rtree.h *******************************************/
130788/*
130789** 2008 May 26
130790**
130791** The author disclaims copyright to this source code.  In place of
130792** a legal notice, here is a blessing:
130793**
130794**    May you do good and not evil.
130795**    May you find forgiveness for yourself and forgive others.
130796**    May you share freely, never taking more than you give.
130797**
130798******************************************************************************
130799**
130800** This header file is used by programs that want to link against the
130801** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
130802*/
130803/* #include "sqlite3.h" */
130804
130805#if 0
130806extern "C" {
130807#endif  /* __cplusplus */
130808
130809SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
130810
130811#if 0
130812}  /* extern "C" */
130813#endif  /* __cplusplus */
130814
130815/************** End of rtree.h ***********************************************/
130816/************** Continuing where we left off in main.c ***********************/
130817#endif
130818#ifdef SQLITE_ENABLE_ICU
130819/************** Include sqliteicu.h in the middle of main.c ******************/
130820/************** Begin file sqliteicu.h ***************************************/
130821/*
130822** 2008 May 26
130823**
130824** The author disclaims copyright to this source code.  In place of
130825** a legal notice, here is a blessing:
130826**
130827**    May you do good and not evil.
130828**    May you find forgiveness for yourself and forgive others.
130829**    May you share freely, never taking more than you give.
130830**
130831******************************************************************************
130832**
130833** This header file is used by programs that want to link against the
130834** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
130835*/
130836/* #include "sqlite3.h" */
130837
130838#if 0
130839extern "C" {
130840#endif  /* __cplusplus */
130841
130842SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
130843
130844#if 0
130845}  /* extern "C" */
130846#endif  /* __cplusplus */
130847
130848
130849/************** End of sqliteicu.h *******************************************/
130850/************** Continuing where we left off in main.c ***********************/
130851#endif
130852#ifdef SQLITE_ENABLE_JSON1
130853SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
130854#endif
130855#ifdef SQLITE_ENABLE_FTS5
130856SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
130857#endif
130858
130859#ifndef SQLITE_AMALGAMATION
130860/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
130861** contains the text of SQLITE_VERSION macro.
130862*/
130863SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
130864#endif
130865
130866/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
130867** a pointer to the to the sqlite3_version[] string constant.
130868*/
130869SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void){ return sqlite3_version; }
130870
130871/* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
130872** pointer to a string constant whose value is the same as the
130873** SQLITE_SOURCE_ID C preprocessor macro.
130874*/
130875SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
130876
130877/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
130878** returns an integer equal to SQLITE_VERSION_NUMBER.
130879*/
130880SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
130881
130882/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
130883** zero if and only if SQLite was compiled with mutexing code omitted due to
130884** the SQLITE_THREADSAFE compile-time option being set to 0.
130885*/
130886SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
130887
130888/*
130889** When compiling the test fixture or with debugging enabled (on Win32),
130890** this variable being set to non-zero will cause OSTRACE macros to emit
130891** extra diagnostic information.
130892*/
130893#ifdef SQLITE_HAVE_OS_TRACE
130894# ifndef SQLITE_DEBUG_OS_TRACE
130895#   define SQLITE_DEBUG_OS_TRACE 0
130896# endif
130897  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
130898#endif
130899
130900#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
130901/*
130902** If the following function pointer is not NULL and if
130903** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
130904** I/O active are written using this function.  These messages
130905** are intended for debugging activity only.
130906*/
130907SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
130908#endif
130909
130910/*
130911** If the following global variable points to a string which is the
130912** name of a directory, then that directory will be used to store
130913** temporary files.
130914**
130915** See also the "PRAGMA temp_store_directory" SQL command.
130916*/
130917SQLITE_API char *sqlite3_temp_directory = 0;
130918
130919/*
130920** If the following global variable points to a string which is the
130921** name of a directory, then that directory will be used to store
130922** all database files specified with a relative pathname.
130923**
130924** See also the "PRAGMA data_store_directory" SQL command.
130925*/
130926SQLITE_API char *sqlite3_data_directory = 0;
130927
130928/*
130929** Initialize SQLite.
130930**
130931** This routine must be called to initialize the memory allocation,
130932** VFS, and mutex subsystems prior to doing any serious work with
130933** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
130934** this routine will be called automatically by key routines such as
130935** sqlite3_open().
130936**
130937** This routine is a no-op except on its very first call for the process,
130938** or for the first call after a call to sqlite3_shutdown.
130939**
130940** The first thread to call this routine runs the initialization to
130941** completion.  If subsequent threads call this routine before the first
130942** thread has finished the initialization process, then the subsequent
130943** threads must block until the first thread finishes with the initialization.
130944**
130945** The first thread might call this routine recursively.  Recursive
130946** calls to this routine should not block, of course.  Otherwise the
130947** initialization process would never complete.
130948**
130949** Let X be the first thread to enter this routine.  Let Y be some other
130950** thread.  Then while the initial invocation of this routine by X is
130951** incomplete, it is required that:
130952**
130953**    *  Calls to this routine from Y must block until the outer-most
130954**       call by X completes.
130955**
130956**    *  Recursive calls to this routine from thread X return immediately
130957**       without blocking.
130958*/
130959SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void){
130960  MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
130961  int rc;                                      /* Result code */
130962#ifdef SQLITE_EXTRA_INIT
130963  int bRunExtraInit = 0;                       /* Extra initialization needed */
130964#endif
130965
130966#ifdef SQLITE_OMIT_WSD
130967  rc = sqlite3_wsd_init(4096, 24);
130968  if( rc!=SQLITE_OK ){
130969    return rc;
130970  }
130971#endif
130972
130973  /* If the following assert() fails on some obscure processor/compiler
130974  ** combination, the work-around is to set the correct pointer
130975  ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
130976  assert( SQLITE_PTRSIZE==sizeof(char*) );
130977
130978  /* If SQLite is already completely initialized, then this call
130979  ** to sqlite3_initialize() should be a no-op.  But the initialization
130980  ** must be complete.  So isInit must not be set until the very end
130981  ** of this routine.
130982  */
130983  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
130984
130985  /* Make sure the mutex subsystem is initialized.  If unable to
130986  ** initialize the mutex subsystem, return early with the error.
130987  ** If the system is so sick that we are unable to allocate a mutex,
130988  ** there is not much SQLite is going to be able to do.
130989  **
130990  ** The mutex subsystem must take care of serializing its own
130991  ** initialization.
130992  */
130993  rc = sqlite3MutexInit();
130994  if( rc ) return rc;
130995
130996  /* Initialize the malloc() system and the recursive pInitMutex mutex.
130997  ** This operation is protected by the STATIC_MASTER mutex.  Note that
130998  ** MutexAlloc() is called for a static mutex prior to initializing the
130999  ** malloc subsystem - this implies that the allocation of a static
131000  ** mutex must not require support from the malloc subsystem.
131001  */
131002  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
131003  sqlite3_mutex_enter(pMaster);
131004  sqlite3GlobalConfig.isMutexInit = 1;
131005  if( !sqlite3GlobalConfig.isMallocInit ){
131006    rc = sqlite3MallocInit();
131007  }
131008  if( rc==SQLITE_OK ){
131009    sqlite3GlobalConfig.isMallocInit = 1;
131010    if( !sqlite3GlobalConfig.pInitMutex ){
131011      sqlite3GlobalConfig.pInitMutex =
131012           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
131013      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
131014        rc = SQLITE_NOMEM;
131015      }
131016    }
131017  }
131018  if( rc==SQLITE_OK ){
131019    sqlite3GlobalConfig.nRefInitMutex++;
131020  }
131021  sqlite3_mutex_leave(pMaster);
131022
131023  /* If rc is not SQLITE_OK at this point, then either the malloc
131024  ** subsystem could not be initialized or the system failed to allocate
131025  ** the pInitMutex mutex. Return an error in either case.  */
131026  if( rc!=SQLITE_OK ){
131027    return rc;
131028  }
131029
131030  /* Do the rest of the initialization under the recursive mutex so
131031  ** that we will be able to handle recursive calls into
131032  ** sqlite3_initialize().  The recursive calls normally come through
131033  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
131034  ** recursive calls might also be possible.
131035  **
131036  ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
131037  ** to the xInit method, so the xInit method need not be threadsafe.
131038  **
131039  ** The following mutex is what serializes access to the appdef pcache xInit
131040  ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
131041  ** call to sqlite3PcacheInitialize().
131042  */
131043  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
131044  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
131045    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
131046    sqlite3GlobalConfig.inProgress = 1;
131047    memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
131048    sqlite3RegisterGlobalFunctions();
131049    if( sqlite3GlobalConfig.isPCacheInit==0 ){
131050      rc = sqlite3PcacheInitialize();
131051    }
131052    if( rc==SQLITE_OK ){
131053      sqlite3GlobalConfig.isPCacheInit = 1;
131054      rc = sqlite3OsInit();
131055    }
131056    if( rc==SQLITE_OK ){
131057      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
131058          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
131059      sqlite3GlobalConfig.isInit = 1;
131060#ifdef SQLITE_EXTRA_INIT
131061      bRunExtraInit = 1;
131062#endif
131063    }
131064    sqlite3GlobalConfig.inProgress = 0;
131065  }
131066  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
131067
131068  /* Go back under the static mutex and clean up the recursive
131069  ** mutex to prevent a resource leak.
131070  */
131071  sqlite3_mutex_enter(pMaster);
131072  sqlite3GlobalConfig.nRefInitMutex--;
131073  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
131074    assert( sqlite3GlobalConfig.nRefInitMutex==0 );
131075    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
131076    sqlite3GlobalConfig.pInitMutex = 0;
131077  }
131078  sqlite3_mutex_leave(pMaster);
131079
131080  /* The following is just a sanity check to make sure SQLite has
131081  ** been compiled correctly.  It is important to run this code, but
131082  ** we don't want to run it too often and soak up CPU cycles for no
131083  ** reason.  So we run it once during initialization.
131084  */
131085#ifndef NDEBUG
131086#ifndef SQLITE_OMIT_FLOATING_POINT
131087  /* This section of code's only "output" is via assert() statements. */
131088  if ( rc==SQLITE_OK ){
131089    u64 x = (((u64)1)<<63)-1;
131090    double y;
131091    assert(sizeof(x)==8);
131092    assert(sizeof(x)==sizeof(y));
131093    memcpy(&y, &x, 8);
131094    assert( sqlite3IsNaN(y) );
131095  }
131096#endif
131097#endif
131098
131099  /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
131100  ** compile-time option.
131101  */
131102#ifdef SQLITE_EXTRA_INIT
131103  if( bRunExtraInit ){
131104    int SQLITE_EXTRA_INIT(const char*);
131105    rc = SQLITE_EXTRA_INIT(0);
131106  }
131107#endif
131108
131109  return rc;
131110}
131111
131112/*
131113** Undo the effects of sqlite3_initialize().  Must not be called while
131114** there are outstanding database connections or memory allocations or
131115** while any part of SQLite is otherwise in use in any thread.  This
131116** routine is not threadsafe.  But it is safe to invoke this routine
131117** on when SQLite is already shut down.  If SQLite is already shut down
131118** when this routine is invoked, then this routine is a harmless no-op.
131119*/
131120SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void){
131121#ifdef SQLITE_OMIT_WSD
131122  int rc = sqlite3_wsd_init(4096, 24);
131123  if( rc!=SQLITE_OK ){
131124    return rc;
131125  }
131126#endif
131127
131128  if( sqlite3GlobalConfig.isInit ){
131129#ifdef SQLITE_EXTRA_SHUTDOWN
131130    void SQLITE_EXTRA_SHUTDOWN(void);
131131    SQLITE_EXTRA_SHUTDOWN();
131132#endif
131133    sqlite3_os_end();
131134    sqlite3_reset_auto_extension();
131135    sqlite3GlobalConfig.isInit = 0;
131136  }
131137  if( sqlite3GlobalConfig.isPCacheInit ){
131138    sqlite3PcacheShutdown();
131139    sqlite3GlobalConfig.isPCacheInit = 0;
131140  }
131141  if( sqlite3GlobalConfig.isMallocInit ){
131142    sqlite3MallocEnd();
131143    sqlite3GlobalConfig.isMallocInit = 0;
131144
131145#ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
131146    /* The heap subsystem has now been shutdown and these values are supposed
131147    ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
131148    ** which would rely on that heap subsystem; therefore, make sure these
131149    ** values cannot refer to heap memory that was just invalidated when the
131150    ** heap subsystem was shutdown.  This is only done if the current call to
131151    ** this function resulted in the heap subsystem actually being shutdown.
131152    */
131153    sqlite3_data_directory = 0;
131154    sqlite3_temp_directory = 0;
131155#endif
131156  }
131157  if( sqlite3GlobalConfig.isMutexInit ){
131158    sqlite3MutexEnd();
131159    sqlite3GlobalConfig.isMutexInit = 0;
131160  }
131161
131162  return SQLITE_OK;
131163}
131164
131165/*
131166** This API allows applications to modify the global configuration of
131167** the SQLite library at run-time.
131168**
131169** This routine should only be called when there are no outstanding
131170** database connections or memory allocations.  This routine is not
131171** threadsafe.  Failure to heed these warnings can lead to unpredictable
131172** behavior.
131173*/
131174SQLITE_API int SQLITE_CDECL sqlite3_config(int op, ...){
131175  va_list ap;
131176  int rc = SQLITE_OK;
131177
131178  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
131179  ** the SQLite library is in use. */
131180  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
131181
131182  va_start(ap, op);
131183  switch( op ){
131184
131185    /* Mutex configuration options are only available in a threadsafe
131186    ** compile.
131187    */
131188#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0  /* IMP: R-54466-46756 */
131189    case SQLITE_CONFIG_SINGLETHREAD: {
131190      /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
131191      ** Single-thread. */
131192      sqlite3GlobalConfig.bCoreMutex = 0;  /* Disable mutex on core */
131193      sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
131194      break;
131195    }
131196#endif
131197#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
131198    case SQLITE_CONFIG_MULTITHREAD: {
131199      /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
131200      ** Multi-thread. */
131201      sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
131202      sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
131203      break;
131204    }
131205#endif
131206#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
131207    case SQLITE_CONFIG_SERIALIZED: {
131208      /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
131209      ** Serialized. */
131210      sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
131211      sqlite3GlobalConfig.bFullMutex = 1;  /* Enable mutex on connections */
131212      break;
131213    }
131214#endif
131215#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
131216    case SQLITE_CONFIG_MUTEX: {
131217      /* Specify an alternative mutex implementation */
131218      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
131219      break;
131220    }
131221#endif
131222#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
131223    case SQLITE_CONFIG_GETMUTEX: {
131224      /* Retrieve the current mutex implementation */
131225      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
131226      break;
131227    }
131228#endif
131229
131230    case SQLITE_CONFIG_MALLOC: {
131231      /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
131232      ** single argument which is a pointer to an instance of the
131233      ** sqlite3_mem_methods structure. The argument specifies alternative
131234      ** low-level memory allocation routines to be used in place of the memory
131235      ** allocation routines built into SQLite. */
131236      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
131237      break;
131238    }
131239    case SQLITE_CONFIG_GETMALLOC: {
131240      /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
131241      ** single argument which is a pointer to an instance of the
131242      ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
131243      ** filled with the currently defined memory allocation routines. */
131244      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
131245      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
131246      break;
131247    }
131248    case SQLITE_CONFIG_MEMSTATUS: {
131249      /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
131250      ** single argument of type int, interpreted as a boolean, which enables
131251      ** or disables the collection of memory allocation statistics. */
131252      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
131253      break;
131254    }
131255    case SQLITE_CONFIG_SCRATCH: {
131256      /* EVIDENCE-OF: R-08404-60887 There are three arguments to
131257      ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
131258      ** which the scratch allocations will be drawn, the size of each scratch
131259      ** allocation (sz), and the maximum number of scratch allocations (N). */
131260      sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
131261      sqlite3GlobalConfig.szScratch = va_arg(ap, int);
131262      sqlite3GlobalConfig.nScratch = va_arg(ap, int);
131263      break;
131264    }
131265    case SQLITE_CONFIG_PAGECACHE: {
131266      /* EVIDENCE-OF: R-31408-40510 There are three arguments to
131267      ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory, the size
131268      ** of each page buffer (sz), and the number of pages (N). */
131269      sqlite3GlobalConfig.pPage = va_arg(ap, void*);
131270      sqlite3GlobalConfig.szPage = va_arg(ap, int);
131271      sqlite3GlobalConfig.nPage = va_arg(ap, int);
131272      break;
131273    }
131274    case SQLITE_CONFIG_PCACHE_HDRSZ: {
131275      /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
131276      ** a single parameter which is a pointer to an integer and writes into
131277      ** that integer the number of extra bytes per page required for each page
131278      ** in SQLITE_CONFIG_PAGECACHE. */
131279      *va_arg(ap, int*) =
131280          sqlite3HeaderSizeBtree() +
131281          sqlite3HeaderSizePcache() +
131282          sqlite3HeaderSizePcache1();
131283      break;
131284    }
131285
131286    case SQLITE_CONFIG_PCACHE: {
131287      /* no-op */
131288      break;
131289    }
131290    case SQLITE_CONFIG_GETPCACHE: {
131291      /* now an error */
131292      rc = SQLITE_ERROR;
131293      break;
131294    }
131295
131296    case SQLITE_CONFIG_PCACHE2: {
131297      /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
131298      ** single argument which is a pointer to an sqlite3_pcache_methods2
131299      ** object. This object specifies the interface to a custom page cache
131300      ** implementation. */
131301      sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
131302      break;
131303    }
131304    case SQLITE_CONFIG_GETPCACHE2: {
131305      /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
131306      ** single argument which is a pointer to an sqlite3_pcache_methods2
131307      ** object. SQLite copies of the current page cache implementation into
131308      ** that object. */
131309      if( sqlite3GlobalConfig.pcache2.xInit==0 ){
131310        sqlite3PCacheSetDefault();
131311      }
131312      *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
131313      break;
131314    }
131315
131316/* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
131317** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
131318** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
131319#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
131320    case SQLITE_CONFIG_HEAP: {
131321      /* EVIDENCE-OF: R-19854-42126 There are three arguments to
131322      ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
131323      ** number of bytes in the memory buffer, and the minimum allocation size.
131324      */
131325      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
131326      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
131327      sqlite3GlobalConfig.mnReq = va_arg(ap, int);
131328
131329      if( sqlite3GlobalConfig.mnReq<1 ){
131330        sqlite3GlobalConfig.mnReq = 1;
131331      }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
131332        /* cap min request size at 2^12 */
131333        sqlite3GlobalConfig.mnReq = (1<<12);
131334      }
131335
131336      if( sqlite3GlobalConfig.pHeap==0 ){
131337        /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
131338        ** is NULL, then SQLite reverts to using its default memory allocator
131339        ** (the system malloc() implementation), undoing any prior invocation of
131340        ** SQLITE_CONFIG_MALLOC.
131341        **
131342        ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
131343        ** revert to its default implementation when sqlite3_initialize() is run
131344        */
131345        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
131346      }else{
131347        /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
131348        ** alternative memory allocator is engaged to handle all of SQLites
131349        ** memory allocation needs. */
131350#ifdef SQLITE_ENABLE_MEMSYS3
131351        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
131352#endif
131353#ifdef SQLITE_ENABLE_MEMSYS5
131354        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
131355#endif
131356      }
131357      break;
131358    }
131359#endif
131360
131361    case SQLITE_CONFIG_LOOKASIDE: {
131362      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
131363      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
131364      break;
131365    }
131366
131367    /* Record a pointer to the logger function and its first argument.
131368    ** The default is NULL.  Logging is disabled if the function pointer is
131369    ** NULL.
131370    */
131371    case SQLITE_CONFIG_LOG: {
131372      /* MSVC is picky about pulling func ptrs from va lists.
131373      ** http://support.microsoft.com/kb/47961
131374      ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
131375      */
131376      typedef void(*LOGFUNC_t)(void*,int,const char*);
131377      sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
131378      sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
131379      break;
131380    }
131381
131382    /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
131383    ** can be changed at start-time using the
131384    ** sqlite3_config(SQLITE_CONFIG_URI,1) or
131385    ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
131386    */
131387    case SQLITE_CONFIG_URI: {
131388      /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
131389      ** argument of type int. If non-zero, then URI handling is globally
131390      ** enabled. If the parameter is zero, then URI handling is globally
131391      ** disabled. */
131392      sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
131393      break;
131394    }
131395
131396    case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
131397      /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
131398      ** option takes a single integer argument which is interpreted as a
131399      ** boolean in order to enable or disable the use of covering indices for
131400      ** full table scans in the query optimizer. */
131401      sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
131402      break;
131403    }
131404
131405#ifdef SQLITE_ENABLE_SQLLOG
131406    case SQLITE_CONFIG_SQLLOG: {
131407      typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
131408      sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
131409      sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
131410      break;
131411    }
131412#endif
131413
131414    case SQLITE_CONFIG_MMAP_SIZE: {
131415      /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
131416      ** integer (sqlite3_int64) values that are the default mmap size limit
131417      ** (the default setting for PRAGMA mmap_size) and the maximum allowed
131418      ** mmap size limit. */
131419      sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
131420      sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
131421      /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
131422      ** negative, then that argument is changed to its compile-time default.
131423      **
131424      ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
131425      ** silently truncated if necessary so that it does not exceed the
131426      ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
131427      ** compile-time option.
131428      */
131429      if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
131430        mxMmap = SQLITE_MAX_MMAP_SIZE;
131431      }
131432      if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
131433      if( szMmap>mxMmap) szMmap = mxMmap;
131434      sqlite3GlobalConfig.mxMmap = mxMmap;
131435      sqlite3GlobalConfig.szMmap = szMmap;
131436      break;
131437    }
131438
131439#if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
131440    case SQLITE_CONFIG_WIN32_HEAPSIZE: {
131441      /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
131442      ** unsigned integer value that specifies the maximum size of the created
131443      ** heap. */
131444      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
131445      break;
131446    }
131447#endif
131448
131449    case SQLITE_CONFIG_PMASZ: {
131450      sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
131451      break;
131452    }
131453
131454    default: {
131455      rc = SQLITE_ERROR;
131456      break;
131457    }
131458  }
131459  va_end(ap);
131460  return rc;
131461}
131462
131463/*
131464** Set up the lookaside buffers for a database connection.
131465** Return SQLITE_OK on success.
131466** If lookaside is already active, return SQLITE_BUSY.
131467**
131468** The sz parameter is the number of bytes in each lookaside slot.
131469** The cnt parameter is the number of slots.  If pStart is NULL the
131470** space for the lookaside memory is obtained from sqlite3_malloc().
131471** If pStart is not NULL then it is sz*cnt bytes of memory to use for
131472** the lookaside memory.
131473*/
131474static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
131475#ifndef SQLITE_OMIT_LOOKASIDE
131476  void *pStart;
131477  if( db->lookaside.nOut ){
131478    return SQLITE_BUSY;
131479  }
131480  /* Free any existing lookaside buffer for this handle before
131481  ** allocating a new one so we don't have to have space for
131482  ** both at the same time.
131483  */
131484  if( db->lookaside.bMalloced ){
131485    sqlite3_free(db->lookaside.pStart);
131486  }
131487  /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
131488  ** than a pointer to be useful.
131489  */
131490  sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
131491  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
131492  if( cnt<0 ) cnt = 0;
131493  if( sz==0 || cnt==0 ){
131494    sz = 0;
131495    pStart = 0;
131496  }else if( pBuf==0 ){
131497    sqlite3BeginBenignMalloc();
131498    pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
131499    sqlite3EndBenignMalloc();
131500    if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
131501  }else{
131502    pStart = pBuf;
131503  }
131504  db->lookaside.pStart = pStart;
131505  db->lookaside.pFree = 0;
131506  db->lookaside.sz = (u16)sz;
131507  if( pStart ){
131508    int i;
131509    LookasideSlot *p;
131510    assert( sz > (int)sizeof(LookasideSlot*) );
131511    p = (LookasideSlot*)pStart;
131512    for(i=cnt-1; i>=0; i--){
131513      p->pNext = db->lookaside.pFree;
131514      db->lookaside.pFree = p;
131515      p = (LookasideSlot*)&((u8*)p)[sz];
131516    }
131517    db->lookaside.pEnd = p;
131518    db->lookaside.bEnabled = 1;
131519    db->lookaside.bMalloced = pBuf==0 ?1:0;
131520  }else{
131521    db->lookaside.pStart = db;
131522    db->lookaside.pEnd = db;
131523    db->lookaside.bEnabled = 0;
131524    db->lookaside.bMalloced = 0;
131525  }
131526#endif /* SQLITE_OMIT_LOOKASIDE */
131527  return SQLITE_OK;
131528}
131529
131530/*
131531** Return the mutex associated with a database connection.
131532*/
131533SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3 *db){
131534#ifdef SQLITE_ENABLE_API_ARMOR
131535  if( !sqlite3SafetyCheckOk(db) ){
131536    (void)SQLITE_MISUSE_BKPT;
131537    return 0;
131538  }
131539#endif
131540  return db->mutex;
131541}
131542
131543/*
131544** Free up as much memory as we can from the given database
131545** connection.
131546*/
131547SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3 *db){
131548  int i;
131549
131550#ifdef SQLITE_ENABLE_API_ARMOR
131551  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
131552#endif
131553  sqlite3_mutex_enter(db->mutex);
131554  sqlite3BtreeEnterAll(db);
131555  for(i=0; i<db->nDb; i++){
131556    Btree *pBt = db->aDb[i].pBt;
131557    if( pBt ){
131558      Pager *pPager = sqlite3BtreePager(pBt);
131559      sqlite3PagerShrink(pPager);
131560    }
131561  }
131562  sqlite3BtreeLeaveAll(db);
131563  sqlite3_mutex_leave(db->mutex);
131564  return SQLITE_OK;
131565}
131566
131567/*
131568** Configuration settings for an individual database connection
131569*/
131570SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3 *db, int op, ...){
131571  va_list ap;
131572  int rc;
131573  va_start(ap, op);
131574  switch( op ){
131575    case SQLITE_DBCONFIG_LOOKASIDE: {
131576      void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
131577      int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
131578      int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
131579      rc = setupLookaside(db, pBuf, sz, cnt);
131580      break;
131581    }
131582    default: {
131583      static const struct {
131584        int op;      /* The opcode */
131585        u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
131586      } aFlagOp[] = {
131587        { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
131588        { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
131589      };
131590      unsigned int i;
131591      rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
131592      for(i=0; i<ArraySize(aFlagOp); i++){
131593        if( aFlagOp[i].op==op ){
131594          int onoff = va_arg(ap, int);
131595          int *pRes = va_arg(ap, int*);
131596          int oldFlags = db->flags;
131597          if( onoff>0 ){
131598            db->flags |= aFlagOp[i].mask;
131599          }else if( onoff==0 ){
131600            db->flags &= ~aFlagOp[i].mask;
131601          }
131602          if( oldFlags!=db->flags ){
131603            sqlite3ExpirePreparedStatements(db);
131604          }
131605          if( pRes ){
131606            *pRes = (db->flags & aFlagOp[i].mask)!=0;
131607          }
131608          rc = SQLITE_OK;
131609          break;
131610        }
131611      }
131612      break;
131613    }
131614  }
131615  va_end(ap);
131616  return rc;
131617}
131618
131619
131620/*
131621** Return true if the buffer z[0..n-1] contains all spaces.
131622*/
131623static int allSpaces(const char *z, int n){
131624  while( n>0 && z[n-1]==' ' ){ n--; }
131625  return n==0;
131626}
131627
131628/*
131629** This is the default collating function named "BINARY" which is always
131630** available.
131631**
131632** If the padFlag argument is not NULL then space padding at the end
131633** of strings is ignored.  This implements the RTRIM collation.
131634*/
131635static int binCollFunc(
131636  void *padFlag,
131637  int nKey1, const void *pKey1,
131638  int nKey2, const void *pKey2
131639){
131640  int rc, n;
131641  n = nKey1<nKey2 ? nKey1 : nKey2;
131642  /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
131643  ** strings byte by byte using the memcmp() function from the standard C
131644  ** library. */
131645  rc = memcmp(pKey1, pKey2, n);
131646  if( rc==0 ){
131647    if( padFlag
131648     && allSpaces(((char*)pKey1)+n, nKey1-n)
131649     && allSpaces(((char*)pKey2)+n, nKey2-n)
131650    ){
131651      /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
131652      ** spaces at the end of either string do not change the result. In other
131653      ** words, strings will compare equal to one another as long as they
131654      ** differ only in the number of spaces at the end.
131655      */
131656    }else{
131657      rc = nKey1 - nKey2;
131658    }
131659  }
131660  return rc;
131661}
131662
131663/*
131664** Another built-in collating sequence: NOCASE.
131665**
131666** This collating sequence is intended to be used for "case independent
131667** comparison". SQLite's knowledge of upper and lower case equivalents
131668** extends only to the 26 characters used in the English language.
131669**
131670** At the moment there is only a UTF-8 implementation.
131671*/
131672static int nocaseCollatingFunc(
131673  void *NotUsed,
131674  int nKey1, const void *pKey1,
131675  int nKey2, const void *pKey2
131676){
131677  int r = sqlite3StrNICmp(
131678      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
131679  UNUSED_PARAMETER(NotUsed);
131680  if( 0==r ){
131681    r = nKey1-nKey2;
131682  }
131683  return r;
131684}
131685
131686/*
131687** Return the ROWID of the most recent insert
131688*/
131689SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3 *db){
131690#ifdef SQLITE_ENABLE_API_ARMOR
131691  if( !sqlite3SafetyCheckOk(db) ){
131692    (void)SQLITE_MISUSE_BKPT;
131693    return 0;
131694  }
131695#endif
131696  return db->lastRowid;
131697}
131698
131699/*
131700** Return the number of changes in the most recent call to sqlite3_exec().
131701*/
131702SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3 *db){
131703#ifdef SQLITE_ENABLE_API_ARMOR
131704  if( !sqlite3SafetyCheckOk(db) ){
131705    (void)SQLITE_MISUSE_BKPT;
131706    return 0;
131707  }
131708#endif
131709  return db->nChange;
131710}
131711
131712/*
131713** Return the number of changes since the database handle was opened.
131714*/
131715SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3 *db){
131716#ifdef SQLITE_ENABLE_API_ARMOR
131717  if( !sqlite3SafetyCheckOk(db) ){
131718    (void)SQLITE_MISUSE_BKPT;
131719    return 0;
131720  }
131721#endif
131722  return db->nTotalChange;
131723}
131724
131725/*
131726** Close all open savepoints. This function only manipulates fields of the
131727** database handle object, it does not close any savepoints that may be open
131728** at the b-tree/pager level.
131729*/
131730SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
131731  while( db->pSavepoint ){
131732    Savepoint *pTmp = db->pSavepoint;
131733    db->pSavepoint = pTmp->pNext;
131734    sqlite3DbFree(db, pTmp);
131735  }
131736  db->nSavepoint = 0;
131737  db->nStatement = 0;
131738  db->isTransactionSavepoint = 0;
131739}
131740
131741/*
131742** Invoke the destructor function associated with FuncDef p, if any. Except,
131743** if this is not the last copy of the function, do not invoke it. Multiple
131744** copies of a single function are created when create_function() is called
131745** with SQLITE_ANY as the encoding.
131746*/
131747static void functionDestroy(sqlite3 *db, FuncDef *p){
131748  FuncDestructor *pDestructor = p->pDestructor;
131749  if( pDestructor ){
131750    pDestructor->nRef--;
131751    if( pDestructor->nRef==0 ){
131752      pDestructor->xDestroy(pDestructor->pUserData);
131753      sqlite3DbFree(db, pDestructor);
131754    }
131755  }
131756}
131757
131758/*
131759** Disconnect all sqlite3_vtab objects that belong to database connection
131760** db. This is called when db is being closed.
131761*/
131762static void disconnectAllVtab(sqlite3 *db){
131763#ifndef SQLITE_OMIT_VIRTUALTABLE
131764  int i;
131765  HashElem *p;
131766  sqlite3BtreeEnterAll(db);
131767  for(i=0; i<db->nDb; i++){
131768    Schema *pSchema = db->aDb[i].pSchema;
131769    if( db->aDb[i].pSchema ){
131770      for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
131771        Table *pTab = (Table *)sqliteHashData(p);
131772        if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
131773      }
131774    }
131775  }
131776  for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
131777    Module *pMod = (Module *)sqliteHashData(p);
131778    if( pMod->pEpoTab ){
131779      sqlite3VtabDisconnect(db, pMod->pEpoTab);
131780    }
131781  }
131782  sqlite3VtabUnlockList(db);
131783  sqlite3BtreeLeaveAll(db);
131784#else
131785  UNUSED_PARAMETER(db);
131786#endif
131787}
131788
131789/*
131790** Return TRUE if database connection db has unfinalized prepared
131791** statements or unfinished sqlite3_backup objects.
131792*/
131793static int connectionIsBusy(sqlite3 *db){
131794  int j;
131795  assert( sqlite3_mutex_held(db->mutex) );
131796  if( db->pVdbe ) return 1;
131797  for(j=0; j<db->nDb; j++){
131798    Btree *pBt = db->aDb[j].pBt;
131799    if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
131800  }
131801  return 0;
131802}
131803
131804/*
131805** Close an existing SQLite database
131806*/
131807static int sqlite3Close(sqlite3 *db, int forceZombie){
131808  if( !db ){
131809    /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
131810    ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
131811    return SQLITE_OK;
131812  }
131813  if( !sqlite3SafetyCheckSickOrOk(db) ){
131814    return SQLITE_MISUSE_BKPT;
131815  }
131816  sqlite3_mutex_enter(db->mutex);
131817
131818  /* Force xDisconnect calls on all virtual tables */
131819  disconnectAllVtab(db);
131820
131821  /* If a transaction is open, the disconnectAllVtab() call above
131822  ** will not have called the xDisconnect() method on any virtual
131823  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
131824  ** call will do so. We need to do this before the check for active
131825  ** SQL statements below, as the v-table implementation may be storing
131826  ** some prepared statements internally.
131827  */
131828  sqlite3VtabRollback(db);
131829
131830  /* Legacy behavior (sqlite3_close() behavior) is to return
131831  ** SQLITE_BUSY if the connection can not be closed immediately.
131832  */
131833  if( !forceZombie && connectionIsBusy(db) ){
131834    sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
131835       "statements or unfinished backups");
131836    sqlite3_mutex_leave(db->mutex);
131837    return SQLITE_BUSY;
131838  }
131839
131840#ifdef SQLITE_ENABLE_SQLLOG
131841  if( sqlite3GlobalConfig.xSqllog ){
131842    /* Closing the handle. Fourth parameter is passed the value 2. */
131843    sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
131844  }
131845#endif
131846
131847  /* Convert the connection into a zombie and then close it.
131848  */
131849  db->magic = SQLITE_MAGIC_ZOMBIE;
131850  sqlite3LeaveMutexAndCloseZombie(db);
131851  return SQLITE_OK;
131852}
131853
131854/*
131855** Two variations on the public interface for closing a database
131856** connection. The sqlite3_close() version returns SQLITE_BUSY and
131857** leaves the connection option if there are unfinalized prepared
131858** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
131859** version forces the connection to become a zombie if there are
131860** unclosed resources, and arranges for deallocation when the last
131861** prepare statement or sqlite3_backup closes.
131862*/
131863SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
131864SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
131865
131866
131867/*
131868** Close the mutex on database connection db.
131869**
131870** Furthermore, if database connection db is a zombie (meaning that there
131871** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
131872** every sqlite3_stmt has now been finalized and every sqlite3_backup has
131873** finished, then free all resources.
131874*/
131875SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
131876  HashElem *i;                    /* Hash table iterator */
131877  int j;
131878
131879  /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
131880  ** or if the connection has not yet been closed by sqlite3_close_v2(),
131881  ** then just leave the mutex and return.
131882  */
131883  if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
131884    sqlite3_mutex_leave(db->mutex);
131885    return;
131886  }
131887
131888  /* If we reach this point, it means that the database connection has
131889  ** closed all sqlite3_stmt and sqlite3_backup objects and has been
131890  ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
131891  ** go ahead and free all resources.
131892  */
131893
131894  /* If a transaction is open, roll it back. This also ensures that if
131895  ** any database schemas have been modified by an uncommitted transaction
131896  ** they are reset. And that the required b-tree mutex is held to make
131897  ** the pager rollback and schema reset an atomic operation. */
131898  sqlite3RollbackAll(db, SQLITE_OK);
131899
131900  /* Free any outstanding Savepoint structures. */
131901  sqlite3CloseSavepoints(db);
131902
131903  /* Close all database connections */
131904  for(j=0; j<db->nDb; j++){
131905    struct Db *pDb = &db->aDb[j];
131906    if( pDb->pBt ){
131907      sqlite3BtreeClose(pDb->pBt);
131908      pDb->pBt = 0;
131909      if( j!=1 ){
131910        pDb->pSchema = 0;
131911      }
131912    }
131913  }
131914  /* Clear the TEMP schema separately and last */
131915  if( db->aDb[1].pSchema ){
131916    sqlite3SchemaClear(db->aDb[1].pSchema);
131917  }
131918  sqlite3VtabUnlockList(db);
131919
131920  /* Free up the array of auxiliary databases */
131921  sqlite3CollapseDatabaseArray(db);
131922  assert( db->nDb<=2 );
131923  assert( db->aDb==db->aDbStatic );
131924
131925  /* Tell the code in notify.c that the connection no longer holds any
131926  ** locks and does not require any further unlock-notify callbacks.
131927  */
131928  sqlite3ConnectionClosed(db);
131929
131930  for(j=0; j<ArraySize(db->aFunc.a); j++){
131931    FuncDef *pNext, *pHash, *p;
131932    for(p=db->aFunc.a[j]; p; p=pHash){
131933      pHash = p->pHash;
131934      while( p ){
131935        functionDestroy(db, p);
131936        pNext = p->pNext;
131937        sqlite3DbFree(db, p);
131938        p = pNext;
131939      }
131940    }
131941  }
131942  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
131943    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
131944    /* Invoke any destructors registered for collation sequence user data. */
131945    for(j=0; j<3; j++){
131946      if( pColl[j].xDel ){
131947        pColl[j].xDel(pColl[j].pUser);
131948      }
131949    }
131950    sqlite3DbFree(db, pColl);
131951  }
131952  sqlite3HashClear(&db->aCollSeq);
131953#ifndef SQLITE_OMIT_VIRTUALTABLE
131954  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
131955    Module *pMod = (Module *)sqliteHashData(i);
131956    if( pMod->xDestroy ){
131957      pMod->xDestroy(pMod->pAux);
131958    }
131959    sqlite3VtabEponymousTableClear(db, pMod);
131960    sqlite3DbFree(db, pMod);
131961  }
131962  sqlite3HashClear(&db->aModule);
131963#endif
131964
131965  sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
131966  sqlite3ValueFree(db->pErr);
131967  sqlite3CloseExtensions(db);
131968#if SQLITE_USER_AUTHENTICATION
131969  sqlite3_free(db->auth.zAuthUser);
131970  sqlite3_free(db->auth.zAuthPW);
131971#endif
131972
131973  db->magic = SQLITE_MAGIC_ERROR;
131974
131975  /* The temp-database schema is allocated differently from the other schema
131976  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
131977  ** So it needs to be freed here. Todo: Why not roll the temp schema into
131978  ** the same sqliteMalloc() as the one that allocates the database
131979  ** structure?
131980  */
131981  sqlite3DbFree(db, db->aDb[1].pSchema);
131982  sqlite3_mutex_leave(db->mutex);
131983  db->magic = SQLITE_MAGIC_CLOSED;
131984  sqlite3_mutex_free(db->mutex);
131985  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
131986  if( db->lookaside.bMalloced ){
131987    sqlite3_free(db->lookaside.pStart);
131988  }
131989  sqlite3_free(db);
131990}
131991
131992/*
131993** Rollback all database files.  If tripCode is not SQLITE_OK, then
131994** any write cursors are invalidated ("tripped" - as in "tripping a circuit
131995** breaker") and made to return tripCode if there are any further
131996** attempts to use that cursor.  Read cursors remain open and valid
131997** but are "saved" in case the table pages are moved around.
131998*/
131999SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
132000  int i;
132001  int inTrans = 0;
132002  int schemaChange;
132003  assert( sqlite3_mutex_held(db->mutex) );
132004  sqlite3BeginBenignMalloc();
132005
132006  /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
132007  ** This is important in case the transaction being rolled back has
132008  ** modified the database schema. If the b-tree mutexes are not taken
132009  ** here, then another shared-cache connection might sneak in between
132010  ** the database rollback and schema reset, which can cause false
132011  ** corruption reports in some cases.  */
132012  sqlite3BtreeEnterAll(db);
132013  schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
132014
132015  for(i=0; i<db->nDb; i++){
132016    Btree *p = db->aDb[i].pBt;
132017    if( p ){
132018      if( sqlite3BtreeIsInTrans(p) ){
132019        inTrans = 1;
132020      }
132021      sqlite3BtreeRollback(p, tripCode, !schemaChange);
132022    }
132023  }
132024  sqlite3VtabRollback(db);
132025  sqlite3EndBenignMalloc();
132026
132027  if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
132028    sqlite3ExpirePreparedStatements(db);
132029    sqlite3ResetAllSchemasOfConnection(db);
132030  }
132031  sqlite3BtreeLeaveAll(db);
132032
132033  /* Any deferred constraint violations have now been resolved. */
132034  db->nDeferredCons = 0;
132035  db->nDeferredImmCons = 0;
132036  db->flags &= ~SQLITE_DeferFKs;
132037
132038  /* If one has been configured, invoke the rollback-hook callback */
132039  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
132040    db->xRollbackCallback(db->pRollbackArg);
132041  }
132042}
132043
132044/*
132045** Return a static string containing the name corresponding to the error code
132046** specified in the argument.
132047*/
132048#if defined(SQLITE_NEED_ERR_NAME)
132049SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
132050  const char *zName = 0;
132051  int i, origRc = rc;
132052  for(i=0; i<2 && zName==0; i++, rc &= 0xff){
132053    switch( rc ){
132054      case SQLITE_OK:                 zName = "SQLITE_OK";                break;
132055      case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
132056      case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
132057      case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
132058      case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
132059      case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
132060      case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
132061      case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
132062      case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
132063      case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
132064      case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
132065      case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
132066      case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
132067      case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
132068      case SQLITE_READONLY_CANTLOCK:  zName = "SQLITE_READONLY_CANTLOCK"; break;
132069      case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
132070      case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
132071      case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
132072      case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
132073      case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
132074      case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
132075      case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
132076      case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
132077      case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
132078      case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
132079      case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
132080      case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
132081      case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
132082      case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
132083      case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
132084      case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
132085      case SQLITE_IOERR_CHECKRESERVEDLOCK:
132086                                zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
132087      case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
132088      case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
132089      case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
132090      case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
132091      case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
132092      case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
132093      case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
132094      case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
132095      case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
132096      case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
132097      case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
132098      case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
132099      case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
132100      case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
132101      case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
132102      case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
132103      case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
132104      case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
132105      case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
132106      case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
132107      case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
132108      case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
132109      case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
132110      case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
132111      case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
132112      case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
132113      case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
132114      case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
132115      case SQLITE_CONSTRAINT_FOREIGNKEY:
132116                                zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
132117      case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
132118      case SQLITE_CONSTRAINT_PRIMARYKEY:
132119                                zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
132120      case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
132121      case SQLITE_CONSTRAINT_COMMITHOOK:
132122                                zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
132123      case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
132124      case SQLITE_CONSTRAINT_FUNCTION:
132125                                zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
132126      case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
132127      case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
132128      case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
132129      case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
132130      case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
132131      case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
132132      case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
132133      case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
132134      case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
132135      case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
132136      case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
132137      case SQLITE_NOTICE_RECOVER_ROLLBACK:
132138                                zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
132139      case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
132140      case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
132141      case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
132142    }
132143  }
132144  if( zName==0 ){
132145    static char zBuf[50];
132146    sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
132147    zName = zBuf;
132148  }
132149  return zName;
132150}
132151#endif
132152
132153/*
132154** Return a static string that describes the kind of error specified in the
132155** argument.
132156*/
132157SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
132158  static const char* const aMsg[] = {
132159    /* SQLITE_OK          */ "not an error",
132160    /* SQLITE_ERROR       */ "SQL logic error or missing database",
132161    /* SQLITE_INTERNAL    */ 0,
132162    /* SQLITE_PERM        */ "access permission denied",
132163    /* SQLITE_ABORT       */ "callback requested query abort",
132164    /* SQLITE_BUSY        */ "database is locked",
132165    /* SQLITE_LOCKED      */ "database table is locked",
132166    /* SQLITE_NOMEM       */ "out of memory",
132167    /* SQLITE_READONLY    */ "attempt to write a readonly database",
132168    /* SQLITE_INTERRUPT   */ "interrupted",
132169    /* SQLITE_IOERR       */ "disk I/O error",
132170    /* SQLITE_CORRUPT     */ "database disk image is malformed",
132171    /* SQLITE_NOTFOUND    */ "unknown operation",
132172    /* SQLITE_FULL        */ "database or disk is full",
132173    /* SQLITE_CANTOPEN    */ "unable to open database file",
132174    /* SQLITE_PROTOCOL    */ "locking protocol",
132175    /* SQLITE_EMPTY       */ "table contains no data",
132176    /* SQLITE_SCHEMA      */ "database schema has changed",
132177    /* SQLITE_TOOBIG      */ "string or blob too big",
132178    /* SQLITE_CONSTRAINT  */ "constraint failed",
132179    /* SQLITE_MISMATCH    */ "datatype mismatch",
132180    /* SQLITE_MISUSE      */ "library routine called out of sequence",
132181    /* SQLITE_NOLFS       */ "large file support is disabled",
132182    /* SQLITE_AUTH        */ "authorization denied",
132183    /* SQLITE_FORMAT      */ "auxiliary database format error",
132184    /* SQLITE_RANGE       */ "bind or column index out of range",
132185    /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
132186  };
132187  const char *zErr = "unknown error";
132188  switch( rc ){
132189    case SQLITE_ABORT_ROLLBACK: {
132190      zErr = "abort due to ROLLBACK";
132191      break;
132192    }
132193    default: {
132194      rc &= 0xff;
132195      if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
132196        zErr = aMsg[rc];
132197      }
132198      break;
132199    }
132200  }
132201  return zErr;
132202}
132203
132204/*
132205** This routine implements a busy callback that sleeps and tries
132206** again until a timeout value is reached.  The timeout value is
132207** an integer number of milliseconds passed in as the first
132208** argument.
132209*/
132210static int sqliteDefaultBusyCallback(
132211 void *ptr,               /* Database connection */
132212 int count                /* Number of times table has been busy */
132213){
132214#if SQLITE_OS_WIN || HAVE_USLEEP
132215  static const u8 delays[] =
132216     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
132217  static const u8 totals[] =
132218     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
132219# define NDELAY ArraySize(delays)
132220  sqlite3 *db = (sqlite3 *)ptr;
132221  int timeout = db->busyTimeout;
132222  int delay, prior;
132223
132224  assert( count>=0 );
132225  if( count < NDELAY ){
132226    delay = delays[count];
132227    prior = totals[count];
132228  }else{
132229    delay = delays[NDELAY-1];
132230    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
132231  }
132232  if( prior + delay > timeout ){
132233    delay = timeout - prior;
132234    if( delay<=0 ) return 0;
132235  }
132236  sqlite3OsSleep(db->pVfs, delay*1000);
132237  return 1;
132238#else
132239  sqlite3 *db = (sqlite3 *)ptr;
132240  int timeout = ((sqlite3 *)ptr)->busyTimeout;
132241  if( (count+1)*1000 > timeout ){
132242    return 0;
132243  }
132244  sqlite3OsSleep(db->pVfs, 1000000);
132245  return 1;
132246#endif
132247}
132248
132249/*
132250** Invoke the given busy handler.
132251**
132252** This routine is called when an operation failed with a lock.
132253** If this routine returns non-zero, the lock is retried.  If it
132254** returns 0, the operation aborts with an SQLITE_BUSY error.
132255*/
132256SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
132257  int rc;
132258  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
132259  rc = p->xFunc(p->pArg, p->nBusy);
132260  if( rc==0 ){
132261    p->nBusy = -1;
132262  }else{
132263    p->nBusy++;
132264  }
132265  return rc;
132266}
132267
132268/*
132269** This routine sets the busy callback for an Sqlite database to the
132270** given callback function with the given argument.
132271*/
132272SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(
132273  sqlite3 *db,
132274  int (*xBusy)(void*,int),
132275  void *pArg
132276){
132277#ifdef SQLITE_ENABLE_API_ARMOR
132278  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
132279#endif
132280  sqlite3_mutex_enter(db->mutex);
132281  db->busyHandler.xFunc = xBusy;
132282  db->busyHandler.pArg = pArg;
132283  db->busyHandler.nBusy = 0;
132284  db->busyTimeout = 0;
132285  sqlite3_mutex_leave(db->mutex);
132286  return SQLITE_OK;
132287}
132288
132289#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
132290/*
132291** This routine sets the progress callback for an Sqlite database to the
132292** given callback function with the given argument. The progress callback will
132293** be invoked every nOps opcodes.
132294*/
132295SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(
132296  sqlite3 *db,
132297  int nOps,
132298  int (*xProgress)(void*),
132299  void *pArg
132300){
132301#ifdef SQLITE_ENABLE_API_ARMOR
132302  if( !sqlite3SafetyCheckOk(db) ){
132303    (void)SQLITE_MISUSE_BKPT;
132304    return;
132305  }
132306#endif
132307  sqlite3_mutex_enter(db->mutex);
132308  if( nOps>0 ){
132309    db->xProgress = xProgress;
132310    db->nProgressOps = (unsigned)nOps;
132311    db->pProgressArg = pArg;
132312  }else{
132313    db->xProgress = 0;
132314    db->nProgressOps = 0;
132315    db->pProgressArg = 0;
132316  }
132317  sqlite3_mutex_leave(db->mutex);
132318}
132319#endif
132320
132321
132322/*
132323** This routine installs a default busy handler that waits for the
132324** specified number of milliseconds before returning 0.
132325*/
132326SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3 *db, int ms){
132327#ifdef SQLITE_ENABLE_API_ARMOR
132328  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
132329#endif
132330  if( ms>0 ){
132331    sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
132332    db->busyTimeout = ms;
132333  }else{
132334    sqlite3_busy_handler(db, 0, 0);
132335  }
132336  return SQLITE_OK;
132337}
132338
132339/*
132340** Cause any pending operation to stop at its earliest opportunity.
132341*/
132342SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3 *db){
132343#ifdef SQLITE_ENABLE_API_ARMOR
132344  if( !sqlite3SafetyCheckOk(db) ){
132345    (void)SQLITE_MISUSE_BKPT;
132346    return;
132347  }
132348#endif
132349  db->u1.isInterrupted = 1;
132350}
132351
132352
132353/*
132354** This function is exactly the same as sqlite3_create_function(), except
132355** that it is designed to be called by internal code. The difference is
132356** that if a malloc() fails in sqlite3_create_function(), an error code
132357** is returned and the mallocFailed flag cleared.
132358*/
132359SQLITE_PRIVATE int sqlite3CreateFunc(
132360  sqlite3 *db,
132361  const char *zFunctionName,
132362  int nArg,
132363  int enc,
132364  void *pUserData,
132365  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
132366  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
132367  void (*xFinal)(sqlite3_context*),
132368  FuncDestructor *pDestructor
132369){
132370  FuncDef *p;
132371  int nName;
132372  int extraFlags;
132373
132374  assert( sqlite3_mutex_held(db->mutex) );
132375  if( zFunctionName==0 ||
132376      (xFunc && (xFinal || xStep)) ||
132377      (!xFunc && (xFinal && !xStep)) ||
132378      (!xFunc && (!xFinal && xStep)) ||
132379      (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
132380      (255<(nName = sqlite3Strlen30( zFunctionName))) ){
132381    return SQLITE_MISUSE_BKPT;
132382  }
132383
132384  assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
132385  extraFlags = enc &  SQLITE_DETERMINISTIC;
132386  enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
132387
132388#ifndef SQLITE_OMIT_UTF16
132389  /* If SQLITE_UTF16 is specified as the encoding type, transform this
132390  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
132391  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
132392  **
132393  ** If SQLITE_ANY is specified, add three versions of the function
132394  ** to the hash table.
132395  */
132396  if( enc==SQLITE_UTF16 ){
132397    enc = SQLITE_UTF16NATIVE;
132398  }else if( enc==SQLITE_ANY ){
132399    int rc;
132400    rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
132401         pUserData, xFunc, xStep, xFinal, pDestructor);
132402    if( rc==SQLITE_OK ){
132403      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
132404          pUserData, xFunc, xStep, xFinal, pDestructor);
132405    }
132406    if( rc!=SQLITE_OK ){
132407      return rc;
132408    }
132409    enc = SQLITE_UTF16BE;
132410  }
132411#else
132412  enc = SQLITE_UTF8;
132413#endif
132414
132415  /* Check if an existing function is being overridden or deleted. If so,
132416  ** and there are active VMs, then return SQLITE_BUSY. If a function
132417  ** is being overridden/deleted but there are no active VMs, allow the
132418  ** operation to continue but invalidate all precompiled statements.
132419  */
132420  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
132421  if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
132422    if( db->nVdbeActive ){
132423      sqlite3ErrorWithMsg(db, SQLITE_BUSY,
132424        "unable to delete/modify user-function due to active statements");
132425      assert( !db->mallocFailed );
132426      return SQLITE_BUSY;
132427    }else{
132428      sqlite3ExpirePreparedStatements(db);
132429    }
132430  }
132431
132432  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
132433  assert(p || db->mallocFailed);
132434  if( !p ){
132435    return SQLITE_NOMEM;
132436  }
132437
132438  /* If an older version of the function with a configured destructor is
132439  ** being replaced invoke the destructor function here. */
132440  functionDestroy(db, p);
132441
132442  if( pDestructor ){
132443    pDestructor->nRef++;
132444  }
132445  p->pDestructor = pDestructor;
132446  p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
132447  testcase( p->funcFlags & SQLITE_DETERMINISTIC );
132448  p->xFunc = xFunc;
132449  p->xStep = xStep;
132450  p->xFinalize = xFinal;
132451  p->pUserData = pUserData;
132452  p->nArg = (u16)nArg;
132453  return SQLITE_OK;
132454}
132455
132456/*
132457** Create new user functions.
132458*/
132459SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
132460  sqlite3 *db,
132461  const char *zFunc,
132462  int nArg,
132463  int enc,
132464  void *p,
132465  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
132466  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
132467  void (*xFinal)(sqlite3_context*)
132468){
132469  return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
132470                                    xFinal, 0);
132471}
132472
132473SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
132474  sqlite3 *db,
132475  const char *zFunc,
132476  int nArg,
132477  int enc,
132478  void *p,
132479  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
132480  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
132481  void (*xFinal)(sqlite3_context*),
132482  void (*xDestroy)(void *)
132483){
132484  int rc = SQLITE_ERROR;
132485  FuncDestructor *pArg = 0;
132486
132487#ifdef SQLITE_ENABLE_API_ARMOR
132488  if( !sqlite3SafetyCheckOk(db) ){
132489    return SQLITE_MISUSE_BKPT;
132490  }
132491#endif
132492  sqlite3_mutex_enter(db->mutex);
132493  if( xDestroy ){
132494    pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
132495    if( !pArg ){
132496      xDestroy(p);
132497      goto out;
132498    }
132499    pArg->xDestroy = xDestroy;
132500    pArg->pUserData = p;
132501  }
132502  rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
132503  if( pArg && pArg->nRef==0 ){
132504    assert( rc!=SQLITE_OK );
132505    xDestroy(p);
132506    sqlite3DbFree(db, pArg);
132507  }
132508
132509 out:
132510  rc = sqlite3ApiExit(db, rc);
132511  sqlite3_mutex_leave(db->mutex);
132512  return rc;
132513}
132514
132515#ifndef SQLITE_OMIT_UTF16
132516SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
132517  sqlite3 *db,
132518  const void *zFunctionName,
132519  int nArg,
132520  int eTextRep,
132521  void *p,
132522  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
132523  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
132524  void (*xFinal)(sqlite3_context*)
132525){
132526  int rc;
132527  char *zFunc8;
132528
132529#ifdef SQLITE_ENABLE_API_ARMOR
132530  if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
132531#endif
132532  sqlite3_mutex_enter(db->mutex);
132533  assert( !db->mallocFailed );
132534  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
132535  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
132536  sqlite3DbFree(db, zFunc8);
132537  rc = sqlite3ApiExit(db, rc);
132538  sqlite3_mutex_leave(db->mutex);
132539  return rc;
132540}
132541#endif
132542
132543
132544/*
132545** Declare that a function has been overloaded by a virtual table.
132546**
132547** If the function already exists as a regular global function, then
132548** this routine is a no-op.  If the function does not exist, then create
132549** a new one that always throws a run-time error.
132550**
132551** When virtual tables intend to provide an overloaded function, they
132552** should call this routine to make sure the global function exists.
132553** A global function must exist in order for name resolution to work
132554** properly.
132555*/
132556SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(
132557  sqlite3 *db,
132558  const char *zName,
132559  int nArg
132560){
132561  int nName = sqlite3Strlen30(zName);
132562  int rc = SQLITE_OK;
132563
132564#ifdef SQLITE_ENABLE_API_ARMOR
132565  if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
132566    return SQLITE_MISUSE_BKPT;
132567  }
132568#endif
132569  sqlite3_mutex_enter(db->mutex);
132570  if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
132571    rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
132572                           0, sqlite3InvalidFunction, 0, 0, 0);
132573  }
132574  rc = sqlite3ApiExit(db, rc);
132575  sqlite3_mutex_leave(db->mutex);
132576  return rc;
132577}
132578
132579#ifndef SQLITE_OMIT_TRACE
132580/*
132581** Register a trace function.  The pArg from the previously registered trace
132582** is returned.
132583**
132584** A NULL trace function means that no tracing is executes.  A non-NULL
132585** trace is a pointer to a function that is invoked at the start of each
132586** SQL statement.
132587*/
132588SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
132589  void *pOld;
132590
132591#ifdef SQLITE_ENABLE_API_ARMOR
132592  if( !sqlite3SafetyCheckOk(db) ){
132593    (void)SQLITE_MISUSE_BKPT;
132594    return 0;
132595  }
132596#endif
132597  sqlite3_mutex_enter(db->mutex);
132598  pOld = db->pTraceArg;
132599  db->xTrace = xTrace;
132600  db->pTraceArg = pArg;
132601  sqlite3_mutex_leave(db->mutex);
132602  return pOld;
132603}
132604/*
132605** Register a profile function.  The pArg from the previously registered
132606** profile function is returned.
132607**
132608** A NULL profile function means that no profiling is executes.  A non-NULL
132609** profile is a pointer to a function that is invoked at the conclusion of
132610** each SQL statement that is run.
132611*/
132612SQLITE_API void *SQLITE_STDCALL sqlite3_profile(
132613  sqlite3 *db,
132614  void (*xProfile)(void*,const char*,sqlite_uint64),
132615  void *pArg
132616){
132617  void *pOld;
132618
132619#ifdef SQLITE_ENABLE_API_ARMOR
132620  if( !sqlite3SafetyCheckOk(db) ){
132621    (void)SQLITE_MISUSE_BKPT;
132622    return 0;
132623  }
132624#endif
132625  sqlite3_mutex_enter(db->mutex);
132626  pOld = db->pProfileArg;
132627  db->xProfile = xProfile;
132628  db->pProfileArg = pArg;
132629  sqlite3_mutex_leave(db->mutex);
132630  return pOld;
132631}
132632#endif /* SQLITE_OMIT_TRACE */
132633
132634/*
132635** Register a function to be invoked when a transaction commits.
132636** If the invoked function returns non-zero, then the commit becomes a
132637** rollback.
132638*/
132639SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(
132640  sqlite3 *db,              /* Attach the hook to this database */
132641  int (*xCallback)(void*),  /* Function to invoke on each commit */
132642  void *pArg                /* Argument to the function */
132643){
132644  void *pOld;
132645
132646#ifdef SQLITE_ENABLE_API_ARMOR
132647  if( !sqlite3SafetyCheckOk(db) ){
132648    (void)SQLITE_MISUSE_BKPT;
132649    return 0;
132650  }
132651#endif
132652  sqlite3_mutex_enter(db->mutex);
132653  pOld = db->pCommitArg;
132654  db->xCommitCallback = xCallback;
132655  db->pCommitArg = pArg;
132656  sqlite3_mutex_leave(db->mutex);
132657  return pOld;
132658}
132659
132660/*
132661** Register a callback to be invoked each time a row is updated,
132662** inserted or deleted using this database connection.
132663*/
132664SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
132665  sqlite3 *db,              /* Attach the hook to this database */
132666  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
132667  void *pArg                /* Argument to the function */
132668){
132669  void *pRet;
132670
132671#ifdef SQLITE_ENABLE_API_ARMOR
132672  if( !sqlite3SafetyCheckOk(db) ){
132673    (void)SQLITE_MISUSE_BKPT;
132674    return 0;
132675  }
132676#endif
132677  sqlite3_mutex_enter(db->mutex);
132678  pRet = db->pUpdateArg;
132679  db->xUpdateCallback = xCallback;
132680  db->pUpdateArg = pArg;
132681  sqlite3_mutex_leave(db->mutex);
132682  return pRet;
132683}
132684
132685/*
132686** Register a callback to be invoked each time a transaction is rolled
132687** back by this database connection.
132688*/
132689SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(
132690  sqlite3 *db,              /* Attach the hook to this database */
132691  void (*xCallback)(void*), /* Callback function */
132692  void *pArg                /* Argument to the function */
132693){
132694  void *pRet;
132695
132696#ifdef SQLITE_ENABLE_API_ARMOR
132697  if( !sqlite3SafetyCheckOk(db) ){
132698    (void)SQLITE_MISUSE_BKPT;
132699    return 0;
132700  }
132701#endif
132702  sqlite3_mutex_enter(db->mutex);
132703  pRet = db->pRollbackArg;
132704  db->xRollbackCallback = xCallback;
132705  db->pRollbackArg = pArg;
132706  sqlite3_mutex_leave(db->mutex);
132707  return pRet;
132708}
132709
132710#ifndef SQLITE_OMIT_WAL
132711/*
132712** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
132713** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
132714** is greater than sqlite3.pWalArg cast to an integer (the value configured by
132715** wal_autocheckpoint()).
132716*/
132717SQLITE_PRIVATE int sqlite3WalDefaultHook(
132718  void *pClientData,     /* Argument */
132719  sqlite3 *db,           /* Connection */
132720  const char *zDb,       /* Database */
132721  int nFrame             /* Size of WAL */
132722){
132723  if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
132724    sqlite3BeginBenignMalloc();
132725    sqlite3_wal_checkpoint(db, zDb);
132726    sqlite3EndBenignMalloc();
132727  }
132728  return SQLITE_OK;
132729}
132730#endif /* SQLITE_OMIT_WAL */
132731
132732/*
132733** Configure an sqlite3_wal_hook() callback to automatically checkpoint
132734** a database after committing a transaction if there are nFrame or
132735** more frames in the log file. Passing zero or a negative value as the
132736** nFrame parameter disables automatic checkpoints entirely.
132737**
132738** The callback registered by this function replaces any existing callback
132739** registered using sqlite3_wal_hook(). Likewise, registering a callback
132740** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
132741** configured by this function.
132742*/
132743SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
132744#ifdef SQLITE_OMIT_WAL
132745  UNUSED_PARAMETER(db);
132746  UNUSED_PARAMETER(nFrame);
132747#else
132748#ifdef SQLITE_ENABLE_API_ARMOR
132749  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
132750#endif
132751  if( nFrame>0 ){
132752    sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
132753  }else{
132754    sqlite3_wal_hook(db, 0, 0);
132755  }
132756#endif
132757  return SQLITE_OK;
132758}
132759
132760/*
132761** Register a callback to be invoked each time a transaction is written
132762** into the write-ahead-log by this database connection.
132763*/
132764SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
132765  sqlite3 *db,                    /* Attach the hook to this db handle */
132766  int(*xCallback)(void *, sqlite3*, const char*, int),
132767  void *pArg                      /* First argument passed to xCallback() */
132768){
132769#ifndef SQLITE_OMIT_WAL
132770  void *pRet;
132771#ifdef SQLITE_ENABLE_API_ARMOR
132772  if( !sqlite3SafetyCheckOk(db) ){
132773    (void)SQLITE_MISUSE_BKPT;
132774    return 0;
132775  }
132776#endif
132777  sqlite3_mutex_enter(db->mutex);
132778  pRet = db->pWalArg;
132779  db->xWalCallback = xCallback;
132780  db->pWalArg = pArg;
132781  sqlite3_mutex_leave(db->mutex);
132782  return pRet;
132783#else
132784  return 0;
132785#endif
132786}
132787
132788/*
132789** Checkpoint database zDb.
132790*/
132791SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
132792  sqlite3 *db,                    /* Database handle */
132793  const char *zDb,                /* Name of attached database (or NULL) */
132794  int eMode,                      /* SQLITE_CHECKPOINT_* value */
132795  int *pnLog,                     /* OUT: Size of WAL log in frames */
132796  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
132797){
132798#ifdef SQLITE_OMIT_WAL
132799  return SQLITE_OK;
132800#else
132801  int rc;                         /* Return code */
132802  int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
132803
132804#ifdef SQLITE_ENABLE_API_ARMOR
132805  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
132806#endif
132807
132808  /* Initialize the output variables to -1 in case an error occurs. */
132809  if( pnLog ) *pnLog = -1;
132810  if( pnCkpt ) *pnCkpt = -1;
132811
132812  assert( SQLITE_CHECKPOINT_PASSIVE==0 );
132813  assert( SQLITE_CHECKPOINT_FULL==1 );
132814  assert( SQLITE_CHECKPOINT_RESTART==2 );
132815  assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
132816  if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
132817    /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
132818    ** mode: */
132819    return SQLITE_MISUSE;
132820  }
132821
132822  sqlite3_mutex_enter(db->mutex);
132823  if( zDb && zDb[0] ){
132824    iDb = sqlite3FindDbName(db, zDb);
132825  }
132826  if( iDb<0 ){
132827    rc = SQLITE_ERROR;
132828    sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
132829  }else{
132830    db->busyHandler.nBusy = 0;
132831    rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
132832    sqlite3Error(db, rc);
132833  }
132834  rc = sqlite3ApiExit(db, rc);
132835  sqlite3_mutex_leave(db->mutex);
132836  return rc;
132837#endif
132838}
132839
132840
132841/*
132842** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
132843** to contains a zero-length string, all attached databases are
132844** checkpointed.
132845*/
132846SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
132847  /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
132848  ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
132849  return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
132850}
132851
132852#ifndef SQLITE_OMIT_WAL
132853/*
132854** Run a checkpoint on database iDb. This is a no-op if database iDb is
132855** not currently open in WAL mode.
132856**
132857** If a transaction is open on the database being checkpointed, this
132858** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
132859** an error occurs while running the checkpoint, an SQLite error code is
132860** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
132861**
132862** The mutex on database handle db should be held by the caller. The mutex
132863** associated with the specific b-tree being checkpointed is taken by
132864** this function while the checkpoint is running.
132865**
132866** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
132867** checkpointed. If an error is encountered it is returned immediately -
132868** no attempt is made to checkpoint any remaining databases.
132869**
132870** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
132871*/
132872SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
132873  int rc = SQLITE_OK;             /* Return code */
132874  int i;                          /* Used to iterate through attached dbs */
132875  int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
132876
132877  assert( sqlite3_mutex_held(db->mutex) );
132878  assert( !pnLog || *pnLog==-1 );
132879  assert( !pnCkpt || *pnCkpt==-1 );
132880
132881  for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
132882    if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
132883      rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
132884      pnLog = 0;
132885      pnCkpt = 0;
132886      if( rc==SQLITE_BUSY ){
132887        bBusy = 1;
132888        rc = SQLITE_OK;
132889      }
132890    }
132891  }
132892
132893  return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
132894}
132895#endif /* SQLITE_OMIT_WAL */
132896
132897/*
132898** This function returns true if main-memory should be used instead of
132899** a temporary file for transient pager files and statement journals.
132900** The value returned depends on the value of db->temp_store (runtime
132901** parameter) and the compile time value of SQLITE_TEMP_STORE. The
132902** following table describes the relationship between these two values
132903** and this functions return value.
132904**
132905**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
132906**   -----------------     --------------     ------------------------------
132907**   0                     any                file      (return 0)
132908**   1                     1                  file      (return 0)
132909**   1                     2                  memory    (return 1)
132910**   1                     0                  file      (return 0)
132911**   2                     1                  file      (return 0)
132912**   2                     2                  memory    (return 1)
132913**   2                     0                  memory    (return 1)
132914**   3                     any                memory    (return 1)
132915*/
132916SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
132917#if SQLITE_TEMP_STORE==1
132918  return ( db->temp_store==2 );
132919#endif
132920#if SQLITE_TEMP_STORE==2
132921  return ( db->temp_store!=1 );
132922#endif
132923#if SQLITE_TEMP_STORE==3
132924  UNUSED_PARAMETER(db);
132925  return 1;
132926#endif
132927#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
132928  UNUSED_PARAMETER(db);
132929  return 0;
132930#endif
132931}
132932
132933/*
132934** Return UTF-8 encoded English language explanation of the most recent
132935** error.
132936*/
132937SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3 *db){
132938  const char *z;
132939  if( !db ){
132940    return sqlite3ErrStr(SQLITE_NOMEM);
132941  }
132942  if( !sqlite3SafetyCheckSickOrOk(db) ){
132943    return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
132944  }
132945  sqlite3_mutex_enter(db->mutex);
132946  if( db->mallocFailed ){
132947    z = sqlite3ErrStr(SQLITE_NOMEM);
132948  }else{
132949    testcase( db->pErr==0 );
132950    z = (char*)sqlite3_value_text(db->pErr);
132951    assert( !db->mallocFailed );
132952    if( z==0 ){
132953      z = sqlite3ErrStr(db->errCode);
132954    }
132955  }
132956  sqlite3_mutex_leave(db->mutex);
132957  return z;
132958}
132959
132960#ifndef SQLITE_OMIT_UTF16
132961/*
132962** Return UTF-16 encoded English language explanation of the most recent
132963** error.
132964*/
132965SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3 *db){
132966  static const u16 outOfMem[] = {
132967    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
132968  };
132969  static const u16 misuse[] = {
132970    'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
132971    'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
132972    'c', 'a', 'l', 'l', 'e', 'd', ' ',
132973    'o', 'u', 't', ' ',
132974    'o', 'f', ' ',
132975    's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
132976  };
132977
132978  const void *z;
132979  if( !db ){
132980    return (void *)outOfMem;
132981  }
132982  if( !sqlite3SafetyCheckSickOrOk(db) ){
132983    return (void *)misuse;
132984  }
132985  sqlite3_mutex_enter(db->mutex);
132986  if( db->mallocFailed ){
132987    z = (void *)outOfMem;
132988  }else{
132989    z = sqlite3_value_text16(db->pErr);
132990    if( z==0 ){
132991      sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
132992      z = sqlite3_value_text16(db->pErr);
132993    }
132994    /* A malloc() may have failed within the call to sqlite3_value_text16()
132995    ** above. If this is the case, then the db->mallocFailed flag needs to
132996    ** be cleared before returning. Do this directly, instead of via
132997    ** sqlite3ApiExit(), to avoid setting the database handle error message.
132998    */
132999    db->mallocFailed = 0;
133000  }
133001  sqlite3_mutex_leave(db->mutex);
133002  return z;
133003}
133004#endif /* SQLITE_OMIT_UTF16 */
133005
133006/*
133007** Return the most recent error code generated by an SQLite routine. If NULL is
133008** passed to this function, we assume a malloc() failed during sqlite3_open().
133009*/
133010SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db){
133011  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
133012    return SQLITE_MISUSE_BKPT;
133013  }
133014  if( !db || db->mallocFailed ){
133015    return SQLITE_NOMEM;
133016  }
133017  return db->errCode & db->errMask;
133018}
133019SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db){
133020  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
133021    return SQLITE_MISUSE_BKPT;
133022  }
133023  if( !db || db->mallocFailed ){
133024    return SQLITE_NOMEM;
133025  }
133026  return db->errCode;
133027}
133028
133029/*
133030** Return a string that describes the kind of error specified in the
133031** argument.  For now, this simply calls the internal sqlite3ErrStr()
133032** function.
133033*/
133034SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int rc){
133035  return sqlite3ErrStr(rc);
133036}
133037
133038/*
133039** Create a new collating function for database "db".  The name is zName
133040** and the encoding is enc.
133041*/
133042static int createCollation(
133043  sqlite3* db,
133044  const char *zName,
133045  u8 enc,
133046  void* pCtx,
133047  int(*xCompare)(void*,int,const void*,int,const void*),
133048  void(*xDel)(void*)
133049){
133050  CollSeq *pColl;
133051  int enc2;
133052
133053  assert( sqlite3_mutex_held(db->mutex) );
133054
133055  /* If SQLITE_UTF16 is specified as the encoding type, transform this
133056  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
133057  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
133058  */
133059  enc2 = enc;
133060  testcase( enc2==SQLITE_UTF16 );
133061  testcase( enc2==SQLITE_UTF16_ALIGNED );
133062  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
133063    enc2 = SQLITE_UTF16NATIVE;
133064  }
133065  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
133066    return SQLITE_MISUSE_BKPT;
133067  }
133068
133069  /* Check if this call is removing or replacing an existing collation
133070  ** sequence. If so, and there are active VMs, return busy. If there
133071  ** are no active VMs, invalidate any pre-compiled statements.
133072  */
133073  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
133074  if( pColl && pColl->xCmp ){
133075    if( db->nVdbeActive ){
133076      sqlite3ErrorWithMsg(db, SQLITE_BUSY,
133077        "unable to delete/modify collation sequence due to active statements");
133078      return SQLITE_BUSY;
133079    }
133080    sqlite3ExpirePreparedStatements(db);
133081
133082    /* If collation sequence pColl was created directly by a call to
133083    ** sqlite3_create_collation, and not generated by synthCollSeq(),
133084    ** then any copies made by synthCollSeq() need to be invalidated.
133085    ** Also, collation destructor - CollSeq.xDel() - function may need
133086    ** to be called.
133087    */
133088    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
133089      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
133090      int j;
133091      for(j=0; j<3; j++){
133092        CollSeq *p = &aColl[j];
133093        if( p->enc==pColl->enc ){
133094          if( p->xDel ){
133095            p->xDel(p->pUser);
133096          }
133097          p->xCmp = 0;
133098        }
133099      }
133100    }
133101  }
133102
133103  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
133104  if( pColl==0 ) return SQLITE_NOMEM;
133105  pColl->xCmp = xCompare;
133106  pColl->pUser = pCtx;
133107  pColl->xDel = xDel;
133108  pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
133109  sqlite3Error(db, SQLITE_OK);
133110  return SQLITE_OK;
133111}
133112
133113
133114/*
133115** This array defines hard upper bounds on limit values.  The
133116** initializer must be kept in sync with the SQLITE_LIMIT_*
133117** #defines in sqlite3.h.
133118*/
133119static const int aHardLimit[] = {
133120  SQLITE_MAX_LENGTH,
133121  SQLITE_MAX_SQL_LENGTH,
133122  SQLITE_MAX_COLUMN,
133123  SQLITE_MAX_EXPR_DEPTH,
133124  SQLITE_MAX_COMPOUND_SELECT,
133125  SQLITE_MAX_VDBE_OP,
133126  SQLITE_MAX_FUNCTION_ARG,
133127  SQLITE_MAX_ATTACHED,
133128  SQLITE_MAX_LIKE_PATTERN_LENGTH,
133129  SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
133130  SQLITE_MAX_TRIGGER_DEPTH,
133131  SQLITE_MAX_WORKER_THREADS,
133132};
133133
133134/*
133135** Make sure the hard limits are set to reasonable values
133136*/
133137#if SQLITE_MAX_LENGTH<100
133138# error SQLITE_MAX_LENGTH must be at least 100
133139#endif
133140#if SQLITE_MAX_SQL_LENGTH<100
133141# error SQLITE_MAX_SQL_LENGTH must be at least 100
133142#endif
133143#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
133144# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
133145#endif
133146#if SQLITE_MAX_COMPOUND_SELECT<2
133147# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
133148#endif
133149#if SQLITE_MAX_VDBE_OP<40
133150# error SQLITE_MAX_VDBE_OP must be at least 40
133151#endif
133152#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
133153# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
133154#endif
133155#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
133156# error SQLITE_MAX_ATTACHED must be between 0 and 125
133157#endif
133158#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
133159# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
133160#endif
133161#if SQLITE_MAX_COLUMN>32767
133162# error SQLITE_MAX_COLUMN must not exceed 32767
133163#endif
133164#if SQLITE_MAX_TRIGGER_DEPTH<1
133165# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
133166#endif
133167#if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
133168# error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
133169#endif
133170
133171
133172/*
133173** Change the value of a limit.  Report the old value.
133174** If an invalid limit index is supplied, report -1.
133175** Make no changes but still report the old value if the
133176** new limit is negative.
133177**
133178** A new lower limit does not shrink existing constructs.
133179** It merely prevents new constructs that exceed the limit
133180** from forming.
133181*/
133182SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
133183  int oldLimit;
133184
133185#ifdef SQLITE_ENABLE_API_ARMOR
133186  if( !sqlite3SafetyCheckOk(db) ){
133187    (void)SQLITE_MISUSE_BKPT;
133188    return -1;
133189  }
133190#endif
133191
133192  /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
133193  ** there is a hard upper bound set at compile-time by a C preprocessor
133194  ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
133195  ** "_MAX_".)
133196  */
133197  assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
133198  assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
133199  assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
133200  assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
133201  assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
133202  assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
133203  assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
133204  assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
133205  assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
133206                                               SQLITE_MAX_LIKE_PATTERN_LENGTH );
133207  assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
133208  assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
133209  assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
133210  assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
133211
133212
133213  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
133214    return -1;
133215  }
133216  oldLimit = db->aLimit[limitId];
133217  if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
133218    if( newLimit>aHardLimit[limitId] ){
133219      newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
133220    }
133221    db->aLimit[limitId] = newLimit;
133222  }
133223  return oldLimit;                     /* IMP: R-53341-35419 */
133224}
133225
133226/*
133227** This function is used to parse both URIs and non-URI filenames passed by the
133228** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
133229** URIs specified as part of ATTACH statements.
133230**
133231** The first argument to this function is the name of the VFS to use (or
133232** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
133233** query parameter. The second argument contains the URI (or non-URI filename)
133234** itself. When this function is called the *pFlags variable should contain
133235** the default flags to open the database handle with. The value stored in
133236** *pFlags may be updated before returning if the URI filename contains
133237** "cache=xxx" or "mode=xxx" query parameters.
133238**
133239** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
133240** the VFS that should be used to open the database file. *pzFile is set to
133241** point to a buffer containing the name of the file to open. It is the
133242** responsibility of the caller to eventually call sqlite3_free() to release
133243** this buffer.
133244**
133245** If an error occurs, then an SQLite error code is returned and *pzErrMsg
133246** may be set to point to a buffer containing an English language error
133247** message. It is the responsibility of the caller to eventually release
133248** this buffer by calling sqlite3_free().
133249*/
133250SQLITE_PRIVATE int sqlite3ParseUri(
133251  const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
133252  const char *zUri,               /* Nul-terminated URI to parse */
133253  unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
133254  sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
133255  char **pzFile,                  /* OUT: Filename component of URI */
133256  char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
133257){
133258  int rc = SQLITE_OK;
133259  unsigned int flags = *pFlags;
133260  const char *zVfs = zDefaultVfs;
133261  char *zFile;
133262  char c;
133263  int nUri = sqlite3Strlen30(zUri);
133264
133265  assert( *pzErrMsg==0 );
133266
133267  if( ((flags & SQLITE_OPEN_URI)             /* IMP: R-48725-32206 */
133268            || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
133269   && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
133270  ){
133271    char *zOpt;
133272    int eState;                   /* Parser state when parsing URI */
133273    int iIn;                      /* Input character index */
133274    int iOut = 0;                 /* Output character index */
133275    u64 nByte = nUri+2;           /* Bytes of space to allocate */
133276
133277    /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
133278    ** method that there may be extra parameters following the file-name.  */
133279    flags |= SQLITE_OPEN_URI;
133280
133281    for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
133282    zFile = sqlite3_malloc64(nByte);
133283    if( !zFile ) return SQLITE_NOMEM;
133284
133285    iIn = 5;
133286#ifdef SQLITE_ALLOW_URI_AUTHORITY
133287    if( strncmp(zUri+5, "///", 3)==0 ){
133288      iIn = 7;
133289      /* The following condition causes URIs with five leading / characters
133290      ** like file://///host/path to be converted into UNCs like //host/path.
133291      ** The correct URI for that UNC has only two or four leading / characters
133292      ** file://host/path or file:////host/path.  But 5 leading slashes is a
133293      ** common error, we are told, so we handle it as a special case. */
133294      if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
133295    }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
133296      iIn = 16;
133297    }
133298#else
133299    /* Discard the scheme and authority segments of the URI. */
133300    if( zUri[5]=='/' && zUri[6]=='/' ){
133301      iIn = 7;
133302      while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
133303      if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
133304        *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
133305            iIn-7, &zUri[7]);
133306        rc = SQLITE_ERROR;
133307        goto parse_uri_out;
133308      }
133309    }
133310#endif
133311
133312    /* Copy the filename and any query parameters into the zFile buffer.
133313    ** Decode %HH escape codes along the way.
133314    **
133315    ** Within this loop, variable eState may be set to 0, 1 or 2, depending
133316    ** on the parsing context. As follows:
133317    **
133318    **   0: Parsing file-name.
133319    **   1: Parsing name section of a name=value query parameter.
133320    **   2: Parsing value section of a name=value query parameter.
133321    */
133322    eState = 0;
133323    while( (c = zUri[iIn])!=0 && c!='#' ){
133324      iIn++;
133325      if( c=='%'
133326       && sqlite3Isxdigit(zUri[iIn])
133327       && sqlite3Isxdigit(zUri[iIn+1])
133328      ){
133329        int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
133330        octet += sqlite3HexToInt(zUri[iIn++]);
133331
133332        assert( octet>=0 && octet<256 );
133333        if( octet==0 ){
133334          /* This branch is taken when "%00" appears within the URI. In this
133335          ** case we ignore all text in the remainder of the path, name or
133336          ** value currently being parsed. So ignore the current character
133337          ** and skip to the next "?", "=" or "&", as appropriate. */
133338          while( (c = zUri[iIn])!=0 && c!='#'
133339              && (eState!=0 || c!='?')
133340              && (eState!=1 || (c!='=' && c!='&'))
133341              && (eState!=2 || c!='&')
133342          ){
133343            iIn++;
133344          }
133345          continue;
133346        }
133347        c = octet;
133348      }else if( eState==1 && (c=='&' || c=='=') ){
133349        if( zFile[iOut-1]==0 ){
133350          /* An empty option name. Ignore this option altogether. */
133351          while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
133352          continue;
133353        }
133354        if( c=='&' ){
133355          zFile[iOut++] = '\0';
133356        }else{
133357          eState = 2;
133358        }
133359        c = 0;
133360      }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
133361        c = 0;
133362        eState = 1;
133363      }
133364      zFile[iOut++] = c;
133365    }
133366    if( eState==1 ) zFile[iOut++] = '\0';
133367    zFile[iOut++] = '\0';
133368    zFile[iOut++] = '\0';
133369
133370    /* Check if there were any options specified that should be interpreted
133371    ** here. Options that are interpreted here include "vfs" and those that
133372    ** correspond to flags that may be passed to the sqlite3_open_v2()
133373    ** method. */
133374    zOpt = &zFile[sqlite3Strlen30(zFile)+1];
133375    while( zOpt[0] ){
133376      int nOpt = sqlite3Strlen30(zOpt);
133377      char *zVal = &zOpt[nOpt+1];
133378      int nVal = sqlite3Strlen30(zVal);
133379
133380      if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
133381        zVfs = zVal;
133382      }else{
133383        struct OpenMode {
133384          const char *z;
133385          int mode;
133386        } *aMode = 0;
133387        char *zModeType = 0;
133388        int mask = 0;
133389        int limit = 0;
133390
133391        if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
133392          static struct OpenMode aCacheMode[] = {
133393            { "shared",  SQLITE_OPEN_SHAREDCACHE },
133394            { "private", SQLITE_OPEN_PRIVATECACHE },
133395            { 0, 0 }
133396          };
133397
133398          mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
133399          aMode = aCacheMode;
133400          limit = mask;
133401          zModeType = "cache";
133402        }
133403        if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
133404          static struct OpenMode aOpenMode[] = {
133405            { "ro",  SQLITE_OPEN_READONLY },
133406            { "rw",  SQLITE_OPEN_READWRITE },
133407            { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
133408            { "memory", SQLITE_OPEN_MEMORY },
133409            { 0, 0 }
133410          };
133411
133412          mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
133413                   | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
133414          aMode = aOpenMode;
133415          limit = mask & flags;
133416          zModeType = "access";
133417        }
133418
133419        if( aMode ){
133420          int i;
133421          int mode = 0;
133422          for(i=0; aMode[i].z; i++){
133423            const char *z = aMode[i].z;
133424            if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
133425              mode = aMode[i].mode;
133426              break;
133427            }
133428          }
133429          if( mode==0 ){
133430            *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
133431            rc = SQLITE_ERROR;
133432            goto parse_uri_out;
133433          }
133434          if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
133435            *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
133436                                        zModeType, zVal);
133437            rc = SQLITE_PERM;
133438            goto parse_uri_out;
133439          }
133440          flags = (flags & ~mask) | mode;
133441        }
133442      }
133443
133444      zOpt = &zVal[nVal+1];
133445    }
133446
133447  }else{
133448    zFile = sqlite3_malloc64(nUri+2);
133449    if( !zFile ) return SQLITE_NOMEM;
133450    memcpy(zFile, zUri, nUri);
133451    zFile[nUri] = '\0';
133452    zFile[nUri+1] = '\0';
133453    flags &= ~SQLITE_OPEN_URI;
133454  }
133455
133456  *ppVfs = sqlite3_vfs_find(zVfs);
133457  if( *ppVfs==0 ){
133458    *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
133459    rc = SQLITE_ERROR;
133460  }
133461 parse_uri_out:
133462  if( rc!=SQLITE_OK ){
133463    sqlite3_free(zFile);
133464    zFile = 0;
133465  }
133466  *pFlags = flags;
133467  *pzFile = zFile;
133468  return rc;
133469}
133470
133471
133472/*
133473** This routine does the work of opening a database on behalf of
133474** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
133475** is UTF-8 encoded.
133476*/
133477static int openDatabase(
133478  const char *zFilename, /* Database filename UTF-8 encoded */
133479  sqlite3 **ppDb,        /* OUT: Returned database handle */
133480  unsigned int flags,    /* Operational flags */
133481  const char *zVfs       /* Name of the VFS to use */
133482){
133483  sqlite3 *db;                    /* Store allocated handle here */
133484  int rc;                         /* Return code */
133485  int isThreadsafe;               /* True for threadsafe connections */
133486  char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
133487  char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
133488
133489#ifdef SQLITE_ENABLE_API_ARMOR
133490  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
133491#endif
133492  *ppDb = 0;
133493#ifndef SQLITE_OMIT_AUTOINIT
133494  rc = sqlite3_initialize();
133495  if( rc ) return rc;
133496#endif
133497
133498  /* Only allow sensible combinations of bits in the flags argument.
133499  ** Throw an error if any non-sense combination is used.  If we
133500  ** do not block illegal combinations here, it could trigger
133501  ** assert() statements in deeper layers.  Sensible combinations
133502  ** are:
133503  **
133504  **  1:  SQLITE_OPEN_READONLY
133505  **  2:  SQLITE_OPEN_READWRITE
133506  **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
133507  */
133508  assert( SQLITE_OPEN_READONLY  == 0x01 );
133509  assert( SQLITE_OPEN_READWRITE == 0x02 );
133510  assert( SQLITE_OPEN_CREATE    == 0x04 );
133511  testcase( (1<<(flags&7))==0x02 ); /* READONLY */
133512  testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
133513  testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
133514  if( ((1<<(flags&7)) & 0x46)==0 ){
133515    return SQLITE_MISUSE_BKPT;  /* IMP: R-65497-44594 */
133516  }
133517
133518  if( sqlite3GlobalConfig.bCoreMutex==0 ){
133519    isThreadsafe = 0;
133520  }else if( flags & SQLITE_OPEN_NOMUTEX ){
133521    isThreadsafe = 0;
133522  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
133523    isThreadsafe = 1;
133524  }else{
133525    isThreadsafe = sqlite3GlobalConfig.bFullMutex;
133526  }
133527  if( flags & SQLITE_OPEN_PRIVATECACHE ){
133528    flags &= ~SQLITE_OPEN_SHAREDCACHE;
133529  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
133530    flags |= SQLITE_OPEN_SHAREDCACHE;
133531  }
133532
133533  /* Remove harmful bits from the flags parameter
133534  **
133535  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
133536  ** dealt with in the previous code block.  Besides these, the only
133537  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
133538  ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
133539  ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
133540  ** off all other flags.
133541  */
133542  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
133543               SQLITE_OPEN_EXCLUSIVE |
133544               SQLITE_OPEN_MAIN_DB |
133545               SQLITE_OPEN_TEMP_DB |
133546               SQLITE_OPEN_TRANSIENT_DB |
133547               SQLITE_OPEN_MAIN_JOURNAL |
133548               SQLITE_OPEN_TEMP_JOURNAL |
133549               SQLITE_OPEN_SUBJOURNAL |
133550               SQLITE_OPEN_MASTER_JOURNAL |
133551               SQLITE_OPEN_NOMUTEX |
133552               SQLITE_OPEN_FULLMUTEX |
133553               SQLITE_OPEN_WAL
133554             );
133555
133556  /* Allocate the sqlite data structure */
133557  db = sqlite3MallocZero( sizeof(sqlite3) );
133558  if( db==0 ) goto opendb_out;
133559  if( isThreadsafe ){
133560    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
133561    if( db->mutex==0 ){
133562      sqlite3_free(db);
133563      db = 0;
133564      goto opendb_out;
133565    }
133566  }
133567  sqlite3_mutex_enter(db->mutex);
133568  db->errMask = 0xff;
133569  db->nDb = 2;
133570  db->magic = SQLITE_MAGIC_BUSY;
133571  db->aDb = db->aDbStatic;
133572
133573  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
133574  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
133575  db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
133576  db->autoCommit = 1;
133577  db->nextAutovac = -1;
133578  db->szMmap = sqlite3GlobalConfig.szMmap;
133579  db->nextPagesize = 0;
133580  db->nMaxSorterMmap = 0x7FFFFFFF;
133581  db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
133582#if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
133583                 | SQLITE_AutoIndex
133584#endif
133585#if SQLITE_DEFAULT_CKPTFULLFSYNC
133586                 | SQLITE_CkptFullFSync
133587#endif
133588#if SQLITE_DEFAULT_FILE_FORMAT<4
133589                 | SQLITE_LegacyFileFmt
133590#endif
133591#ifdef SQLITE_ENABLE_LOAD_EXTENSION
133592                 | SQLITE_LoadExtension
133593#endif
133594#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
133595                 | SQLITE_RecTriggers
133596#endif
133597#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
133598                 | SQLITE_ForeignKeys
133599#endif
133600#if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
133601                 | SQLITE_ReverseOrder
133602#endif
133603#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
133604                 | SQLITE_CellSizeCk
133605#endif
133606      ;
133607  sqlite3HashInit(&db->aCollSeq);
133608#ifndef SQLITE_OMIT_VIRTUALTABLE
133609  sqlite3HashInit(&db->aModule);
133610#endif
133611
133612  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
133613  ** and UTF-16, so add a version for each to avoid any unnecessary
133614  ** conversions. The only error that can occur here is a malloc() failure.
133615  **
133616  ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
133617  ** functions:
133618  */
133619  createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
133620  createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
133621  createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
133622  createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
133623  createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
133624  if( db->mallocFailed ){
133625    goto opendb_out;
133626  }
133627  /* EVIDENCE-OF: R-08308-17224 The default collating function for all
133628  ** strings is BINARY.
133629  */
133630  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
133631  assert( db->pDfltColl!=0 );
133632
133633  /* Parse the filename/URI argument. */
133634  db->openFlags = flags;
133635  rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
133636  if( rc!=SQLITE_OK ){
133637    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
133638    sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
133639    sqlite3_free(zErrMsg);
133640    goto opendb_out;
133641  }
133642
133643  /* Open the backend database driver */
133644  rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
133645                        flags | SQLITE_OPEN_MAIN_DB);
133646  if( rc!=SQLITE_OK ){
133647    if( rc==SQLITE_IOERR_NOMEM ){
133648      rc = SQLITE_NOMEM;
133649    }
133650    sqlite3Error(db, rc);
133651    goto opendb_out;
133652  }
133653  sqlite3BtreeEnter(db->aDb[0].pBt);
133654  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
133655  if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
133656  sqlite3BtreeLeave(db->aDb[0].pBt);
133657  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
133658
133659  /* The default safety_level for the main database is 'full'; for the temp
133660  ** database it is 'NONE'. This matches the pager layer defaults.
133661  */
133662  db->aDb[0].zName = "main";
133663  db->aDb[0].safety_level = 3;
133664  db->aDb[1].zName = "temp";
133665  db->aDb[1].safety_level = 1;
133666
133667  db->magic = SQLITE_MAGIC_OPEN;
133668  if( db->mallocFailed ){
133669    goto opendb_out;
133670  }
133671
133672  /* Register all built-in functions, but do not attempt to read the
133673  ** database schema yet. This is delayed until the first time the database
133674  ** is accessed.
133675  */
133676  sqlite3Error(db, SQLITE_OK);
133677  sqlite3RegisterBuiltinFunctions(db);
133678
133679  /* Load automatic extensions - extensions that have been registered
133680  ** using the sqlite3_automatic_extension() API.
133681  */
133682  rc = sqlite3_errcode(db);
133683  if( rc==SQLITE_OK ){
133684    sqlite3AutoLoadExtensions(db);
133685    rc = sqlite3_errcode(db);
133686    if( rc!=SQLITE_OK ){
133687      goto opendb_out;
133688    }
133689  }
133690
133691#ifdef SQLITE_ENABLE_FTS1
133692  if( !db->mallocFailed ){
133693    extern int sqlite3Fts1Init(sqlite3*);
133694    rc = sqlite3Fts1Init(db);
133695  }
133696#endif
133697
133698#ifdef SQLITE_ENABLE_FTS2
133699  if( !db->mallocFailed && rc==SQLITE_OK ){
133700    extern int sqlite3Fts2Init(sqlite3*);
133701    rc = sqlite3Fts2Init(db);
133702  }
133703#endif
133704
133705#ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
133706  if( !db->mallocFailed && rc==SQLITE_OK ){
133707    rc = sqlite3Fts3Init(db);
133708  }
133709#endif
133710
133711#ifdef SQLITE_ENABLE_FTS5
133712  if( !db->mallocFailed && rc==SQLITE_OK ){
133713    rc = sqlite3Fts5Init(db);
133714  }
133715#endif
133716
133717#ifdef SQLITE_ENABLE_ICU
133718  if( !db->mallocFailed && rc==SQLITE_OK ){
133719    rc = sqlite3IcuInit(db);
133720  }
133721#endif
133722
133723#ifdef SQLITE_ENABLE_RTREE
133724  if( !db->mallocFailed && rc==SQLITE_OK){
133725    rc = sqlite3RtreeInit(db);
133726  }
133727#endif
133728
133729#ifdef SQLITE_ENABLE_DBSTAT_VTAB
133730  if( !db->mallocFailed && rc==SQLITE_OK){
133731    rc = sqlite3DbstatRegister(db);
133732  }
133733#endif
133734
133735#ifdef SQLITE_ENABLE_JSON1
133736  if( !db->mallocFailed && rc==SQLITE_OK){
133737    rc = sqlite3Json1Init(db);
133738  }
133739#endif
133740
133741  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
133742  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
133743  ** mode.  Doing nothing at all also makes NORMAL the default.
133744  */
133745#ifdef SQLITE_DEFAULT_LOCKING_MODE
133746  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
133747  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
133748                          SQLITE_DEFAULT_LOCKING_MODE);
133749#endif
133750
133751  if( rc ) sqlite3Error(db, rc);
133752
133753  /* Enable the lookaside-malloc subsystem */
133754  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
133755                        sqlite3GlobalConfig.nLookaside);
133756
133757  sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
133758
133759opendb_out:
133760  sqlite3_free(zOpen);
133761  if( db ){
133762    assert( db->mutex!=0 || isThreadsafe==0
133763           || sqlite3GlobalConfig.bFullMutex==0 );
133764    sqlite3_mutex_leave(db->mutex);
133765  }
133766  rc = sqlite3_errcode(db);
133767  assert( db!=0 || rc==SQLITE_NOMEM );
133768  if( rc==SQLITE_NOMEM ){
133769    sqlite3_close(db);
133770    db = 0;
133771  }else if( rc!=SQLITE_OK ){
133772    db->magic = SQLITE_MAGIC_SICK;
133773  }
133774  *ppDb = db;
133775#ifdef SQLITE_ENABLE_SQLLOG
133776  if( sqlite3GlobalConfig.xSqllog ){
133777    /* Opening a db handle. Fourth parameter is passed 0. */
133778    void *pArg = sqlite3GlobalConfig.pSqllogArg;
133779    sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
133780  }
133781#endif
133782  return rc & 0xff;
133783}
133784
133785/*
133786** Open a new database handle.
133787*/
133788SQLITE_API int SQLITE_STDCALL sqlite3_open(
133789  const char *zFilename,
133790  sqlite3 **ppDb
133791){
133792  return openDatabase(zFilename, ppDb,
133793                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
133794}
133795SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
133796  const char *filename,   /* Database filename (UTF-8) */
133797  sqlite3 **ppDb,         /* OUT: SQLite db handle */
133798  int flags,              /* Flags */
133799  const char *zVfs        /* Name of VFS module to use */
133800){
133801  return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
133802}
133803
133804#ifndef SQLITE_OMIT_UTF16
133805/*
133806** Open a new database handle.
133807*/
133808SQLITE_API int SQLITE_STDCALL sqlite3_open16(
133809  const void *zFilename,
133810  sqlite3 **ppDb
133811){
133812  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
133813  sqlite3_value *pVal;
133814  int rc;
133815
133816#ifdef SQLITE_ENABLE_API_ARMOR
133817  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
133818#endif
133819  *ppDb = 0;
133820#ifndef SQLITE_OMIT_AUTOINIT
133821  rc = sqlite3_initialize();
133822  if( rc ) return rc;
133823#endif
133824  if( zFilename==0 ) zFilename = "\000\000";
133825  pVal = sqlite3ValueNew(0);
133826  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
133827  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
133828  if( zFilename8 ){
133829    rc = openDatabase(zFilename8, ppDb,
133830                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
133831    assert( *ppDb || rc==SQLITE_NOMEM );
133832    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
133833      SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
133834    }
133835  }else{
133836    rc = SQLITE_NOMEM;
133837  }
133838  sqlite3ValueFree(pVal);
133839
133840  return rc & 0xff;
133841}
133842#endif /* SQLITE_OMIT_UTF16 */
133843
133844/*
133845** Register a new collation sequence with the database handle db.
133846*/
133847SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
133848  sqlite3* db,
133849  const char *zName,
133850  int enc,
133851  void* pCtx,
133852  int(*xCompare)(void*,int,const void*,int,const void*)
133853){
133854  return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
133855}
133856
133857/*
133858** Register a new collation sequence with the database handle db.
133859*/
133860SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
133861  sqlite3* db,
133862  const char *zName,
133863  int enc,
133864  void* pCtx,
133865  int(*xCompare)(void*,int,const void*,int,const void*),
133866  void(*xDel)(void*)
133867){
133868  int rc;
133869
133870#ifdef SQLITE_ENABLE_API_ARMOR
133871  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
133872#endif
133873  sqlite3_mutex_enter(db->mutex);
133874  assert( !db->mallocFailed );
133875  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
133876  rc = sqlite3ApiExit(db, rc);
133877  sqlite3_mutex_leave(db->mutex);
133878  return rc;
133879}
133880
133881#ifndef SQLITE_OMIT_UTF16
133882/*
133883** Register a new collation sequence with the database handle db.
133884*/
133885SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
133886  sqlite3* db,
133887  const void *zName,
133888  int enc,
133889  void* pCtx,
133890  int(*xCompare)(void*,int,const void*,int,const void*)
133891){
133892  int rc = SQLITE_OK;
133893  char *zName8;
133894
133895#ifdef SQLITE_ENABLE_API_ARMOR
133896  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
133897#endif
133898  sqlite3_mutex_enter(db->mutex);
133899  assert( !db->mallocFailed );
133900  zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
133901  if( zName8 ){
133902    rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
133903    sqlite3DbFree(db, zName8);
133904  }
133905  rc = sqlite3ApiExit(db, rc);
133906  sqlite3_mutex_leave(db->mutex);
133907  return rc;
133908}
133909#endif /* SQLITE_OMIT_UTF16 */
133910
133911/*
133912** Register a collation sequence factory callback with the database handle
133913** db. Replace any previously installed collation sequence factory.
133914*/
133915SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
133916  sqlite3 *db,
133917  void *pCollNeededArg,
133918  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
133919){
133920#ifdef SQLITE_ENABLE_API_ARMOR
133921  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
133922#endif
133923  sqlite3_mutex_enter(db->mutex);
133924  db->xCollNeeded = xCollNeeded;
133925  db->xCollNeeded16 = 0;
133926  db->pCollNeededArg = pCollNeededArg;
133927  sqlite3_mutex_leave(db->mutex);
133928  return SQLITE_OK;
133929}
133930
133931#ifndef SQLITE_OMIT_UTF16
133932/*
133933** Register a collation sequence factory callback with the database handle
133934** db. Replace any previously installed collation sequence factory.
133935*/
133936SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
133937  sqlite3 *db,
133938  void *pCollNeededArg,
133939  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
133940){
133941#ifdef SQLITE_ENABLE_API_ARMOR
133942  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
133943#endif
133944  sqlite3_mutex_enter(db->mutex);
133945  db->xCollNeeded = 0;
133946  db->xCollNeeded16 = xCollNeeded16;
133947  db->pCollNeededArg = pCollNeededArg;
133948  sqlite3_mutex_leave(db->mutex);
133949  return SQLITE_OK;
133950}
133951#endif /* SQLITE_OMIT_UTF16 */
133952
133953#ifndef SQLITE_OMIT_DEPRECATED
133954/*
133955** This function is now an anachronism. It used to be used to recover from a
133956** malloc() failure, but SQLite now does this automatically.
133957*/
133958SQLITE_API int SQLITE_STDCALL sqlite3_global_recover(void){
133959  return SQLITE_OK;
133960}
133961#endif
133962
133963/*
133964** Test to see whether or not the database connection is in autocommit
133965** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
133966** by default.  Autocommit is disabled by a BEGIN statement and reenabled
133967** by the next COMMIT or ROLLBACK.
133968*/
133969SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3 *db){
133970#ifdef SQLITE_ENABLE_API_ARMOR
133971  if( !sqlite3SafetyCheckOk(db) ){
133972    (void)SQLITE_MISUSE_BKPT;
133973    return 0;
133974  }
133975#endif
133976  return db->autoCommit;
133977}
133978
133979/*
133980** The following routines are substitutes for constants SQLITE_CORRUPT,
133981** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
133982** constants.  They serve two purposes:
133983**
133984**   1.  Serve as a convenient place to set a breakpoint in a debugger
133985**       to detect when version error conditions occurs.
133986**
133987**   2.  Invoke sqlite3_log() to provide the source code location where
133988**       a low-level error is first detected.
133989*/
133990SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
133991  testcase( sqlite3GlobalConfig.xLog!=0 );
133992  sqlite3_log(SQLITE_CORRUPT,
133993              "database corruption at line %d of [%.10s]",
133994              lineno, 20+sqlite3_sourceid());
133995  return SQLITE_CORRUPT;
133996}
133997SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
133998  testcase( sqlite3GlobalConfig.xLog!=0 );
133999  sqlite3_log(SQLITE_MISUSE,
134000              "misuse at line %d of [%.10s]",
134001              lineno, 20+sqlite3_sourceid());
134002  return SQLITE_MISUSE;
134003}
134004SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
134005  testcase( sqlite3GlobalConfig.xLog!=0 );
134006  sqlite3_log(SQLITE_CANTOPEN,
134007              "cannot open file at line %d of [%.10s]",
134008              lineno, 20+sqlite3_sourceid());
134009  return SQLITE_CANTOPEN;
134010}
134011
134012
134013#ifndef SQLITE_OMIT_DEPRECATED
134014/*
134015** This is a convenience routine that makes sure that all thread-specific
134016** data for this thread has been deallocated.
134017**
134018** SQLite no longer uses thread-specific data so this routine is now a
134019** no-op.  It is retained for historical compatibility.
134020*/
134021SQLITE_API void SQLITE_STDCALL sqlite3_thread_cleanup(void){
134022}
134023#endif
134024
134025/*
134026** Return meta information about a specific column of a database table.
134027** See comment in sqlite3.h (sqlite.h.in) for details.
134028*/
134029SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
134030  sqlite3 *db,                /* Connection handle */
134031  const char *zDbName,        /* Database name or NULL */
134032  const char *zTableName,     /* Table name */
134033  const char *zColumnName,    /* Column name */
134034  char const **pzDataType,    /* OUTPUT: Declared data type */
134035  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
134036  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
134037  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
134038  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
134039){
134040  int rc;
134041  char *zErrMsg = 0;
134042  Table *pTab = 0;
134043  Column *pCol = 0;
134044  int iCol = 0;
134045  char const *zDataType = 0;
134046  char const *zCollSeq = 0;
134047  int notnull = 0;
134048  int primarykey = 0;
134049  int autoinc = 0;
134050
134051
134052#ifdef SQLITE_ENABLE_API_ARMOR
134053  if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
134054    return SQLITE_MISUSE_BKPT;
134055  }
134056#endif
134057
134058  /* Ensure the database schema has been loaded */
134059  sqlite3_mutex_enter(db->mutex);
134060  sqlite3BtreeEnterAll(db);
134061  rc = sqlite3Init(db, &zErrMsg);
134062  if( SQLITE_OK!=rc ){
134063    goto error_out;
134064  }
134065
134066  /* Locate the table in question */
134067  pTab = sqlite3FindTable(db, zTableName, zDbName);
134068  if( !pTab || pTab->pSelect ){
134069    pTab = 0;
134070    goto error_out;
134071  }
134072
134073  /* Find the column for which info is requested */
134074  if( zColumnName==0 ){
134075    /* Query for existance of table only */
134076  }else{
134077    for(iCol=0; iCol<pTab->nCol; iCol++){
134078      pCol = &pTab->aCol[iCol];
134079      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
134080        break;
134081      }
134082    }
134083    if( iCol==pTab->nCol ){
134084      if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
134085        iCol = pTab->iPKey;
134086        pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
134087      }else{
134088        pTab = 0;
134089        goto error_out;
134090      }
134091    }
134092  }
134093
134094  /* The following block stores the meta information that will be returned
134095  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
134096  ** and autoinc. At this point there are two possibilities:
134097  **
134098  **     1. The specified column name was rowid", "oid" or "_rowid_"
134099  **        and there is no explicitly declared IPK column.
134100  **
134101  **     2. The table is not a view and the column name identified an
134102  **        explicitly declared column. Copy meta information from *pCol.
134103  */
134104  if( pCol ){
134105    zDataType = pCol->zType;
134106    zCollSeq = pCol->zColl;
134107    notnull = pCol->notNull!=0;
134108    primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
134109    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
134110  }else{
134111    zDataType = "INTEGER";
134112    primarykey = 1;
134113  }
134114  if( !zCollSeq ){
134115    zCollSeq = "BINARY";
134116  }
134117
134118error_out:
134119  sqlite3BtreeLeaveAll(db);
134120
134121  /* Whether the function call succeeded or failed, set the output parameters
134122  ** to whatever their local counterparts contain. If an error did occur,
134123  ** this has the effect of zeroing all output parameters.
134124  */
134125  if( pzDataType ) *pzDataType = zDataType;
134126  if( pzCollSeq ) *pzCollSeq = zCollSeq;
134127  if( pNotNull ) *pNotNull = notnull;
134128  if( pPrimaryKey ) *pPrimaryKey = primarykey;
134129  if( pAutoinc ) *pAutoinc = autoinc;
134130
134131  if( SQLITE_OK==rc && !pTab ){
134132    sqlite3DbFree(db, zErrMsg);
134133    zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
134134        zColumnName);
134135    rc = SQLITE_ERROR;
134136  }
134137  sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
134138  sqlite3DbFree(db, zErrMsg);
134139  rc = sqlite3ApiExit(db, rc);
134140  sqlite3_mutex_leave(db->mutex);
134141  return rc;
134142}
134143
134144/*
134145** Sleep for a little while.  Return the amount of time slept.
134146*/
134147SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int ms){
134148  sqlite3_vfs *pVfs;
134149  int rc;
134150  pVfs = sqlite3_vfs_find(0);
134151  if( pVfs==0 ) return 0;
134152
134153  /* This function works in milliseconds, but the underlying OsSleep()
134154  ** API uses microseconds. Hence the 1000's.
134155  */
134156  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
134157  return rc;
134158}
134159
134160/*
134161** Enable or disable the extended result codes.
134162*/
134163SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3 *db, int onoff){
134164#ifdef SQLITE_ENABLE_API_ARMOR
134165  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
134166#endif
134167  sqlite3_mutex_enter(db->mutex);
134168  db->errMask = onoff ? 0xffffffff : 0xff;
134169  sqlite3_mutex_leave(db->mutex);
134170  return SQLITE_OK;
134171}
134172
134173/*
134174** Invoke the xFileControl method on a particular database.
134175*/
134176SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
134177  int rc = SQLITE_ERROR;
134178  Btree *pBtree;
134179
134180#ifdef SQLITE_ENABLE_API_ARMOR
134181  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
134182#endif
134183  sqlite3_mutex_enter(db->mutex);
134184  pBtree = sqlite3DbNameToBtree(db, zDbName);
134185  if( pBtree ){
134186    Pager *pPager;
134187    sqlite3_file *fd;
134188    sqlite3BtreeEnter(pBtree);
134189    pPager = sqlite3BtreePager(pBtree);
134190    assert( pPager!=0 );
134191    fd = sqlite3PagerFile(pPager);
134192    assert( fd!=0 );
134193    if( op==SQLITE_FCNTL_FILE_POINTER ){
134194      *(sqlite3_file**)pArg = fd;
134195      rc = SQLITE_OK;
134196    }else if( fd->pMethods ){
134197      rc = sqlite3OsFileControl(fd, op, pArg);
134198    }else{
134199      rc = SQLITE_NOTFOUND;
134200    }
134201    sqlite3BtreeLeave(pBtree);
134202  }
134203  sqlite3_mutex_leave(db->mutex);
134204  return rc;
134205}
134206
134207/*
134208** Interface to the testing logic.
134209*/
134210SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...){
134211  int rc = 0;
134212#ifdef SQLITE_OMIT_BUILTIN_TEST
134213  UNUSED_PARAMETER(op);
134214#else
134215  va_list ap;
134216  va_start(ap, op);
134217  switch( op ){
134218
134219    /*
134220    ** Save the current state of the PRNG.
134221    */
134222    case SQLITE_TESTCTRL_PRNG_SAVE: {
134223      sqlite3PrngSaveState();
134224      break;
134225    }
134226
134227    /*
134228    ** Restore the state of the PRNG to the last state saved using
134229    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
134230    ** this verb acts like PRNG_RESET.
134231    */
134232    case SQLITE_TESTCTRL_PRNG_RESTORE: {
134233      sqlite3PrngRestoreState();
134234      break;
134235    }
134236
134237    /*
134238    ** Reset the PRNG back to its uninitialized state.  The next call
134239    ** to sqlite3_randomness() will reseed the PRNG using a single call
134240    ** to the xRandomness method of the default VFS.
134241    */
134242    case SQLITE_TESTCTRL_PRNG_RESET: {
134243      sqlite3_randomness(0,0);
134244      break;
134245    }
134246
134247    /*
134248    **  sqlite3_test_control(BITVEC_TEST, size, program)
134249    **
134250    ** Run a test against a Bitvec object of size.  The program argument
134251    ** is an array of integers that defines the test.  Return -1 on a
134252    ** memory allocation error, 0 on success, or non-zero for an error.
134253    ** See the sqlite3BitvecBuiltinTest() for additional information.
134254    */
134255    case SQLITE_TESTCTRL_BITVEC_TEST: {
134256      int sz = va_arg(ap, int);
134257      int *aProg = va_arg(ap, int*);
134258      rc = sqlite3BitvecBuiltinTest(sz, aProg);
134259      break;
134260    }
134261
134262    /*
134263    **  sqlite3_test_control(FAULT_INSTALL, xCallback)
134264    **
134265    ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
134266    ** if xCallback is not NULL.
134267    **
134268    ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
134269    ** is called immediately after installing the new callback and the return
134270    ** value from sqlite3FaultSim(0) becomes the return from
134271    ** sqlite3_test_control().
134272    */
134273    case SQLITE_TESTCTRL_FAULT_INSTALL: {
134274      /* MSVC is picky about pulling func ptrs from va lists.
134275      ** http://support.microsoft.com/kb/47961
134276      ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
134277      */
134278      typedef int(*TESTCALLBACKFUNC_t)(int);
134279      sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
134280      rc = sqlite3FaultSim(0);
134281      break;
134282    }
134283
134284    /*
134285    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
134286    **
134287    ** Register hooks to call to indicate which malloc() failures
134288    ** are benign.
134289    */
134290    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
134291      typedef void (*void_function)(void);
134292      void_function xBenignBegin;
134293      void_function xBenignEnd;
134294      xBenignBegin = va_arg(ap, void_function);
134295      xBenignEnd = va_arg(ap, void_function);
134296      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
134297      break;
134298    }
134299
134300    /*
134301    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
134302    **
134303    ** Set the PENDING byte to the value in the argument, if X>0.
134304    ** Make no changes if X==0.  Return the value of the pending byte
134305    ** as it existing before this routine was called.
134306    **
134307    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
134308    ** an incompatible database file format.  Changing the PENDING byte
134309    ** while any database connection is open results in undefined and
134310    ** deleterious behavior.
134311    */
134312    case SQLITE_TESTCTRL_PENDING_BYTE: {
134313      rc = PENDING_BYTE;
134314#ifndef SQLITE_OMIT_WSD
134315      {
134316        unsigned int newVal = va_arg(ap, unsigned int);
134317        if( newVal ) sqlite3PendingByte = newVal;
134318      }
134319#endif
134320      break;
134321    }
134322
134323    /*
134324    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
134325    **
134326    ** This action provides a run-time test to see whether or not
134327    ** assert() was enabled at compile-time.  If X is true and assert()
134328    ** is enabled, then the return value is true.  If X is true and
134329    ** assert() is disabled, then the return value is zero.  If X is
134330    ** false and assert() is enabled, then the assertion fires and the
134331    ** process aborts.  If X is false and assert() is disabled, then the
134332    ** return value is zero.
134333    */
134334    case SQLITE_TESTCTRL_ASSERT: {
134335      volatile int x = 0;
134336      assert( (x = va_arg(ap,int))!=0 );
134337      rc = x;
134338      break;
134339    }
134340
134341
134342    /*
134343    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
134344    **
134345    ** This action provides a run-time test to see how the ALWAYS and
134346    ** NEVER macros were defined at compile-time.
134347    **
134348    ** The return value is ALWAYS(X).
134349    **
134350    ** The recommended test is X==2.  If the return value is 2, that means
134351    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
134352    ** default setting.  If the return value is 1, then ALWAYS() is either
134353    ** hard-coded to true or else it asserts if its argument is false.
134354    ** The first behavior (hard-coded to true) is the case if
134355    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
134356    ** behavior (assert if the argument to ALWAYS() is false) is the case if
134357    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
134358    **
134359    ** The run-time test procedure might look something like this:
134360    **
134361    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
134362    **      // ALWAYS() and NEVER() are no-op pass-through macros
134363    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
134364    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
134365    **    }else{
134366    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
134367    **    }
134368    */
134369    case SQLITE_TESTCTRL_ALWAYS: {
134370      int x = va_arg(ap,int);
134371      rc = ALWAYS(x);
134372      break;
134373    }
134374
134375    /*
134376    **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
134377    **
134378    ** The integer returned reveals the byte-order of the computer on which
134379    ** SQLite is running:
134380    **
134381    **       1     big-endian,    determined at run-time
134382    **      10     little-endian, determined at run-time
134383    **  432101     big-endian,    determined at compile-time
134384    **  123410     little-endian, determined at compile-time
134385    */
134386    case SQLITE_TESTCTRL_BYTEORDER: {
134387      rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
134388      break;
134389    }
134390
134391    /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
134392    **
134393    ** Set the nReserve size to N for the main database on the database
134394    ** connection db.
134395    */
134396    case SQLITE_TESTCTRL_RESERVE: {
134397      sqlite3 *db = va_arg(ap, sqlite3*);
134398      int x = va_arg(ap,int);
134399      sqlite3_mutex_enter(db->mutex);
134400      sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
134401      sqlite3_mutex_leave(db->mutex);
134402      break;
134403    }
134404
134405    /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
134406    **
134407    ** Enable or disable various optimizations for testing purposes.  The
134408    ** argument N is a bitmask of optimizations to be disabled.  For normal
134409    ** operation N should be 0.  The idea is that a test program (like the
134410    ** SQL Logic Test or SLT test module) can run the same SQL multiple times
134411    ** with various optimizations disabled to verify that the same answer
134412    ** is obtained in every case.
134413    */
134414    case SQLITE_TESTCTRL_OPTIMIZATIONS: {
134415      sqlite3 *db = va_arg(ap, sqlite3*);
134416      db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
134417      break;
134418    }
134419
134420#ifdef SQLITE_N_KEYWORD
134421    /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
134422    **
134423    ** If zWord is a keyword recognized by the parser, then return the
134424    ** number of keywords.  Or if zWord is not a keyword, return 0.
134425    **
134426    ** This test feature is only available in the amalgamation since
134427    ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
134428    ** is built using separate source files.
134429    */
134430    case SQLITE_TESTCTRL_ISKEYWORD: {
134431      const char *zWord = va_arg(ap, const char*);
134432      int n = sqlite3Strlen30(zWord);
134433      rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
134434      break;
134435    }
134436#endif
134437
134438    /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
134439    **
134440    ** Pass pFree into sqlite3ScratchFree().
134441    ** If sz>0 then allocate a scratch buffer into pNew.
134442    */
134443    case SQLITE_TESTCTRL_SCRATCHMALLOC: {
134444      void *pFree, **ppNew;
134445      int sz;
134446      sz = va_arg(ap, int);
134447      ppNew = va_arg(ap, void**);
134448      pFree = va_arg(ap, void*);
134449      if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
134450      sqlite3ScratchFree(pFree);
134451      break;
134452    }
134453
134454    /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
134455    **
134456    ** If parameter onoff is non-zero, configure the wrappers so that all
134457    ** subsequent calls to localtime() and variants fail. If onoff is zero,
134458    ** undo this setting.
134459    */
134460    case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
134461      sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
134462      break;
134463    }
134464
134465    /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
134466    **
134467    ** Set or clear a flag that indicates that the database file is always well-
134468    ** formed and never corrupt.  This flag is clear by default, indicating that
134469    ** database files might have arbitrary corruption.  Setting the flag during
134470    ** testing causes certain assert() statements in the code to be activated
134471    ** that demonstrat invariants on well-formed database files.
134472    */
134473    case SQLITE_TESTCTRL_NEVER_CORRUPT: {
134474      sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
134475      break;
134476    }
134477
134478
134479    /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
134480    **
134481    ** Set the VDBE coverage callback function to xCallback with context
134482    ** pointer ptr.
134483    */
134484    case SQLITE_TESTCTRL_VDBE_COVERAGE: {
134485#ifdef SQLITE_VDBE_COVERAGE
134486      typedef void (*branch_callback)(void*,int,u8,u8);
134487      sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
134488      sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
134489#endif
134490      break;
134491    }
134492
134493    /*   sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
134494    case SQLITE_TESTCTRL_SORTER_MMAP: {
134495      sqlite3 *db = va_arg(ap, sqlite3*);
134496      db->nMaxSorterMmap = va_arg(ap, int);
134497      break;
134498    }
134499
134500    /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
134501    **
134502    ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
134503    ** not.
134504    */
134505    case SQLITE_TESTCTRL_ISINIT: {
134506      if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
134507      break;
134508    }
134509
134510    /*  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
134511    **
134512    ** This test control is used to create imposter tables.  "db" is a pointer
134513    ** to the database connection.  dbName is the database name (ex: "main" or
134514    ** "temp") which will receive the imposter.  "onOff" turns imposter mode on
134515    ** or off.  "tnum" is the root page of the b-tree to which the imposter
134516    ** table should connect.
134517    **
134518    ** Enable imposter mode only when the schema has already been parsed.  Then
134519    ** run a single CREATE TABLE statement to construct the imposter table in
134520    ** the parsed schema.  Then turn imposter mode back off again.
134521    **
134522    ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
134523    ** the schema to be reparsed the next time it is needed.  This has the
134524    ** effect of erasing all imposter tables.
134525    */
134526    case SQLITE_TESTCTRL_IMPOSTER: {
134527      sqlite3 *db = va_arg(ap, sqlite3*);
134528      sqlite3_mutex_enter(db->mutex);
134529      db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
134530      db->init.busy = db->init.imposterTable = va_arg(ap,int);
134531      db->init.newTnum = va_arg(ap,int);
134532      if( db->init.busy==0 && db->init.newTnum>0 ){
134533        sqlite3ResetAllSchemasOfConnection(db);
134534      }
134535      sqlite3_mutex_leave(db->mutex);
134536      break;
134537    }
134538  }
134539  va_end(ap);
134540#endif /* SQLITE_OMIT_BUILTIN_TEST */
134541  return rc;
134542}
134543
134544/*
134545** This is a utility routine, useful to VFS implementations, that checks
134546** to see if a database file was a URI that contained a specific query
134547** parameter, and if so obtains the value of the query parameter.
134548**
134549** The zFilename argument is the filename pointer passed into the xOpen()
134550** method of a VFS implementation.  The zParam argument is the name of the
134551** query parameter we seek.  This routine returns the value of the zParam
134552** parameter if it exists.  If the parameter does not exist, this routine
134553** returns a NULL pointer.
134554*/
134555SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam){
134556  if( zFilename==0 || zParam==0 ) return 0;
134557  zFilename += sqlite3Strlen30(zFilename) + 1;
134558  while( zFilename[0] ){
134559    int x = strcmp(zFilename, zParam);
134560    zFilename += sqlite3Strlen30(zFilename) + 1;
134561    if( x==0 ) return zFilename;
134562    zFilename += sqlite3Strlen30(zFilename) + 1;
134563  }
134564  return 0;
134565}
134566
134567/*
134568** Return a boolean value for a query parameter.
134569*/
134570SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
134571  const char *z = sqlite3_uri_parameter(zFilename, zParam);
134572  bDflt = bDflt!=0;
134573  return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
134574}
134575
134576/*
134577** Return a 64-bit integer value for a query parameter.
134578*/
134579SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(
134580  const char *zFilename,    /* Filename as passed to xOpen */
134581  const char *zParam,       /* URI parameter sought */
134582  sqlite3_int64 bDflt       /* return if parameter is missing */
134583){
134584  const char *z = sqlite3_uri_parameter(zFilename, zParam);
134585  sqlite3_int64 v;
134586  if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
134587    bDflt = v;
134588  }
134589  return bDflt;
134590}
134591
134592/*
134593** Return the Btree pointer identified by zDbName.  Return NULL if not found.
134594*/
134595SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
134596  int i;
134597  for(i=0; i<db->nDb; i++){
134598    if( db->aDb[i].pBt
134599     && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
134600    ){
134601      return db->aDb[i].pBt;
134602    }
134603  }
134604  return 0;
134605}
134606
134607/*
134608** Return the filename of the database associated with a database
134609** connection.
134610*/
134611SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName){
134612  Btree *pBt;
134613#ifdef SQLITE_ENABLE_API_ARMOR
134614  if( !sqlite3SafetyCheckOk(db) ){
134615    (void)SQLITE_MISUSE_BKPT;
134616    return 0;
134617  }
134618#endif
134619  pBt = sqlite3DbNameToBtree(db, zDbName);
134620  return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
134621}
134622
134623/*
134624** Return 1 if database is read-only or 0 if read/write.  Return -1 if
134625** no such database exists.
134626*/
134627SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
134628  Btree *pBt;
134629#ifdef SQLITE_ENABLE_API_ARMOR
134630  if( !sqlite3SafetyCheckOk(db) ){
134631    (void)SQLITE_MISUSE_BKPT;
134632    return -1;
134633  }
134634#endif
134635  pBt = sqlite3DbNameToBtree(db, zDbName);
134636  return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
134637}
134638
134639/************** End of main.c ************************************************/
134640/************** Begin file notify.c ******************************************/
134641/*
134642** 2009 March 3
134643**
134644** The author disclaims copyright to this source code.  In place of
134645** a legal notice, here is a blessing:
134646**
134647**    May you do good and not evil.
134648**    May you find forgiveness for yourself and forgive others.
134649**    May you share freely, never taking more than you give.
134650**
134651*************************************************************************
134652**
134653** This file contains the implementation of the sqlite3_unlock_notify()
134654** API method and its associated functionality.
134655*/
134656/* #include "sqliteInt.h" */
134657/* #include "btreeInt.h" */
134658
134659/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
134660#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
134661
134662/*
134663** Public interfaces:
134664**
134665**   sqlite3ConnectionBlocked()
134666**   sqlite3ConnectionUnlocked()
134667**   sqlite3ConnectionClosed()
134668**   sqlite3_unlock_notify()
134669*/
134670
134671#define assertMutexHeld() \
134672  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
134673
134674/*
134675** Head of a linked list of all sqlite3 objects created by this process
134676** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
134677** is not NULL. This variable may only accessed while the STATIC_MASTER
134678** mutex is held.
134679*/
134680static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
134681
134682#ifndef NDEBUG
134683/*
134684** This function is a complex assert() that verifies the following
134685** properties of the blocked connections list:
134686**
134687**   1) Each entry in the list has a non-NULL value for either
134688**      pUnlockConnection or pBlockingConnection, or both.
134689**
134690**   2) All entries in the list that share a common value for
134691**      xUnlockNotify are grouped together.
134692**
134693**   3) If the argument db is not NULL, then none of the entries in the
134694**      blocked connections list have pUnlockConnection or pBlockingConnection
134695**      set to db. This is used when closing connection db.
134696*/
134697static void checkListProperties(sqlite3 *db){
134698  sqlite3 *p;
134699  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
134700    int seen = 0;
134701    sqlite3 *p2;
134702
134703    /* Verify property (1) */
134704    assert( p->pUnlockConnection || p->pBlockingConnection );
134705
134706    /* Verify property (2) */
134707    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
134708      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
134709      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
134710      assert( db==0 || p->pUnlockConnection!=db );
134711      assert( db==0 || p->pBlockingConnection!=db );
134712    }
134713  }
134714}
134715#else
134716# define checkListProperties(x)
134717#endif
134718
134719/*
134720** Remove connection db from the blocked connections list. If connection
134721** db is not currently a part of the list, this function is a no-op.
134722*/
134723static void removeFromBlockedList(sqlite3 *db){
134724  sqlite3 **pp;
134725  assertMutexHeld();
134726  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
134727    if( *pp==db ){
134728      *pp = (*pp)->pNextBlocked;
134729      break;
134730    }
134731  }
134732}
134733
134734/*
134735** Add connection db to the blocked connections list. It is assumed
134736** that it is not already a part of the list.
134737*/
134738static void addToBlockedList(sqlite3 *db){
134739  sqlite3 **pp;
134740  assertMutexHeld();
134741  for(
134742    pp=&sqlite3BlockedList;
134743    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
134744    pp=&(*pp)->pNextBlocked
134745  );
134746  db->pNextBlocked = *pp;
134747  *pp = db;
134748}
134749
134750/*
134751** Obtain the STATIC_MASTER mutex.
134752*/
134753static void enterMutex(void){
134754  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
134755  checkListProperties(0);
134756}
134757
134758/*
134759** Release the STATIC_MASTER mutex.
134760*/
134761static void leaveMutex(void){
134762  assertMutexHeld();
134763  checkListProperties(0);
134764  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
134765}
134766
134767/*
134768** Register an unlock-notify callback.
134769**
134770** This is called after connection "db" has attempted some operation
134771** but has received an SQLITE_LOCKED error because another connection
134772** (call it pOther) in the same process was busy using the same shared
134773** cache.  pOther is found by looking at db->pBlockingConnection.
134774**
134775** If there is no blocking connection, the callback is invoked immediately,
134776** before this routine returns.
134777**
134778** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
134779** a deadlock.
134780**
134781** Otherwise, make arrangements to invoke xNotify when pOther drops
134782** its locks.
134783**
134784** Each call to this routine overrides any prior callbacks registered
134785** on the same "db".  If xNotify==0 then any prior callbacks are immediately
134786** cancelled.
134787*/
134788SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
134789  sqlite3 *db,
134790  void (*xNotify)(void **, int),
134791  void *pArg
134792){
134793  int rc = SQLITE_OK;
134794
134795  sqlite3_mutex_enter(db->mutex);
134796  enterMutex();
134797
134798  if( xNotify==0 ){
134799    removeFromBlockedList(db);
134800    db->pBlockingConnection = 0;
134801    db->pUnlockConnection = 0;
134802    db->xUnlockNotify = 0;
134803    db->pUnlockArg = 0;
134804  }else if( 0==db->pBlockingConnection ){
134805    /* The blocking transaction has been concluded. Or there never was a
134806    ** blocking transaction. In either case, invoke the notify callback
134807    ** immediately.
134808    */
134809    xNotify(&pArg, 1);
134810  }else{
134811    sqlite3 *p;
134812
134813    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
134814    if( p ){
134815      rc = SQLITE_LOCKED;              /* Deadlock detected. */
134816    }else{
134817      db->pUnlockConnection = db->pBlockingConnection;
134818      db->xUnlockNotify = xNotify;
134819      db->pUnlockArg = pArg;
134820      removeFromBlockedList(db);
134821      addToBlockedList(db);
134822    }
134823  }
134824
134825  leaveMutex();
134826  assert( !db->mallocFailed );
134827  sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
134828  sqlite3_mutex_leave(db->mutex);
134829  return rc;
134830}
134831
134832/*
134833** This function is called while stepping or preparing a statement
134834** associated with connection db. The operation will return SQLITE_LOCKED
134835** to the user because it requires a lock that will not be available
134836** until connection pBlocker concludes its current transaction.
134837*/
134838SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
134839  enterMutex();
134840  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
134841    addToBlockedList(db);
134842  }
134843  db->pBlockingConnection = pBlocker;
134844  leaveMutex();
134845}
134846
134847/*
134848** This function is called when
134849** the transaction opened by database db has just finished. Locks held
134850** by database connection db have been released.
134851**
134852** This function loops through each entry in the blocked connections
134853** list and does the following:
134854**
134855**   1) If the sqlite3.pBlockingConnection member of a list entry is
134856**      set to db, then set pBlockingConnection=0.
134857**
134858**   2) If the sqlite3.pUnlockConnection member of a list entry is
134859**      set to db, then invoke the configured unlock-notify callback and
134860**      set pUnlockConnection=0.
134861**
134862**   3) If the two steps above mean that pBlockingConnection==0 and
134863**      pUnlockConnection==0, remove the entry from the blocked connections
134864**      list.
134865*/
134866SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
134867  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
134868  int nArg = 0;                            /* Number of entries in aArg[] */
134869  sqlite3 **pp;                            /* Iterator variable */
134870  void **aArg;               /* Arguments to the unlock callback */
134871  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
134872  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
134873
134874  aArg = aStatic;
134875  enterMutex();         /* Enter STATIC_MASTER mutex */
134876
134877  /* This loop runs once for each entry in the blocked-connections list. */
134878  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
134879    sqlite3 *p = *pp;
134880
134881    /* Step 1. */
134882    if( p->pBlockingConnection==db ){
134883      p->pBlockingConnection = 0;
134884    }
134885
134886    /* Step 2. */
134887    if( p->pUnlockConnection==db ){
134888      assert( p->xUnlockNotify );
134889      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
134890        xUnlockNotify(aArg, nArg);
134891        nArg = 0;
134892      }
134893
134894      sqlite3BeginBenignMalloc();
134895      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
134896      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
134897      if( (!aDyn && nArg==(int)ArraySize(aStatic))
134898       || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
134899      ){
134900        /* The aArg[] array needs to grow. */
134901        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
134902        if( pNew ){
134903          memcpy(pNew, aArg, nArg*sizeof(void *));
134904          sqlite3_free(aDyn);
134905          aDyn = aArg = pNew;
134906        }else{
134907          /* This occurs when the array of context pointers that need to
134908          ** be passed to the unlock-notify callback is larger than the
134909          ** aStatic[] array allocated on the stack and the attempt to
134910          ** allocate a larger array from the heap has failed.
134911          **
134912          ** This is a difficult situation to handle. Returning an error
134913          ** code to the caller is insufficient, as even if an error code
134914          ** is returned the transaction on connection db will still be
134915          ** closed and the unlock-notify callbacks on blocked connections
134916          ** will go unissued. This might cause the application to wait
134917          ** indefinitely for an unlock-notify callback that will never
134918          ** arrive.
134919          **
134920          ** Instead, invoke the unlock-notify callback with the context
134921          ** array already accumulated. We can then clear the array and
134922          ** begin accumulating any further context pointers without
134923          ** requiring any dynamic allocation. This is sub-optimal because
134924          ** it means that instead of one callback with a large array of
134925          ** context pointers the application will receive two or more
134926          ** callbacks with smaller arrays of context pointers, which will
134927          ** reduce the applications ability to prioritize multiple
134928          ** connections. But it is the best that can be done under the
134929          ** circumstances.
134930          */
134931          xUnlockNotify(aArg, nArg);
134932          nArg = 0;
134933        }
134934      }
134935      sqlite3EndBenignMalloc();
134936
134937      aArg[nArg++] = p->pUnlockArg;
134938      xUnlockNotify = p->xUnlockNotify;
134939      p->pUnlockConnection = 0;
134940      p->xUnlockNotify = 0;
134941      p->pUnlockArg = 0;
134942    }
134943
134944    /* Step 3. */
134945    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
134946      /* Remove connection p from the blocked connections list. */
134947      *pp = p->pNextBlocked;
134948      p->pNextBlocked = 0;
134949    }else{
134950      pp = &p->pNextBlocked;
134951    }
134952  }
134953
134954  if( nArg!=0 ){
134955    xUnlockNotify(aArg, nArg);
134956  }
134957  sqlite3_free(aDyn);
134958  leaveMutex();         /* Leave STATIC_MASTER mutex */
134959}
134960
134961/*
134962** This is called when the database connection passed as an argument is
134963** being closed. The connection is removed from the blocked list.
134964*/
134965SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
134966  sqlite3ConnectionUnlocked(db);
134967  enterMutex();
134968  removeFromBlockedList(db);
134969  checkListProperties(db);
134970  leaveMutex();
134971}
134972#endif
134973
134974/************** End of notify.c **********************************************/
134975/************** Begin file fts3.c ********************************************/
134976/*
134977** 2006 Oct 10
134978**
134979** The author disclaims copyright to this source code.  In place of
134980** a legal notice, here is a blessing:
134981**
134982**    May you do good and not evil.
134983**    May you find forgiveness for yourself and forgive others.
134984**    May you share freely, never taking more than you give.
134985**
134986******************************************************************************
134987**
134988** This is an SQLite module implementing full-text search.
134989*/
134990
134991/*
134992** The code in this file is only compiled if:
134993**
134994**     * The FTS3 module is being built as an extension
134995**       (in which case SQLITE_CORE is not defined), or
134996**
134997**     * The FTS3 module is being built into the core of
134998**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
134999*/
135000
135001/* The full-text index is stored in a series of b+tree (-like)
135002** structures called segments which map terms to doclists.  The
135003** structures are like b+trees in layout, but are constructed from the
135004** bottom up in optimal fashion and are not updatable.  Since trees
135005** are built from the bottom up, things will be described from the
135006** bottom up.
135007**
135008**
135009**** Varints ****
135010** The basic unit of encoding is a variable-length integer called a
135011** varint.  We encode variable-length integers in little-endian order
135012** using seven bits * per byte as follows:
135013**
135014** KEY:
135015**         A = 0xxxxxxx    7 bits of data and one flag bit
135016**         B = 1xxxxxxx    7 bits of data and one flag bit
135017**
135018**  7 bits - A
135019** 14 bits - BA
135020** 21 bits - BBA
135021** and so on.
135022**
135023** This is similar in concept to how sqlite encodes "varints" but
135024** the encoding is not the same.  SQLite varints are big-endian
135025** are are limited to 9 bytes in length whereas FTS3 varints are
135026** little-endian and can be up to 10 bytes in length (in theory).
135027**
135028** Example encodings:
135029**
135030**     1:    0x01
135031**   127:    0x7f
135032**   128:    0x81 0x00
135033**
135034**
135035**** Document lists ****
135036** A doclist (document list) holds a docid-sorted list of hits for a
135037** given term.  Doclists hold docids and associated token positions.
135038** A docid is the unique integer identifier for a single document.
135039** A position is the index of a word within the document.  The first
135040** word of the document has a position of 0.
135041**
135042** FTS3 used to optionally store character offsets using a compile-time
135043** option.  But that functionality is no longer supported.
135044**
135045** A doclist is stored like this:
135046**
135047** array {
135048**   varint docid;          (delta from previous doclist)
135049**   array {                (position list for column 0)
135050**     varint position;     (2 more than the delta from previous position)
135051**   }
135052**   array {
135053**     varint POS_COLUMN;   (marks start of position list for new column)
135054**     varint column;       (index of new column)
135055**     array {
135056**       varint position;   (2 more than the delta from previous position)
135057**     }
135058**   }
135059**   varint POS_END;        (marks end of positions for this document.
135060** }
135061**
135062** Here, array { X } means zero or more occurrences of X, adjacent in
135063** memory.  A "position" is an index of a token in the token stream
135064** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
135065** in the same logical place as the position element, and act as sentinals
135066** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
135067** The positions numbers are not stored literally but rather as two more
135068** than the difference from the prior position, or the just the position plus
135069** 2 for the first position.  Example:
135070**
135071**   label:       A B C D E  F  G H   I  J K
135072**   value:     123 5 9 1 1 14 35 0 234 72 0
135073**
135074** The 123 value is the first docid.  For column zero in this document
135075** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
135076** at D signals the start of a new column; the 1 at E indicates that the
135077** new column is column number 1.  There are two positions at 12 and 45
135078** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
135079** 234 at I is the delta to next docid (357).  It has one position 70
135080** (72-2) and then terminates with the 0 at K.
135081**
135082** A "position-list" is the list of positions for multiple columns for
135083** a single docid.  A "column-list" is the set of positions for a single
135084** column.  Hence, a position-list consists of one or more column-lists,
135085** a document record consists of a docid followed by a position-list and
135086** a doclist consists of one or more document records.
135087**
135088** A bare doclist omits the position information, becoming an
135089** array of varint-encoded docids.
135090**
135091**** Segment leaf nodes ****
135092** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
135093** nodes are written using LeafWriter, and read using LeafReader (to
135094** iterate through a single leaf node's data) and LeavesReader (to
135095** iterate through a segment's entire leaf layer).  Leaf nodes have
135096** the format:
135097**
135098** varint iHeight;             (height from leaf level, always 0)
135099** varint nTerm;               (length of first term)
135100** char pTerm[nTerm];          (content of first term)
135101** varint nDoclist;            (length of term's associated doclist)
135102** char pDoclist[nDoclist];    (content of doclist)
135103** array {
135104**                             (further terms are delta-encoded)
135105**   varint nPrefix;           (length of prefix shared with previous term)
135106**   varint nSuffix;           (length of unshared suffix)
135107**   char pTermSuffix[nSuffix];(unshared suffix of next term)
135108**   varint nDoclist;          (length of term's associated doclist)
135109**   char pDoclist[nDoclist];  (content of doclist)
135110** }
135111**
135112** Here, array { X } means zero or more occurrences of X, adjacent in
135113** memory.
135114**
135115** Leaf nodes are broken into blocks which are stored contiguously in
135116** the %_segments table in sorted order.  This means that when the end
135117** of a node is reached, the next term is in the node with the next
135118** greater node id.
135119**
135120** New data is spilled to a new leaf node when the current node
135121** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
135122** larger than STANDALONE_MIN (default 1024) is placed in a standalone
135123** node (a leaf node with a single term and doclist).  The goal of
135124** these settings is to pack together groups of small doclists while
135125** making it efficient to directly access large doclists.  The
135126** assumption is that large doclists represent terms which are more
135127** likely to be query targets.
135128**
135129** TODO(shess) It may be useful for blocking decisions to be more
135130** dynamic.  For instance, it may make more sense to have a 2.5k leaf
135131** node rather than splitting into 2k and .5k nodes.  My intuition is
135132** that this might extend through 2x or 4x the pagesize.
135133**
135134**
135135**** Segment interior nodes ****
135136** Segment interior nodes store blockids for subtree nodes and terms
135137** to describe what data is stored by the each subtree.  Interior
135138** nodes are written using InteriorWriter, and read using
135139** InteriorReader.  InteriorWriters are created as needed when
135140** SegmentWriter creates new leaf nodes, or when an interior node
135141** itself grows too big and must be split.  The format of interior
135142** nodes:
135143**
135144** varint iHeight;           (height from leaf level, always >0)
135145** varint iBlockid;          (block id of node's leftmost subtree)
135146** optional {
135147**   varint nTerm;           (length of first term)
135148**   char pTerm[nTerm];      (content of first term)
135149**   array {
135150**                                (further terms are delta-encoded)
135151**     varint nPrefix;            (length of shared prefix with previous term)
135152**     varint nSuffix;            (length of unshared suffix)
135153**     char pTermSuffix[nSuffix]; (unshared suffix of next term)
135154**   }
135155** }
135156**
135157** Here, optional { X } means an optional element, while array { X }
135158** means zero or more occurrences of X, adjacent in memory.
135159**
135160** An interior node encodes n terms separating n+1 subtrees.  The
135161** subtree blocks are contiguous, so only the first subtree's blockid
135162** is encoded.  The subtree at iBlockid will contain all terms less
135163** than the first term encoded (or all terms if no term is encoded).
135164** Otherwise, for terms greater than or equal to pTerm[i] but less
135165** than pTerm[i+1], the subtree for that term will be rooted at
135166** iBlockid+i.  Interior nodes only store enough term data to
135167** distinguish adjacent children (if the rightmost term of the left
135168** child is "something", and the leftmost term of the right child is
135169** "wicked", only "w" is stored).
135170**
135171** New data is spilled to a new interior node at the same height when
135172** the current node exceeds INTERIOR_MAX bytes (default 2048).
135173** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
135174** interior nodes and making the tree too skinny.  The interior nodes
135175** at a given height are naturally tracked by interior nodes at
135176** height+1, and so on.
135177**
135178**
135179**** Segment directory ****
135180** The segment directory in table %_segdir stores meta-information for
135181** merging and deleting segments, and also the root node of the
135182** segment's tree.
135183**
135184** The root node is the top node of the segment's tree after encoding
135185** the entire segment, restricted to ROOT_MAX bytes (default 1024).
135186** This could be either a leaf node or an interior node.  If the top
135187** node requires more than ROOT_MAX bytes, it is flushed to %_segments
135188** and a new root interior node is generated (which should always fit
135189** within ROOT_MAX because it only needs space for 2 varints, the
135190** height and the blockid of the previous root).
135191**
135192** The meta-information in the segment directory is:
135193**   level               - segment level (see below)
135194**   idx                 - index within level
135195**                       - (level,idx uniquely identify a segment)
135196**   start_block         - first leaf node
135197**   leaves_end_block    - last leaf node
135198**   end_block           - last block (including interior nodes)
135199**   root                - contents of root node
135200**
135201** If the root node is a leaf node, then start_block,
135202** leaves_end_block, and end_block are all 0.
135203**
135204**
135205**** Segment merging ****
135206** To amortize update costs, segments are grouped into levels and
135207** merged in batches.  Each increase in level represents exponentially
135208** more documents.
135209**
135210** New documents (actually, document updates) are tokenized and
135211** written individually (using LeafWriter) to a level 0 segment, with
135212** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
135213** level 0 segments are merged into a single level 1 segment.  Level 1
135214** is populated like level 0, and eventually MERGE_COUNT level 1
135215** segments are merged to a single level 2 segment (representing
135216** MERGE_COUNT^2 updates), and so on.
135217**
135218** A segment merge traverses all segments at a given level in
135219** parallel, performing a straightforward sorted merge.  Since segment
135220** leaf nodes are written in to the %_segments table in order, this
135221** merge traverses the underlying sqlite disk structures efficiently.
135222** After the merge, all segment blocks from the merged level are
135223** deleted.
135224**
135225** MERGE_COUNT controls how often we merge segments.  16 seems to be
135226** somewhat of a sweet spot for insertion performance.  32 and 64 show
135227** very similar performance numbers to 16 on insertion, though they're
135228** a tiny bit slower (perhaps due to more overhead in merge-time
135229** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
135230** 16, 2 about 66% slower than 16.
135231**
135232** At query time, high MERGE_COUNT increases the number of segments
135233** which need to be scanned and merged.  For instance, with 100k docs
135234** inserted:
135235**
135236**    MERGE_COUNT   segments
135237**       16           25
135238**        8           12
135239**        4           10
135240**        2            6
135241**
135242** This appears to have only a moderate impact on queries for very
135243** frequent terms (which are somewhat dominated by segment merge
135244** costs), and infrequent and non-existent terms still seem to be fast
135245** even with many segments.
135246**
135247** TODO(shess) That said, it would be nice to have a better query-side
135248** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
135249** optimizations to things like doclist merging will swing the sweet
135250** spot around.
135251**
135252**
135253**
135254**** Handling of deletions and updates ****
135255** Since we're using a segmented structure, with no docid-oriented
135256** index into the term index, we clearly cannot simply update the term
135257** index when a document is deleted or updated.  For deletions, we
135258** write an empty doclist (varint(docid) varint(POS_END)), for updates
135259** we simply write the new doclist.  Segment merges overwrite older
135260** data for a particular docid with newer data, so deletes or updates
135261** will eventually overtake the earlier data and knock it out.  The
135262** query logic likewise merges doclists so that newer data knocks out
135263** older data.
135264*/
135265
135266/************** Include fts3Int.h in the middle of fts3.c ********************/
135267/************** Begin file fts3Int.h *****************************************/
135268/*
135269** 2009 Nov 12
135270**
135271** The author disclaims copyright to this source code.  In place of
135272** a legal notice, here is a blessing:
135273**
135274**    May you do good and not evil.
135275**    May you find forgiveness for yourself and forgive others.
135276**    May you share freely, never taking more than you give.
135277**
135278******************************************************************************
135279**
135280*/
135281#ifndef _FTSINT_H
135282#define _FTSINT_H
135283
135284#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
135285# define NDEBUG 1
135286#endif
135287
135288/*
135289** FTS4 is really an extension for FTS3.  It is enabled using the
135290** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
135291** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
135292*/
135293#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
135294# define SQLITE_ENABLE_FTS3
135295#endif
135296
135297#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
135298
135299/* If not building as part of the core, include sqlite3ext.h. */
135300#ifndef SQLITE_CORE
135301/* # include "sqlite3ext.h"  */
135302SQLITE_EXTENSION_INIT3
135303#endif
135304
135305/* #include "sqlite3.h" */
135306/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
135307/************** Begin file fts3_tokenizer.h **********************************/
135308/*
135309** 2006 July 10
135310**
135311** The author disclaims copyright to this source code.
135312**
135313*************************************************************************
135314** Defines the interface to tokenizers used by fulltext-search.  There
135315** are three basic components:
135316**
135317** sqlite3_tokenizer_module is a singleton defining the tokenizer
135318** interface functions.  This is essentially the class structure for
135319** tokenizers.
135320**
135321** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
135322** including customization information defined at creation time.
135323**
135324** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
135325** tokens from a particular input.
135326*/
135327#ifndef _FTS3_TOKENIZER_H_
135328#define _FTS3_TOKENIZER_H_
135329
135330/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
135331** If tokenizers are to be allowed to call sqlite3_*() functions, then
135332** we will need a way to register the API consistently.
135333*/
135334/* #include "sqlite3.h" */
135335
135336/*
135337** Structures used by the tokenizer interface. When a new tokenizer
135338** implementation is registered, the caller provides a pointer to
135339** an sqlite3_tokenizer_module containing pointers to the callback
135340** functions that make up an implementation.
135341**
135342** When an fts3 table is created, it passes any arguments passed to
135343** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
135344** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
135345** implementation. The xCreate() function in turn returns an
135346** sqlite3_tokenizer structure representing the specific tokenizer to
135347** be used for the fts3 table (customized by the tokenizer clause arguments).
135348**
135349** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
135350** method is called. It returns an sqlite3_tokenizer_cursor object
135351** that may be used to tokenize a specific input buffer based on
135352** the tokenization rules supplied by a specific sqlite3_tokenizer
135353** object.
135354*/
135355typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
135356typedef struct sqlite3_tokenizer sqlite3_tokenizer;
135357typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
135358
135359struct sqlite3_tokenizer_module {
135360
135361  /*
135362  ** Structure version. Should always be set to 0 or 1.
135363  */
135364  int iVersion;
135365
135366  /*
135367  ** Create a new tokenizer. The values in the argv[] array are the
135368  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
135369  ** TABLE statement that created the fts3 table. For example, if
135370  ** the following SQL is executed:
135371  **
135372  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
135373  **
135374  ** then argc is set to 2, and the argv[] array contains pointers
135375  ** to the strings "arg1" and "arg2".
135376  **
135377  ** This method should return either SQLITE_OK (0), or an SQLite error
135378  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
135379  ** to point at the newly created tokenizer structure. The generic
135380  ** sqlite3_tokenizer.pModule variable should not be initialized by
135381  ** this callback. The caller will do so.
135382  */
135383  int (*xCreate)(
135384    int argc,                           /* Size of argv array */
135385    const char *const*argv,             /* Tokenizer argument strings */
135386    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
135387  );
135388
135389  /*
135390  ** Destroy an existing tokenizer. The fts3 module calls this method
135391  ** exactly once for each successful call to xCreate().
135392  */
135393  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
135394
135395  /*
135396  ** Create a tokenizer cursor to tokenize an input buffer. The caller
135397  ** is responsible for ensuring that the input buffer remains valid
135398  ** until the cursor is closed (using the xClose() method).
135399  */
135400  int (*xOpen)(
135401    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
135402    const char *pInput, int nBytes,      /* Input buffer */
135403    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
135404  );
135405
135406  /*
135407  ** Destroy an existing tokenizer cursor. The fts3 module calls this
135408  ** method exactly once for each successful call to xOpen().
135409  */
135410  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
135411
135412  /*
135413  ** Retrieve the next token from the tokenizer cursor pCursor. This
135414  ** method should either return SQLITE_OK and set the values of the
135415  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
135416  ** the end of the buffer has been reached, or an SQLite error code.
135417  **
135418  ** *ppToken should be set to point at a buffer containing the
135419  ** normalized version of the token (i.e. after any case-folding and/or
135420  ** stemming has been performed). *pnBytes should be set to the length
135421  ** of this buffer in bytes. The input text that generated the token is
135422  ** identified by the byte offsets returned in *piStartOffset and
135423  ** *piEndOffset. *piStartOffset should be set to the index of the first
135424  ** byte of the token in the input buffer. *piEndOffset should be set
135425  ** to the index of the first byte just past the end of the token in
135426  ** the input buffer.
135427  **
135428  ** The buffer *ppToken is set to point at is managed by the tokenizer
135429  ** implementation. It is only required to be valid until the next call
135430  ** to xNext() or xClose().
135431  */
135432  /* TODO(shess) current implementation requires pInput to be
135433  ** nul-terminated.  This should either be fixed, or pInput/nBytes
135434  ** should be converted to zInput.
135435  */
135436  int (*xNext)(
135437    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
135438    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
135439    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
135440    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
135441    int *piPosition      /* OUT: Number of tokens returned before this one */
135442  );
135443
135444  /***********************************************************************
135445  ** Methods below this point are only available if iVersion>=1.
135446  */
135447
135448  /*
135449  ** Configure the language id of a tokenizer cursor.
135450  */
135451  int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
135452};
135453
135454struct sqlite3_tokenizer {
135455  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
135456  /* Tokenizer implementations will typically add additional fields */
135457};
135458
135459struct sqlite3_tokenizer_cursor {
135460  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
135461  /* Tokenizer implementations will typically add additional fields */
135462};
135463
135464int fts3_global_term_cnt(int iTerm, int iCol);
135465int fts3_term_cnt(int iTerm, int iCol);
135466
135467
135468#endif /* _FTS3_TOKENIZER_H_ */
135469
135470/************** End of fts3_tokenizer.h **************************************/
135471/************** Continuing where we left off in fts3Int.h ********************/
135472/************** Include fts3_hash.h in the middle of fts3Int.h ***************/
135473/************** Begin file fts3_hash.h ***************************************/
135474/*
135475** 2001 September 22
135476**
135477** The author disclaims copyright to this source code.  In place of
135478** a legal notice, here is a blessing:
135479**
135480**    May you do good and not evil.
135481**    May you find forgiveness for yourself and forgive others.
135482**    May you share freely, never taking more than you give.
135483**
135484*************************************************************************
135485** This is the header file for the generic hash-table implementation
135486** used in SQLite.  We've modified it slightly to serve as a standalone
135487** hash table implementation for the full-text indexing module.
135488**
135489*/
135490#ifndef _FTS3_HASH_H_
135491#define _FTS3_HASH_H_
135492
135493/* Forward declarations of structures. */
135494typedef struct Fts3Hash Fts3Hash;
135495typedef struct Fts3HashElem Fts3HashElem;
135496
135497/* A complete hash table is an instance of the following structure.
135498** The internals of this structure are intended to be opaque -- client
135499** code should not attempt to access or modify the fields of this structure
135500** directly.  Change this structure only by using the routines below.
135501** However, many of the "procedures" and "functions" for modifying and
135502** accessing this structure are really macros, so we can't really make
135503** this structure opaque.
135504*/
135505struct Fts3Hash {
135506  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
135507  char copyKey;           /* True if copy of key made on insert */
135508  int count;              /* Number of entries in this table */
135509  Fts3HashElem *first;    /* The first element of the array */
135510  int htsize;             /* Number of buckets in the hash table */
135511  struct _fts3ht {        /* the hash table */
135512    int count;               /* Number of entries with this hash */
135513    Fts3HashElem *chain;     /* Pointer to first entry with this hash */
135514  } *ht;
135515};
135516
135517/* Each element in the hash table is an instance of the following
135518** structure.  All elements are stored on a single doubly-linked list.
135519**
135520** Again, this structure is intended to be opaque, but it can't really
135521** be opaque because it is used by macros.
135522*/
135523struct Fts3HashElem {
135524  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
135525  void *data;                /* Data associated with this element */
135526  void *pKey; int nKey;      /* Key associated with this element */
135527};
135528
135529/*
135530** There are 2 different modes of operation for a hash table:
135531**
135532**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
135533**                           (including the null-terminator, if any).  Case
135534**                           is respected in comparisons.
135535**
135536**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
135537**                           memcmp() is used to compare keys.
135538**
135539** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
135540*/
135541#define FTS3_HASH_STRING    1
135542#define FTS3_HASH_BINARY    2
135543
135544/*
135545** Access routines.  To delete, insert a NULL pointer.
135546*/
135547SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
135548SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
135549SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
135550SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
135551SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
135552
135553/*
135554** Shorthand for the functions above
135555*/
135556#define fts3HashInit     sqlite3Fts3HashInit
135557#define fts3HashInsert   sqlite3Fts3HashInsert
135558#define fts3HashFind     sqlite3Fts3HashFind
135559#define fts3HashClear    sqlite3Fts3HashClear
135560#define fts3HashFindElem sqlite3Fts3HashFindElem
135561
135562/*
135563** Macros for looping over all elements of a hash table.  The idiom is
135564** like this:
135565**
135566**   Fts3Hash h;
135567**   Fts3HashElem *p;
135568**   ...
135569**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
135570**     SomeStructure *pData = fts3HashData(p);
135571**     // do something with pData
135572**   }
135573*/
135574#define fts3HashFirst(H)  ((H)->first)
135575#define fts3HashNext(E)   ((E)->next)
135576#define fts3HashData(E)   ((E)->data)
135577#define fts3HashKey(E)    ((E)->pKey)
135578#define fts3HashKeysize(E) ((E)->nKey)
135579
135580/*
135581** Number of entries in a hash table
135582*/
135583#define fts3HashCount(H)  ((H)->count)
135584
135585#endif /* _FTS3_HASH_H_ */
135586
135587/************** End of fts3_hash.h *******************************************/
135588/************** Continuing where we left off in fts3Int.h ********************/
135589
135590/*
135591** This constant determines the maximum depth of an FTS expression tree
135592** that the library will create and use. FTS uses recursion to perform
135593** various operations on the query tree, so the disadvantage of a large
135594** limit is that it may allow very large queries to use large amounts
135595** of stack space (perhaps causing a stack overflow).
135596*/
135597#ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
135598# define SQLITE_FTS3_MAX_EXPR_DEPTH 12
135599#endif
135600
135601
135602/*
135603** This constant controls how often segments are merged. Once there are
135604** FTS3_MERGE_COUNT segments of level N, they are merged into a single
135605** segment of level N+1.
135606*/
135607#define FTS3_MERGE_COUNT 16
135608
135609/*
135610** This is the maximum amount of data (in bytes) to store in the
135611** Fts3Table.pendingTerms hash table. Normally, the hash table is
135612** populated as documents are inserted/updated/deleted in a transaction
135613** and used to create a new segment when the transaction is committed.
135614** However if this limit is reached midway through a transaction, a new
135615** segment is created and the hash table cleared immediately.
135616*/
135617#define FTS3_MAX_PENDING_DATA (1*1024*1024)
135618
135619/*
135620** Macro to return the number of elements in an array. SQLite has a
135621** similar macro called ArraySize(). Use a different name to avoid
135622** a collision when building an amalgamation with built-in FTS3.
135623*/
135624#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
135625
135626
135627#ifndef MIN
135628# define MIN(x,y) ((x)<(y)?(x):(y))
135629#endif
135630#ifndef MAX
135631# define MAX(x,y) ((x)>(y)?(x):(y))
135632#endif
135633
135634/*
135635** Maximum length of a varint encoded integer. The varint format is different
135636** from that used by SQLite, so the maximum length is 10, not 9.
135637*/
135638#define FTS3_VARINT_MAX 10
135639
135640/*
135641** FTS4 virtual tables may maintain multiple indexes - one index of all terms
135642** in the document set and zero or more prefix indexes. All indexes are stored
135643** as one or more b+-trees in the %_segments and %_segdir tables.
135644**
135645** It is possible to determine which index a b+-tree belongs to based on the
135646** value stored in the "%_segdir.level" column. Given this value L, the index
135647** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
135648** level values between 0 and 1023 (inclusive) belong to index 0, all levels
135649** between 1024 and 2047 to index 1, and so on.
135650**
135651** It is considered impossible for an index to use more than 1024 levels. In
135652** theory though this may happen, but only after at least
135653** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
135654*/
135655#define FTS3_SEGDIR_MAXLEVEL      1024
135656#define FTS3_SEGDIR_MAXLEVEL_STR "1024"
135657
135658/*
135659** The testcase() macro is only used by the amalgamation.  If undefined,
135660** make it a no-op.
135661*/
135662#ifndef testcase
135663# define testcase(X)
135664#endif
135665
135666/*
135667** Terminator values for position-lists and column-lists.
135668*/
135669#define POS_COLUMN  (1)     /* Column-list terminator */
135670#define POS_END     (0)     /* Position-list terminator */
135671
135672/*
135673** This section provides definitions to allow the
135674** FTS3 extension to be compiled outside of the
135675** amalgamation.
135676*/
135677#ifndef SQLITE_AMALGAMATION
135678/*
135679** Macros indicating that conditional expressions are always true or
135680** false.
135681*/
135682#ifdef SQLITE_COVERAGE_TEST
135683# define ALWAYS(x) (1)
135684# define NEVER(X)  (0)
135685#elif defined(SQLITE_DEBUG)
135686# define ALWAYS(x) sqlite3Fts3Always((x)!=0)
135687# define NEVER(x) sqlite3Fts3Never((x)!=0)
135688SQLITE_PRIVATE int sqlite3Fts3Always(int b);
135689SQLITE_PRIVATE int sqlite3Fts3Never(int b);
135690#else
135691# define ALWAYS(x) (x)
135692# define NEVER(x)  (x)
135693#endif
135694
135695/*
135696** Internal types used by SQLite.
135697*/
135698typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
135699typedef short int i16;            /* 2-byte (or larger) signed integer */
135700typedef unsigned int u32;         /* 4-byte unsigned integer */
135701typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
135702typedef sqlite3_int64 i64;        /* 8-byte signed integer */
135703
135704/*
135705** Macro used to suppress compiler warnings for unused parameters.
135706*/
135707#define UNUSED_PARAMETER(x) (void)(x)
135708
135709/*
135710** Activate assert() only if SQLITE_TEST is enabled.
135711*/
135712#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
135713# define NDEBUG 1
135714#endif
135715
135716/*
135717** The TESTONLY macro is used to enclose variable declarations or
135718** other bits of code that are needed to support the arguments
135719** within testcase() and assert() macros.
135720*/
135721#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
135722# define TESTONLY(X)  X
135723#else
135724# define TESTONLY(X)
135725#endif
135726
135727#endif /* SQLITE_AMALGAMATION */
135728
135729#ifdef SQLITE_DEBUG
135730SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
135731# define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
135732#else
135733# define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
135734#endif
135735
135736typedef struct Fts3Table Fts3Table;
135737typedef struct Fts3Cursor Fts3Cursor;
135738typedef struct Fts3Expr Fts3Expr;
135739typedef struct Fts3Phrase Fts3Phrase;
135740typedef struct Fts3PhraseToken Fts3PhraseToken;
135741
135742typedef struct Fts3Doclist Fts3Doclist;
135743typedef struct Fts3SegFilter Fts3SegFilter;
135744typedef struct Fts3DeferredToken Fts3DeferredToken;
135745typedef struct Fts3SegReader Fts3SegReader;
135746typedef struct Fts3MultiSegReader Fts3MultiSegReader;
135747
135748typedef struct MatchinfoBuffer MatchinfoBuffer;
135749
135750/*
135751** A connection to a fulltext index is an instance of the following
135752** structure. The xCreate and xConnect methods create an instance
135753** of this structure and xDestroy and xDisconnect free that instance.
135754** All other methods receive a pointer to the structure as one of their
135755** arguments.
135756*/
135757struct Fts3Table {
135758  sqlite3_vtab base;              /* Base class used by SQLite core */
135759  sqlite3 *db;                    /* The database connection */
135760  const char *zDb;                /* logical database name */
135761  const char *zName;              /* virtual table name */
135762  int nColumn;                    /* number of named columns in virtual table */
135763  char **azColumn;                /* column names.  malloced */
135764  u8 *abNotindexed;               /* True for 'notindexed' columns */
135765  sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
135766  char *zContentTbl;              /* content=xxx option, or NULL */
135767  char *zLanguageid;              /* languageid=xxx option, or NULL */
135768  int nAutoincrmerge;             /* Value configured by 'automerge' */
135769  u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
135770
135771  /* Precompiled statements used by the implementation. Each of these
135772  ** statements is run and reset within a single virtual table API call.
135773  */
135774  sqlite3_stmt *aStmt[40];
135775
135776  char *zReadExprlist;
135777  char *zWriteExprlist;
135778
135779  int nNodeSize;                  /* Soft limit for node size */
135780  u8 bFts4;                       /* True for FTS4, false for FTS3 */
135781  u8 bHasStat;                    /* True if %_stat table exists (2==unknown) */
135782  u8 bHasDocsize;                 /* True if %_docsize table exists */
135783  u8 bDescIdx;                    /* True if doclists are in reverse order */
135784  u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
135785  int nPgsz;                      /* Page size for host database */
135786  char *zSegmentsTbl;             /* Name of %_segments table */
135787  sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
135788
135789  /*
135790  ** The following array of hash tables is used to buffer pending index
135791  ** updates during transactions. All pending updates buffered at any one
135792  ** time must share a common language-id (see the FTS4 langid= feature).
135793  ** The current language id is stored in variable iPrevLangid.
135794  **
135795  ** A single FTS4 table may have multiple full-text indexes. For each index
135796  ** there is an entry in the aIndex[] array. Index 0 is an index of all the
135797  ** terms that appear in the document set. Each subsequent index in aIndex[]
135798  ** is an index of prefixes of a specific length.
135799  **
135800  ** Variable nPendingData contains an estimate the memory consumed by the
135801  ** pending data structures, including hash table overhead, but not including
135802  ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
135803  ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
135804  ** recently inserted record.
135805  */
135806  int nIndex;                     /* Size of aIndex[] */
135807  struct Fts3Index {
135808    int nPrefix;                  /* Prefix length (0 for main terms index) */
135809    Fts3Hash hPending;            /* Pending terms table for this index */
135810  } *aIndex;
135811  int nMaxPendingData;            /* Max pending data before flush to disk */
135812  int nPendingData;               /* Current bytes of pending data */
135813  sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
135814  int iPrevLangid;                /* Langid of recently inserted document */
135815  int bPrevDelete;                /* True if last operation was a delete */
135816
135817#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
135818  /* State variables used for validating that the transaction control
135819  ** methods of the virtual table are called at appropriate times.  These
135820  ** values do not contribute to FTS functionality; they are used for
135821  ** verifying the operation of the SQLite core.
135822  */
135823  int inTransaction;     /* True after xBegin but before xCommit/xRollback */
135824  int mxSavepoint;       /* Largest valid xSavepoint integer */
135825#endif
135826
135827#ifdef SQLITE_TEST
135828  /* True to disable the incremental doclist optimization. This is controled
135829  ** by special insert command 'test-no-incr-doclist'.  */
135830  int bNoIncrDoclist;
135831#endif
135832};
135833
135834/*
135835** When the core wants to read from the virtual table, it creates a
135836** virtual table cursor (an instance of the following structure) using
135837** the xOpen method. Cursors are destroyed using the xClose method.
135838*/
135839struct Fts3Cursor {
135840  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
135841  i16 eSearch;                    /* Search strategy (see below) */
135842  u8 isEof;                       /* True if at End Of Results */
135843  u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
135844  sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
135845  Fts3Expr *pExpr;                /* Parsed MATCH query string */
135846  int iLangid;                    /* Language being queried for */
135847  int nPhrase;                    /* Number of matchable phrases in query */
135848  Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
135849  sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
135850  char *pNextId;                  /* Pointer into the body of aDoclist */
135851  char *aDoclist;                 /* List of docids for full-text queries */
135852  int nDoclist;                   /* Size of buffer at aDoclist */
135853  u8 bDesc;                       /* True to sort in descending order */
135854  int eEvalmode;                  /* An FTS3_EVAL_XX constant */
135855  int nRowAvg;                    /* Average size of database rows, in pages */
135856  sqlite3_int64 nDoc;             /* Documents in table */
135857  i64 iMinDocid;                  /* Minimum docid to return */
135858  i64 iMaxDocid;                  /* Maximum docid to return */
135859  int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
135860  MatchinfoBuffer *pMIBuffer;     /* Buffer for matchinfo data */
135861};
135862
135863#define FTS3_EVAL_FILTER    0
135864#define FTS3_EVAL_NEXT      1
135865#define FTS3_EVAL_MATCHINFO 2
135866
135867/*
135868** The Fts3Cursor.eSearch member is always set to one of the following.
135869** Actualy, Fts3Cursor.eSearch can be greater than or equal to
135870** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
135871** of the column to be searched.  For example, in
135872**
135873**     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
135874**     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
135875**
135876** Because the LHS of the MATCH operator is 2nd column "b",
135877** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
135878** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
135879** indicating that all columns should be searched,
135880** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
135881*/
135882#define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
135883#define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
135884#define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
135885
135886/*
135887** The lower 16-bits of the sqlite3_index_info.idxNum value set by
135888** the xBestIndex() method contains the Fts3Cursor.eSearch value described
135889** above. The upper 16-bits contain a combination of the following
135890** bits, used to describe extra constraints on full-text searches.
135891*/
135892#define FTS3_HAVE_LANGID    0x00010000      /* languageid=? */
135893#define FTS3_HAVE_DOCID_GE  0x00020000      /* docid>=? */
135894#define FTS3_HAVE_DOCID_LE  0x00040000      /* docid<=? */
135895
135896struct Fts3Doclist {
135897  char *aAll;                    /* Array containing doclist (or NULL) */
135898  int nAll;                      /* Size of a[] in bytes */
135899  char *pNextDocid;              /* Pointer to next docid */
135900
135901  sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
135902  int bFreeList;                 /* True if pList should be sqlite3_free()d */
135903  char *pList;                   /* Pointer to position list following iDocid */
135904  int nList;                     /* Length of position list */
135905};
135906
135907/*
135908** A "phrase" is a sequence of one or more tokens that must match in
135909** sequence.  A single token is the base case and the most common case.
135910** For a sequence of tokens contained in double-quotes (i.e. "one two three")
135911** nToken will be the number of tokens in the string.
135912*/
135913struct Fts3PhraseToken {
135914  char *z;                        /* Text of the token */
135915  int n;                          /* Number of bytes in buffer z */
135916  int isPrefix;                   /* True if token ends with a "*" character */
135917  int bFirst;                     /* True if token must appear at position 0 */
135918
135919  /* Variables above this point are populated when the expression is
135920  ** parsed (by code in fts3_expr.c). Below this point the variables are
135921  ** used when evaluating the expression. */
135922  Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
135923  Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
135924};
135925
135926struct Fts3Phrase {
135927  /* Cache of doclist for this phrase. */
135928  Fts3Doclist doclist;
135929  int bIncr;                 /* True if doclist is loaded incrementally */
135930  int iDoclistToken;
135931
135932  /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
135933  ** OR condition.  */
135934  char *pOrPoslist;
135935  i64 iOrDocid;
135936
135937  /* Variables below this point are populated by fts3_expr.c when parsing
135938  ** a MATCH expression. Everything above is part of the evaluation phase.
135939  */
135940  int nToken;                /* Number of tokens in the phrase */
135941  int iColumn;               /* Index of column this phrase must match */
135942  Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
135943};
135944
135945/*
135946** A tree of these objects forms the RHS of a MATCH operator.
135947**
135948** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
135949** points to a malloced buffer, size nDoclist bytes, containing the results
135950** of this phrase query in FTS3 doclist format. As usual, the initial
135951** "Length" field found in doclists stored on disk is omitted from this
135952** buffer.
135953**
135954** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
135955** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
135956** where nCol is the number of columns in the queried FTS table. The array
135957** is populated as follows:
135958**
135959**   aMI[iCol*3 + 0] = Undefined
135960**   aMI[iCol*3 + 1] = Number of occurrences
135961**   aMI[iCol*3 + 2] = Number of rows containing at least one instance
135962**
135963** The aMI array is allocated using sqlite3_malloc(). It should be freed
135964** when the expression node is.
135965*/
135966struct Fts3Expr {
135967  int eType;                 /* One of the FTSQUERY_XXX values defined below */
135968  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
135969  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
135970  Fts3Expr *pLeft;           /* Left operand */
135971  Fts3Expr *pRight;          /* Right operand */
135972  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
135973
135974  /* The following are used by the fts3_eval.c module. */
135975  sqlite3_int64 iDocid;      /* Current docid */
135976  u8 bEof;                   /* True this expression is at EOF already */
135977  u8 bStart;                 /* True if iDocid is valid */
135978  u8 bDeferred;              /* True if this expression is entirely deferred */
135979
135980  /* The following are used by the fts3_snippet.c module. */
135981  int iPhrase;               /* Index of this phrase in matchinfo() results */
135982  u32 *aMI;                  /* See above */
135983};
135984
135985/*
135986** Candidate values for Fts3Query.eType. Note that the order of the first
135987** four values is in order of precedence when parsing expressions. For
135988** example, the following:
135989**
135990**   "a OR b AND c NOT d NEAR e"
135991**
135992** is equivalent to:
135993**
135994**   "a OR (b AND (c NOT (d NEAR e)))"
135995*/
135996#define FTSQUERY_NEAR   1
135997#define FTSQUERY_NOT    2
135998#define FTSQUERY_AND    3
135999#define FTSQUERY_OR     4
136000#define FTSQUERY_PHRASE 5
136001
136002
136003/* fts3_write.c */
136004SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
136005SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
136006SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
136007SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
136008SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
136009  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
136010SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
136011  Fts3Table*,int,const char*,int,int,Fts3SegReader**);
136012SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
136013SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
136014SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
136015
136016SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
136017SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
136018
136019#ifndef SQLITE_DISABLE_FTS4_DEFERRED
136020SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
136021SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
136022SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
136023SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
136024SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
136025#else
136026# define sqlite3Fts3FreeDeferredTokens(x)
136027# define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
136028# define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
136029# define sqlite3Fts3FreeDeferredDoclists(x)
136030# define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
136031#endif
136032
136033SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
136034SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
136035
136036/* Special values interpreted by sqlite3SegReaderCursor() */
136037#define FTS3_SEGCURSOR_PENDING        -1
136038#define FTS3_SEGCURSOR_ALL            -2
136039
136040SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
136041SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
136042SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
136043
136044SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
136045    int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
136046
136047/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
136048#define FTS3_SEGMENT_REQUIRE_POS   0x00000001
136049#define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
136050#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
136051#define FTS3_SEGMENT_PREFIX        0x00000008
136052#define FTS3_SEGMENT_SCAN          0x00000010
136053#define FTS3_SEGMENT_FIRST         0x00000020
136054
136055/* Type passed as 4th argument to SegmentReaderIterate() */
136056struct Fts3SegFilter {
136057  const char *zTerm;
136058  int nTerm;
136059  int iCol;
136060  int flags;
136061};
136062
136063struct Fts3MultiSegReader {
136064  /* Used internally by sqlite3Fts3SegReaderXXX() calls */
136065  Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
136066  int nSegment;                   /* Size of apSegment array */
136067  int nAdvance;                   /* How many seg-readers to advance */
136068  Fts3SegFilter *pFilter;         /* Pointer to filter object */
136069  char *aBuffer;                  /* Buffer to merge doclists in */
136070  int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
136071
136072  int iColFilter;                 /* If >=0, filter for this column */
136073  int bRestart;
136074
136075  /* Used by fts3.c only. */
136076  int nCost;                      /* Cost of running iterator */
136077  int bLookup;                    /* True if a lookup of a single entry. */
136078
136079  /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
136080  char *zTerm;                    /* Pointer to term buffer */
136081  int nTerm;                      /* Size of zTerm in bytes */
136082  char *aDoclist;                 /* Pointer to doclist buffer */
136083  int nDoclist;                   /* Size of aDoclist[] in bytes */
136084};
136085
136086SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
136087
136088#define fts3GetVarint32(p, piVal) (                                           \
136089  (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
136090)
136091
136092/* fts3.c */
136093SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
136094SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
136095SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
136096SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
136097SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
136098SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
136099SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
136100SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
136101SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
136102SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
136103SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
136104
136105/* fts3_tokenizer.c */
136106SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
136107SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
136108SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
136109    sqlite3_tokenizer **, char **
136110);
136111SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
136112
136113/* fts3_snippet.c */
136114SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
136115SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
136116  const char *, const char *, int, int
136117);
136118SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
136119SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
136120
136121/* fts3_expr.c */
136122SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
136123  char **, int, int, int, const char *, int, Fts3Expr **, char **
136124);
136125SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
136126#ifdef SQLITE_TEST
136127SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
136128SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
136129#endif
136130
136131SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
136132  sqlite3_tokenizer_cursor **
136133);
136134
136135/* fts3_aux.c */
136136SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
136137
136138SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
136139
136140SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
136141    Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
136142SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
136143    Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
136144SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
136145SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
136146SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
136147
136148/* fts3_tokenize_vtab.c */
136149SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
136150
136151/* fts3_unicode2.c (functions generated by parsing unicode text files) */
136152#ifndef SQLITE_DISABLE_FTS3_UNICODE
136153SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
136154SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
136155SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
136156#endif
136157
136158#endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
136159#endif /* _FTSINT_H */
136160
136161/************** End of fts3Int.h *********************************************/
136162/************** Continuing where we left off in fts3.c ***********************/
136163#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
136164
136165#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
136166# define SQLITE_CORE 1
136167#endif
136168
136169/* #include <assert.h> */
136170/* #include <stdlib.h> */
136171/* #include <stddef.h> */
136172/* #include <stdio.h> */
136173/* #include <string.h> */
136174/* #include <stdarg.h> */
136175
136176/* #include "fts3.h" */
136177#ifndef SQLITE_CORE
136178/* # include "sqlite3ext.h" */
136179  SQLITE_EXTENSION_INIT1
136180#endif
136181
136182static int fts3EvalNext(Fts3Cursor *pCsr);
136183static int fts3EvalStart(Fts3Cursor *pCsr);
136184static int fts3TermSegReaderCursor(
136185    Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
136186
136187#ifndef SQLITE_AMALGAMATION
136188# if defined(SQLITE_DEBUG)
136189SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
136190SQLITE_PRIVATE int sqlite3Fts3Never(int b)  { assert( !b ); return b; }
136191# endif
136192#endif
136193
136194/*
136195** Write a 64-bit variable-length integer to memory starting at p[0].
136196** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
136197** The number of bytes written is returned.
136198*/
136199SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
136200  unsigned char *q = (unsigned char *) p;
136201  sqlite_uint64 vu = v;
136202  do{
136203    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
136204    vu >>= 7;
136205  }while( vu!=0 );
136206  q[-1] &= 0x7f;  /* turn off high bit in final byte */
136207  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
136208  return (int) (q - (unsigned char *)p);
136209}
136210
136211#define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
136212  v = (v & mask1) | ( (*ptr++) << shift );                    \
136213  if( (v & mask2)==0 ){ var = v; return ret; }
136214#define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
136215  v = (*ptr++);                                               \
136216  if( (v & mask2)==0 ){ var = v; return ret; }
136217
136218/*
136219** Read a 64-bit variable-length integer from memory starting at p[0].
136220** Return the number of bytes read, or 0 on error.
136221** The value is stored in *v.
136222*/
136223SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
136224  const char *pStart = p;
136225  u32 a;
136226  u64 b;
136227  int shift;
136228
136229  GETVARINT_INIT(a, p, 0,  0x00,     0x80, *v, 1);
136230  GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *v, 2);
136231  GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *v, 3);
136232  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
136233  b = (a & 0x0FFFFFFF );
136234
136235  for(shift=28; shift<=63; shift+=7){
136236    u64 c = *p++;
136237    b += (c&0x7F) << shift;
136238    if( (c & 0x80)==0 ) break;
136239  }
136240  *v = b;
136241  return (int)(p - pStart);
136242}
136243
136244/*
136245** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
136246** 32-bit integer before it is returned.
136247*/
136248SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
136249  u32 a;
136250
136251#ifndef fts3GetVarint32
136252  GETVARINT_INIT(a, p, 0,  0x00,     0x80, *pi, 1);
136253#else
136254  a = (*p++);
136255  assert( a & 0x80 );
136256#endif
136257
136258  GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *pi, 2);
136259  GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *pi, 3);
136260  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
136261  a = (a & 0x0FFFFFFF );
136262  *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
136263  return 5;
136264}
136265
136266/*
136267** Return the number of bytes required to encode v as a varint
136268*/
136269SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
136270  int i = 0;
136271  do{
136272    i++;
136273    v >>= 7;
136274  }while( v!=0 );
136275  return i;
136276}
136277
136278/*
136279** Convert an SQL-style quoted string into a normal string by removing
136280** the quote characters.  The conversion is done in-place.  If the
136281** input does not begin with a quote character, then this routine
136282** is a no-op.
136283**
136284** Examples:
136285**
136286**     "abc"   becomes   abc
136287**     'xyz'   becomes   xyz
136288**     [pqr]   becomes   pqr
136289**     `mno`   becomes   mno
136290**
136291*/
136292SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
136293  char quote;                     /* Quote character (if any ) */
136294
136295  quote = z[0];
136296  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
136297    int iIn = 1;                  /* Index of next byte to read from input */
136298    int iOut = 0;                 /* Index of next byte to write to output */
136299
136300    /* If the first byte was a '[', then the close-quote character is a ']' */
136301    if( quote=='[' ) quote = ']';
136302
136303    while( z[iIn] ){
136304      if( z[iIn]==quote ){
136305        if( z[iIn+1]!=quote ) break;
136306        z[iOut++] = quote;
136307        iIn += 2;
136308      }else{
136309        z[iOut++] = z[iIn++];
136310      }
136311    }
136312    z[iOut] = '\0';
136313  }
136314}
136315
136316/*
136317** Read a single varint from the doclist at *pp and advance *pp to point
136318** to the first byte past the end of the varint.  Add the value of the varint
136319** to *pVal.
136320*/
136321static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
136322  sqlite3_int64 iVal;
136323  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
136324  *pVal += iVal;
136325}
136326
136327/*
136328** When this function is called, *pp points to the first byte following a
136329** varint that is part of a doclist (or position-list, or any other list
136330** of varints). This function moves *pp to point to the start of that varint,
136331** and sets *pVal by the varint value.
136332**
136333** Argument pStart points to the first byte of the doclist that the
136334** varint is part of.
136335*/
136336static void fts3GetReverseVarint(
136337  char **pp,
136338  char *pStart,
136339  sqlite3_int64 *pVal
136340){
136341  sqlite3_int64 iVal;
136342  char *p;
136343
136344  /* Pointer p now points at the first byte past the varint we are
136345  ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
136346  ** clear on character p[-1]. */
136347  for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
136348  p++;
136349  *pp = p;
136350
136351  sqlite3Fts3GetVarint(p, &iVal);
136352  *pVal = iVal;
136353}
136354
136355/*
136356** The xDisconnect() virtual table method.
136357*/
136358static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
136359  Fts3Table *p = (Fts3Table *)pVtab;
136360  int i;
136361
136362  assert( p->nPendingData==0 );
136363  assert( p->pSegments==0 );
136364
136365  /* Free any prepared statements held */
136366  for(i=0; i<SizeofArray(p->aStmt); i++){
136367    sqlite3_finalize(p->aStmt[i]);
136368  }
136369  sqlite3_free(p->zSegmentsTbl);
136370  sqlite3_free(p->zReadExprlist);
136371  sqlite3_free(p->zWriteExprlist);
136372  sqlite3_free(p->zContentTbl);
136373  sqlite3_free(p->zLanguageid);
136374
136375  /* Invoke the tokenizer destructor to free the tokenizer. */
136376  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
136377
136378  sqlite3_free(p);
136379  return SQLITE_OK;
136380}
136381
136382/*
136383** Write an error message into *pzErr
136384*/
136385SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
136386  va_list ap;
136387  sqlite3_free(*pzErr);
136388  va_start(ap, zFormat);
136389  *pzErr = sqlite3_vmprintf(zFormat, ap);
136390  va_end(ap);
136391}
136392
136393/*
136394** Construct one or more SQL statements from the format string given
136395** and then evaluate those statements. The success code is written
136396** into *pRc.
136397**
136398** If *pRc is initially non-zero then this routine is a no-op.
136399*/
136400static void fts3DbExec(
136401  int *pRc,              /* Success code */
136402  sqlite3 *db,           /* Database in which to run SQL */
136403  const char *zFormat,   /* Format string for SQL */
136404  ...                    /* Arguments to the format string */
136405){
136406  va_list ap;
136407  char *zSql;
136408  if( *pRc ) return;
136409  va_start(ap, zFormat);
136410  zSql = sqlite3_vmprintf(zFormat, ap);
136411  va_end(ap);
136412  if( zSql==0 ){
136413    *pRc = SQLITE_NOMEM;
136414  }else{
136415    *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
136416    sqlite3_free(zSql);
136417  }
136418}
136419
136420/*
136421** The xDestroy() virtual table method.
136422*/
136423static int fts3DestroyMethod(sqlite3_vtab *pVtab){
136424  Fts3Table *p = (Fts3Table *)pVtab;
136425  int rc = SQLITE_OK;              /* Return code */
136426  const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
136427  sqlite3 *db = p->db;             /* Database handle */
136428
136429  /* Drop the shadow tables */
136430  if( p->zContentTbl==0 ){
136431    fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
136432  }
136433  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
136434  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
136435  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
136436  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
136437
136438  /* If everything has worked, invoke fts3DisconnectMethod() to free the
136439  ** memory associated with the Fts3Table structure and return SQLITE_OK.
136440  ** Otherwise, return an SQLite error code.
136441  */
136442  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
136443}
136444
136445
136446/*
136447** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
136448** passed as the first argument. This is done as part of the xConnect()
136449** and xCreate() methods.
136450**
136451** If *pRc is non-zero when this function is called, it is a no-op.
136452** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
136453** before returning.
136454*/
136455static void fts3DeclareVtab(int *pRc, Fts3Table *p){
136456  if( *pRc==SQLITE_OK ){
136457    int i;                        /* Iterator variable */
136458    int rc;                       /* Return code */
136459    char *zSql;                   /* SQL statement passed to declare_vtab() */
136460    char *zCols;                  /* List of user defined columns */
136461    const char *zLanguageid;
136462
136463    zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
136464    sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
136465
136466    /* Create a list of user columns for the virtual table */
136467    zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
136468    for(i=1; zCols && i<p->nColumn; i++){
136469      zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
136470    }
136471
136472    /* Create the whole "CREATE TABLE" statement to pass to SQLite */
136473    zSql = sqlite3_mprintf(
136474        "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
136475        zCols, p->zName, zLanguageid
136476    );
136477    if( !zCols || !zSql ){
136478      rc = SQLITE_NOMEM;
136479    }else{
136480      rc = sqlite3_declare_vtab(p->db, zSql);
136481    }
136482
136483    sqlite3_free(zSql);
136484    sqlite3_free(zCols);
136485    *pRc = rc;
136486  }
136487}
136488
136489/*
136490** Create the %_stat table if it does not already exist.
136491*/
136492SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
136493  fts3DbExec(pRc, p->db,
136494      "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
136495          "(id INTEGER PRIMARY KEY, value BLOB);",
136496      p->zDb, p->zName
136497  );
136498  if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
136499}
136500
136501/*
136502** Create the backing store tables (%_content, %_segments and %_segdir)
136503** required by the FTS3 table passed as the only argument. This is done
136504** as part of the vtab xCreate() method.
136505**
136506** If the p->bHasDocsize boolean is true (indicating that this is an
136507** FTS4 table, not an FTS3 table) then also create the %_docsize and
136508** %_stat tables required by FTS4.
136509*/
136510static int fts3CreateTables(Fts3Table *p){
136511  int rc = SQLITE_OK;             /* Return code */
136512  int i;                          /* Iterator variable */
136513  sqlite3 *db = p->db;            /* The database connection */
136514
136515  if( p->zContentTbl==0 ){
136516    const char *zLanguageid = p->zLanguageid;
136517    char *zContentCols;           /* Columns of %_content table */
136518
136519    /* Create a list of user columns for the content table */
136520    zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
136521    for(i=0; zContentCols && i<p->nColumn; i++){
136522      char *z = p->azColumn[i];
136523      zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
136524    }
136525    if( zLanguageid && zContentCols ){
136526      zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
136527    }
136528    if( zContentCols==0 ) rc = SQLITE_NOMEM;
136529
136530    /* Create the content table */
136531    fts3DbExec(&rc, db,
136532       "CREATE TABLE %Q.'%q_content'(%s)",
136533       p->zDb, p->zName, zContentCols
136534    );
136535    sqlite3_free(zContentCols);
136536  }
136537
136538  /* Create other tables */
136539  fts3DbExec(&rc, db,
136540      "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
136541      p->zDb, p->zName
136542  );
136543  fts3DbExec(&rc, db,
136544      "CREATE TABLE %Q.'%q_segdir'("
136545        "level INTEGER,"
136546        "idx INTEGER,"
136547        "start_block INTEGER,"
136548        "leaves_end_block INTEGER,"
136549        "end_block INTEGER,"
136550        "root BLOB,"
136551        "PRIMARY KEY(level, idx)"
136552      ");",
136553      p->zDb, p->zName
136554  );
136555  if( p->bHasDocsize ){
136556    fts3DbExec(&rc, db,
136557        "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
136558        p->zDb, p->zName
136559    );
136560  }
136561  assert( p->bHasStat==p->bFts4 );
136562  if( p->bHasStat ){
136563    sqlite3Fts3CreateStatTable(&rc, p);
136564  }
136565  return rc;
136566}
136567
136568/*
136569** Store the current database page-size in bytes in p->nPgsz.
136570**
136571** If *pRc is non-zero when this function is called, it is a no-op.
136572** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
136573** before returning.
136574*/
136575static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
136576  if( *pRc==SQLITE_OK ){
136577    int rc;                       /* Return code */
136578    char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
136579    sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
136580
136581    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
136582    if( !zSql ){
136583      rc = SQLITE_NOMEM;
136584    }else{
136585      rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
136586      if( rc==SQLITE_OK ){
136587        sqlite3_step(pStmt);
136588        p->nPgsz = sqlite3_column_int(pStmt, 0);
136589        rc = sqlite3_finalize(pStmt);
136590      }else if( rc==SQLITE_AUTH ){
136591        p->nPgsz = 1024;
136592        rc = SQLITE_OK;
136593      }
136594    }
136595    assert( p->nPgsz>0 || rc!=SQLITE_OK );
136596    sqlite3_free(zSql);
136597    *pRc = rc;
136598  }
136599}
136600
136601/*
136602** "Special" FTS4 arguments are column specifications of the following form:
136603**
136604**   <key> = <value>
136605**
136606** There may not be whitespace surrounding the "=" character. The <value>
136607** term may be quoted, but the <key> may not.
136608*/
136609static int fts3IsSpecialColumn(
136610  const char *z,
136611  int *pnKey,
136612  char **pzValue
136613){
136614  char *zValue;
136615  const char *zCsr = z;
136616
136617  while( *zCsr!='=' ){
136618    if( *zCsr=='\0' ) return 0;
136619    zCsr++;
136620  }
136621
136622  *pnKey = (int)(zCsr-z);
136623  zValue = sqlite3_mprintf("%s", &zCsr[1]);
136624  if( zValue ){
136625    sqlite3Fts3Dequote(zValue);
136626  }
136627  *pzValue = zValue;
136628  return 1;
136629}
136630
136631/*
136632** Append the output of a printf() style formatting to an existing string.
136633*/
136634static void fts3Appendf(
136635  int *pRc,                       /* IN/OUT: Error code */
136636  char **pz,                      /* IN/OUT: Pointer to string buffer */
136637  const char *zFormat,            /* Printf format string to append */
136638  ...                             /* Arguments for printf format string */
136639){
136640  if( *pRc==SQLITE_OK ){
136641    va_list ap;
136642    char *z;
136643    va_start(ap, zFormat);
136644    z = sqlite3_vmprintf(zFormat, ap);
136645    va_end(ap);
136646    if( z && *pz ){
136647      char *z2 = sqlite3_mprintf("%s%s", *pz, z);
136648      sqlite3_free(z);
136649      z = z2;
136650    }
136651    if( z==0 ) *pRc = SQLITE_NOMEM;
136652    sqlite3_free(*pz);
136653    *pz = z;
136654  }
136655}
136656
136657/*
136658** Return a copy of input string zInput enclosed in double-quotes (") and
136659** with all double quote characters escaped. For example:
136660**
136661**     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
136662**
136663** The pointer returned points to memory obtained from sqlite3_malloc(). It
136664** is the callers responsibility to call sqlite3_free() to release this
136665** memory.
136666*/
136667static char *fts3QuoteId(char const *zInput){
136668  int nRet;
136669  char *zRet;
136670  nRet = 2 + (int)strlen(zInput)*2 + 1;
136671  zRet = sqlite3_malloc(nRet);
136672  if( zRet ){
136673    int i;
136674    char *z = zRet;
136675    *(z++) = '"';
136676    for(i=0; zInput[i]; i++){
136677      if( zInput[i]=='"' ) *(z++) = '"';
136678      *(z++) = zInput[i];
136679    }
136680    *(z++) = '"';
136681    *(z++) = '\0';
136682  }
136683  return zRet;
136684}
136685
136686/*
136687** Return a list of comma separated SQL expressions and a FROM clause that
136688** could be used in a SELECT statement such as the following:
136689**
136690**     SELECT <list of expressions> FROM %_content AS x ...
136691**
136692** to return the docid, followed by each column of text data in order
136693** from left to write. If parameter zFunc is not NULL, then instead of
136694** being returned directly each column of text data is passed to an SQL
136695** function named zFunc first. For example, if zFunc is "unzip" and the
136696** table has the three user-defined columns "a", "b", and "c", the following
136697** string is returned:
136698**
136699**     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
136700**
136701** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
136702** is the responsibility of the caller to eventually free it.
136703**
136704** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
136705** a NULL pointer is returned). Otherwise, if an OOM error is encountered
136706** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
136707** no error occurs, *pRc is left unmodified.
136708*/
136709static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
136710  char *zRet = 0;
136711  char *zFree = 0;
136712  char *zFunction;
136713  int i;
136714
136715  if( p->zContentTbl==0 ){
136716    if( !zFunc ){
136717      zFunction = "";
136718    }else{
136719      zFree = zFunction = fts3QuoteId(zFunc);
136720    }
136721    fts3Appendf(pRc, &zRet, "docid");
136722    for(i=0; i<p->nColumn; i++){
136723      fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
136724    }
136725    if( p->zLanguageid ){
136726      fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
136727    }
136728    sqlite3_free(zFree);
136729  }else{
136730    fts3Appendf(pRc, &zRet, "rowid");
136731    for(i=0; i<p->nColumn; i++){
136732      fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
136733    }
136734    if( p->zLanguageid ){
136735      fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
136736    }
136737  }
136738  fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
136739      p->zDb,
136740      (p->zContentTbl ? p->zContentTbl : p->zName),
136741      (p->zContentTbl ? "" : "_content")
136742  );
136743  return zRet;
136744}
136745
136746/*
136747** Return a list of N comma separated question marks, where N is the number
136748** of columns in the %_content table (one for the docid plus one for each
136749** user-defined text column).
136750**
136751** If argument zFunc is not NULL, then all but the first question mark
136752** is preceded by zFunc and an open bracket, and followed by a closed
136753** bracket. For example, if zFunc is "zip" and the FTS3 table has three
136754** user-defined text columns, the following string is returned:
136755**
136756**     "?, zip(?), zip(?), zip(?)"
136757**
136758** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
136759** is the responsibility of the caller to eventually free it.
136760**
136761** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
136762** a NULL pointer is returned). Otherwise, if an OOM error is encountered
136763** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
136764** no error occurs, *pRc is left unmodified.
136765*/
136766static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
136767  char *zRet = 0;
136768  char *zFree = 0;
136769  char *zFunction;
136770  int i;
136771
136772  if( !zFunc ){
136773    zFunction = "";
136774  }else{
136775    zFree = zFunction = fts3QuoteId(zFunc);
136776  }
136777  fts3Appendf(pRc, &zRet, "?");
136778  for(i=0; i<p->nColumn; i++){
136779    fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
136780  }
136781  if( p->zLanguageid ){
136782    fts3Appendf(pRc, &zRet, ", ?");
136783  }
136784  sqlite3_free(zFree);
136785  return zRet;
136786}
136787
136788/*
136789** This function interprets the string at (*pp) as a non-negative integer
136790** value. It reads the integer and sets *pnOut to the value read, then
136791** sets *pp to point to the byte immediately following the last byte of
136792** the integer value.
136793**
136794** Only decimal digits ('0'..'9') may be part of an integer value.
136795**
136796** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
136797** the output value undefined. Otherwise SQLITE_OK is returned.
136798**
136799** This function is used when parsing the "prefix=" FTS4 parameter.
136800*/
136801static int fts3GobbleInt(const char **pp, int *pnOut){
136802  const int MAX_NPREFIX = 10000000;
136803  const char *p;                  /* Iterator pointer */
136804  int nInt = 0;                   /* Output value */
136805
136806  for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
136807    nInt = nInt * 10 + (p[0] - '0');
136808    if( nInt>MAX_NPREFIX ){
136809      nInt = 0;
136810      break;
136811    }
136812  }
136813  if( p==*pp ) return SQLITE_ERROR;
136814  *pnOut = nInt;
136815  *pp = p;
136816  return SQLITE_OK;
136817}
136818
136819/*
136820** This function is called to allocate an array of Fts3Index structures
136821** representing the indexes maintained by the current FTS table. FTS tables
136822** always maintain the main "terms" index, but may also maintain one or
136823** more "prefix" indexes, depending on the value of the "prefix=" parameter
136824** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
136825**
136826** Argument zParam is passed the value of the "prefix=" option if one was
136827** specified, or NULL otherwise.
136828**
136829** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
136830** the allocated array. *pnIndex is set to the number of elements in the
136831** array. If an error does occur, an SQLite error code is returned.
136832**
136833** Regardless of whether or not an error is returned, it is the responsibility
136834** of the caller to call sqlite3_free() on the output array to free it.
136835*/
136836static int fts3PrefixParameter(
136837  const char *zParam,             /* ABC in prefix=ABC parameter to parse */
136838  int *pnIndex,                   /* OUT: size of *apIndex[] array */
136839  struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
136840){
136841  struct Fts3Index *aIndex;       /* Allocated array */
136842  int nIndex = 1;                 /* Number of entries in array */
136843
136844  if( zParam && zParam[0] ){
136845    const char *p;
136846    nIndex++;
136847    for(p=zParam; *p; p++){
136848      if( *p==',' ) nIndex++;
136849    }
136850  }
136851
136852  aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
136853  *apIndex = aIndex;
136854  if( !aIndex ){
136855    return SQLITE_NOMEM;
136856  }
136857
136858  memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
136859  if( zParam ){
136860    const char *p = zParam;
136861    int i;
136862    for(i=1; i<nIndex; i++){
136863      int nPrefix = 0;
136864      if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
136865      assert( nPrefix>=0 );
136866      if( nPrefix==0 ){
136867        nIndex--;
136868        i--;
136869      }else{
136870        aIndex[i].nPrefix = nPrefix;
136871      }
136872      p++;
136873    }
136874  }
136875
136876  *pnIndex = nIndex;
136877  return SQLITE_OK;
136878}
136879
136880/*
136881** This function is called when initializing an FTS4 table that uses the
136882** content=xxx option. It determines the number of and names of the columns
136883** of the new FTS4 table.
136884**
136885** The third argument passed to this function is the value passed to the
136886** config=xxx option (i.e. "xxx"). This function queries the database for
136887** a table of that name. If found, the output variables are populated
136888** as follows:
136889**
136890**   *pnCol:   Set to the number of columns table xxx has,
136891**
136892**   *pnStr:   Set to the total amount of space required to store a copy
136893**             of each columns name, including the nul-terminator.
136894**
136895**   *pazCol:  Set to point to an array of *pnCol strings. Each string is
136896**             the name of the corresponding column in table xxx. The array
136897**             and its contents are allocated using a single allocation. It
136898**             is the responsibility of the caller to free this allocation
136899**             by eventually passing the *pazCol value to sqlite3_free().
136900**
136901** If the table cannot be found, an error code is returned and the output
136902** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
136903** returned (and the output variables are undefined).
136904*/
136905static int fts3ContentColumns(
136906  sqlite3 *db,                    /* Database handle */
136907  const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
136908  const char *zTbl,               /* Name of content table */
136909  const char ***pazCol,           /* OUT: Malloc'd array of column names */
136910  int *pnCol,                     /* OUT: Size of array *pazCol */
136911  int *pnStr,                     /* OUT: Bytes of string content */
136912  char **pzErr                    /* OUT: error message */
136913){
136914  int rc = SQLITE_OK;             /* Return code */
136915  char *zSql;                     /* "SELECT *" statement on zTbl */
136916  sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
136917
136918  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
136919  if( !zSql ){
136920    rc = SQLITE_NOMEM;
136921  }else{
136922    rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
136923    if( rc!=SQLITE_OK ){
136924      sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
136925    }
136926  }
136927  sqlite3_free(zSql);
136928
136929  if( rc==SQLITE_OK ){
136930    const char **azCol;           /* Output array */
136931    int nStr = 0;                 /* Size of all column names (incl. 0x00) */
136932    int nCol;                     /* Number of table columns */
136933    int i;                        /* Used to iterate through columns */
136934
136935    /* Loop through the returned columns. Set nStr to the number of bytes of
136936    ** space required to store a copy of each column name, including the
136937    ** nul-terminator byte.  */
136938    nCol = sqlite3_column_count(pStmt);
136939    for(i=0; i<nCol; i++){
136940      const char *zCol = sqlite3_column_name(pStmt, i);
136941      nStr += (int)strlen(zCol) + 1;
136942    }
136943
136944    /* Allocate and populate the array to return. */
136945    azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
136946    if( azCol==0 ){
136947      rc = SQLITE_NOMEM;
136948    }else{
136949      char *p = (char *)&azCol[nCol];
136950      for(i=0; i<nCol; i++){
136951        const char *zCol = sqlite3_column_name(pStmt, i);
136952        int n = (int)strlen(zCol)+1;
136953        memcpy(p, zCol, n);
136954        azCol[i] = p;
136955        p += n;
136956      }
136957    }
136958    sqlite3_finalize(pStmt);
136959
136960    /* Set the output variables. */
136961    *pnCol = nCol;
136962    *pnStr = nStr;
136963    *pazCol = azCol;
136964  }
136965
136966  return rc;
136967}
136968
136969/*
136970** This function is the implementation of both the xConnect and xCreate
136971** methods of the FTS3 virtual table.
136972**
136973** The argv[] array contains the following:
136974**
136975**   argv[0]   -> module name  ("fts3" or "fts4")
136976**   argv[1]   -> database name
136977**   argv[2]   -> table name
136978**   argv[...] -> "column name" and other module argument fields.
136979*/
136980static int fts3InitVtab(
136981  int isCreate,                   /* True for xCreate, false for xConnect */
136982  sqlite3 *db,                    /* The SQLite database connection */
136983  void *pAux,                     /* Hash table containing tokenizers */
136984  int argc,                       /* Number of elements in argv array */
136985  const char * const *argv,       /* xCreate/xConnect argument array */
136986  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
136987  char **pzErr                    /* Write any error message here */
136988){
136989  Fts3Hash *pHash = (Fts3Hash *)pAux;
136990  Fts3Table *p = 0;               /* Pointer to allocated vtab */
136991  int rc = SQLITE_OK;             /* Return code */
136992  int i;                          /* Iterator variable */
136993  int nByte;                      /* Size of allocation used for *p */
136994  int iCol;                       /* Column index */
136995  int nString = 0;                /* Bytes required to hold all column names */
136996  int nCol = 0;                   /* Number of columns in the FTS table */
136997  char *zCsr;                     /* Space for holding column names */
136998  int nDb;                        /* Bytes required to hold database name */
136999  int nName;                      /* Bytes required to hold table name */
137000  int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
137001  const char **aCol;              /* Array of column names */
137002  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
137003
137004  int nIndex = 0;                 /* Size of aIndex[] array */
137005  struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
137006
137007  /* The results of parsing supported FTS4 key=value options: */
137008  int bNoDocsize = 0;             /* True to omit %_docsize table */
137009  int bDescIdx = 0;               /* True to store descending indexes */
137010  char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
137011  char *zCompress = 0;            /* compress=? parameter (or NULL) */
137012  char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
137013  char *zContent = 0;             /* content=? parameter (or NULL) */
137014  char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
137015  char **azNotindexed = 0;        /* The set of notindexed= columns */
137016  int nNotindexed = 0;            /* Size of azNotindexed[] array */
137017
137018  assert( strlen(argv[0])==4 );
137019  assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
137020       || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
137021  );
137022
137023  nDb = (int)strlen(argv[1]) + 1;
137024  nName = (int)strlen(argv[2]) + 1;
137025
137026  nByte = sizeof(const char *) * (argc-2);
137027  aCol = (const char **)sqlite3_malloc(nByte);
137028  if( aCol ){
137029    memset((void*)aCol, 0, nByte);
137030    azNotindexed = (char **)sqlite3_malloc(nByte);
137031  }
137032  if( azNotindexed ){
137033    memset(azNotindexed, 0, nByte);
137034  }
137035  if( !aCol || !azNotindexed ){
137036    rc = SQLITE_NOMEM;
137037    goto fts3_init_out;
137038  }
137039
137040  /* Loop through all of the arguments passed by the user to the FTS3/4
137041  ** module (i.e. all the column names and special arguments). This loop
137042  ** does the following:
137043  **
137044  **   + Figures out the number of columns the FTSX table will have, and
137045  **     the number of bytes of space that must be allocated to store copies
137046  **     of the column names.
137047  **
137048  **   + If there is a tokenizer specification included in the arguments,
137049  **     initializes the tokenizer pTokenizer.
137050  */
137051  for(i=3; rc==SQLITE_OK && i<argc; i++){
137052    char const *z = argv[i];
137053    int nKey;
137054    char *zVal;
137055
137056    /* Check if this is a tokenizer specification */
137057    if( !pTokenizer
137058     && strlen(z)>8
137059     && 0==sqlite3_strnicmp(z, "tokenize", 8)
137060     && 0==sqlite3Fts3IsIdChar(z[8])
137061    ){
137062      rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
137063    }
137064
137065    /* Check if it is an FTS4 special argument. */
137066    else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
137067      struct Fts4Option {
137068        const char *zOpt;
137069        int nOpt;
137070      } aFts4Opt[] = {
137071        { "matchinfo",   9 },     /* 0 -> MATCHINFO */
137072        { "prefix",      6 },     /* 1 -> PREFIX */
137073        { "compress",    8 },     /* 2 -> COMPRESS */
137074        { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
137075        { "order",       5 },     /* 4 -> ORDER */
137076        { "content",     7 },     /* 5 -> CONTENT */
137077        { "languageid", 10 },     /* 6 -> LANGUAGEID */
137078        { "notindexed", 10 }      /* 7 -> NOTINDEXED */
137079      };
137080
137081      int iOpt;
137082      if( !zVal ){
137083        rc = SQLITE_NOMEM;
137084      }else{
137085        for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
137086          struct Fts4Option *pOp = &aFts4Opt[iOpt];
137087          if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
137088            break;
137089          }
137090        }
137091        if( iOpt==SizeofArray(aFts4Opt) ){
137092          sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
137093          rc = SQLITE_ERROR;
137094        }else{
137095          switch( iOpt ){
137096            case 0:               /* MATCHINFO */
137097              if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
137098                sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
137099                rc = SQLITE_ERROR;
137100              }
137101              bNoDocsize = 1;
137102              break;
137103
137104            case 1:               /* PREFIX */
137105              sqlite3_free(zPrefix);
137106              zPrefix = zVal;
137107              zVal = 0;
137108              break;
137109
137110            case 2:               /* COMPRESS */
137111              sqlite3_free(zCompress);
137112              zCompress = zVal;
137113              zVal = 0;
137114              break;
137115
137116            case 3:               /* UNCOMPRESS */
137117              sqlite3_free(zUncompress);
137118              zUncompress = zVal;
137119              zVal = 0;
137120              break;
137121
137122            case 4:               /* ORDER */
137123              if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
137124               && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
137125              ){
137126                sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
137127                rc = SQLITE_ERROR;
137128              }
137129              bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
137130              break;
137131
137132            case 5:              /* CONTENT */
137133              sqlite3_free(zContent);
137134              zContent = zVal;
137135              zVal = 0;
137136              break;
137137
137138            case 6:              /* LANGUAGEID */
137139              assert( iOpt==6 );
137140              sqlite3_free(zLanguageid);
137141              zLanguageid = zVal;
137142              zVal = 0;
137143              break;
137144
137145            case 7:              /* NOTINDEXED */
137146              azNotindexed[nNotindexed++] = zVal;
137147              zVal = 0;
137148              break;
137149          }
137150        }
137151        sqlite3_free(zVal);
137152      }
137153    }
137154
137155    /* Otherwise, the argument is a column name. */
137156    else {
137157      nString += (int)(strlen(z) + 1);
137158      aCol[nCol++] = z;
137159    }
137160  }
137161
137162  /* If a content=xxx option was specified, the following:
137163  **
137164  **   1. Ignore any compress= and uncompress= options.
137165  **
137166  **   2. If no column names were specified as part of the CREATE VIRTUAL
137167  **      TABLE statement, use all columns from the content table.
137168  */
137169  if( rc==SQLITE_OK && zContent ){
137170    sqlite3_free(zCompress);
137171    sqlite3_free(zUncompress);
137172    zCompress = 0;
137173    zUncompress = 0;
137174    if( nCol==0 ){
137175      sqlite3_free((void*)aCol);
137176      aCol = 0;
137177      rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
137178
137179      /* If a languageid= option was specified, remove the language id
137180      ** column from the aCol[] array. */
137181      if( rc==SQLITE_OK && zLanguageid ){
137182        int j;
137183        for(j=0; j<nCol; j++){
137184          if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
137185            int k;
137186            for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
137187            nCol--;
137188            break;
137189          }
137190        }
137191      }
137192    }
137193  }
137194  if( rc!=SQLITE_OK ) goto fts3_init_out;
137195
137196  if( nCol==0 ){
137197    assert( nString==0 );
137198    aCol[0] = "content";
137199    nString = 8;
137200    nCol = 1;
137201  }
137202
137203  if( pTokenizer==0 ){
137204    rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
137205    if( rc!=SQLITE_OK ) goto fts3_init_out;
137206  }
137207  assert( pTokenizer );
137208
137209  rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
137210  if( rc==SQLITE_ERROR ){
137211    assert( zPrefix );
137212    sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
137213  }
137214  if( rc!=SQLITE_OK ) goto fts3_init_out;
137215
137216  /* Allocate and populate the Fts3Table structure. */
137217  nByte = sizeof(Fts3Table) +                  /* Fts3Table */
137218          nCol * sizeof(char *) +              /* azColumn */
137219          nIndex * sizeof(struct Fts3Index) +  /* aIndex */
137220          nCol * sizeof(u8) +                  /* abNotindexed */
137221          nName +                              /* zName */
137222          nDb +                                /* zDb */
137223          nString;                             /* Space for azColumn strings */
137224  p = (Fts3Table*)sqlite3_malloc(nByte);
137225  if( p==0 ){
137226    rc = SQLITE_NOMEM;
137227    goto fts3_init_out;
137228  }
137229  memset(p, 0, nByte);
137230  p->db = db;
137231  p->nColumn = nCol;
137232  p->nPendingData = 0;
137233  p->azColumn = (char **)&p[1];
137234  p->pTokenizer = pTokenizer;
137235  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
137236  p->bHasDocsize = (isFts4 && bNoDocsize==0);
137237  p->bHasStat = isFts4;
137238  p->bFts4 = isFts4;
137239  p->bDescIdx = bDescIdx;
137240  p->nAutoincrmerge = 0xff;   /* 0xff means setting unknown */
137241  p->zContentTbl = zContent;
137242  p->zLanguageid = zLanguageid;
137243  zContent = 0;
137244  zLanguageid = 0;
137245  TESTONLY( p->inTransaction = -1 );
137246  TESTONLY( p->mxSavepoint = -1 );
137247
137248  p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
137249  memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
137250  p->nIndex = nIndex;
137251  for(i=0; i<nIndex; i++){
137252    fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
137253  }
137254  p->abNotindexed = (u8 *)&p->aIndex[nIndex];
137255
137256  /* Fill in the zName and zDb fields of the vtab structure. */
137257  zCsr = (char *)&p->abNotindexed[nCol];
137258  p->zName = zCsr;
137259  memcpy(zCsr, argv[2], nName);
137260  zCsr += nName;
137261  p->zDb = zCsr;
137262  memcpy(zCsr, argv[1], nDb);
137263  zCsr += nDb;
137264
137265  /* Fill in the azColumn array */
137266  for(iCol=0; iCol<nCol; iCol++){
137267    char *z;
137268    int n = 0;
137269    z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
137270    memcpy(zCsr, z, n);
137271    zCsr[n] = '\0';
137272    sqlite3Fts3Dequote(zCsr);
137273    p->azColumn[iCol] = zCsr;
137274    zCsr += n+1;
137275    assert( zCsr <= &((char *)p)[nByte] );
137276  }
137277
137278  /* Fill in the abNotindexed array */
137279  for(iCol=0; iCol<nCol; iCol++){
137280    int n = (int)strlen(p->azColumn[iCol]);
137281    for(i=0; i<nNotindexed; i++){
137282      char *zNot = azNotindexed[i];
137283      if( zNot && n==(int)strlen(zNot)
137284       && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
137285      ){
137286        p->abNotindexed[iCol] = 1;
137287        sqlite3_free(zNot);
137288        azNotindexed[i] = 0;
137289      }
137290    }
137291  }
137292  for(i=0; i<nNotindexed; i++){
137293    if( azNotindexed[i] ){
137294      sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
137295      rc = SQLITE_ERROR;
137296    }
137297  }
137298
137299  if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
137300    char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
137301    rc = SQLITE_ERROR;
137302    sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
137303  }
137304  p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
137305  p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
137306  if( rc!=SQLITE_OK ) goto fts3_init_out;
137307
137308  /* If this is an xCreate call, create the underlying tables in the
137309  ** database. TODO: For xConnect(), it could verify that said tables exist.
137310  */
137311  if( isCreate ){
137312    rc = fts3CreateTables(p);
137313  }
137314
137315  /* Check to see if a legacy fts3 table has been "upgraded" by the
137316  ** addition of a %_stat table so that it can use incremental merge.
137317  */
137318  if( !isFts4 && !isCreate ){
137319    p->bHasStat = 2;
137320  }
137321
137322  /* Figure out the page-size for the database. This is required in order to
137323  ** estimate the cost of loading large doclists from the database.  */
137324  fts3DatabasePageSize(&rc, p);
137325  p->nNodeSize = p->nPgsz-35;
137326
137327  /* Declare the table schema to SQLite. */
137328  fts3DeclareVtab(&rc, p);
137329
137330fts3_init_out:
137331  sqlite3_free(zPrefix);
137332  sqlite3_free(aIndex);
137333  sqlite3_free(zCompress);
137334  sqlite3_free(zUncompress);
137335  sqlite3_free(zContent);
137336  sqlite3_free(zLanguageid);
137337  for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
137338  sqlite3_free((void *)aCol);
137339  sqlite3_free((void *)azNotindexed);
137340  if( rc!=SQLITE_OK ){
137341    if( p ){
137342      fts3DisconnectMethod((sqlite3_vtab *)p);
137343    }else if( pTokenizer ){
137344      pTokenizer->pModule->xDestroy(pTokenizer);
137345    }
137346  }else{
137347    assert( p->pSegments==0 );
137348    *ppVTab = &p->base;
137349  }
137350  return rc;
137351}
137352
137353/*
137354** The xConnect() and xCreate() methods for the virtual table. All the
137355** work is done in function fts3InitVtab().
137356*/
137357static int fts3ConnectMethod(
137358  sqlite3 *db,                    /* Database connection */
137359  void *pAux,                     /* Pointer to tokenizer hash table */
137360  int argc,                       /* Number of elements in argv array */
137361  const char * const *argv,       /* xCreate/xConnect argument array */
137362  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
137363  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
137364){
137365  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
137366}
137367static int fts3CreateMethod(
137368  sqlite3 *db,                    /* Database connection */
137369  void *pAux,                     /* Pointer to tokenizer hash table */
137370  int argc,                       /* Number of elements in argv array */
137371  const char * const *argv,       /* xCreate/xConnect argument array */
137372  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
137373  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
137374){
137375  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
137376}
137377
137378/*
137379** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
137380** extension is currently being used by a version of SQLite too old to
137381** support estimatedRows. In that case this function is a no-op.
137382*/
137383static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
137384#if SQLITE_VERSION_NUMBER>=3008002
137385  if( sqlite3_libversion_number()>=3008002 ){
137386    pIdxInfo->estimatedRows = nRow;
137387  }
137388#endif
137389}
137390
137391/*
137392** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
137393** extension is currently being used by a version of SQLite too old to
137394** support index-info flags. In that case this function is a no-op.
137395*/
137396static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
137397#if SQLITE_VERSION_NUMBER>=3008012
137398  if( sqlite3_libversion_number()>=3008012 ){
137399    pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
137400  }
137401#endif
137402}
137403
137404/*
137405** Implementation of the xBestIndex method for FTS3 tables. There
137406** are three possible strategies, in order of preference:
137407**
137408**   1. Direct lookup by rowid or docid.
137409**   2. Full-text search using a MATCH operator on a non-docid column.
137410**   3. Linear scan of %_content table.
137411*/
137412static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
137413  Fts3Table *p = (Fts3Table *)pVTab;
137414  int i;                          /* Iterator variable */
137415  int iCons = -1;                 /* Index of constraint to use */
137416
137417  int iLangidCons = -1;           /* Index of langid=x constraint, if present */
137418  int iDocidGe = -1;              /* Index of docid>=x constraint, if present */
137419  int iDocidLe = -1;              /* Index of docid<=x constraint, if present */
137420  int iIdx;
137421
137422  /* By default use a full table scan. This is an expensive option,
137423  ** so search through the constraints to see if a more efficient
137424  ** strategy is possible.
137425  */
137426  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
137427  pInfo->estimatedCost = 5000000;
137428  for(i=0; i<pInfo->nConstraint; i++){
137429    int bDocid;                 /* True if this constraint is on docid */
137430    struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
137431    if( pCons->usable==0 ){
137432      if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
137433        /* There exists an unusable MATCH constraint. This means that if
137434        ** the planner does elect to use the results of this call as part
137435        ** of the overall query plan the user will see an "unable to use
137436        ** function MATCH in the requested context" error. To discourage
137437        ** this, return a very high cost here.  */
137438        pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
137439        pInfo->estimatedCost = 1e50;
137440        fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
137441        return SQLITE_OK;
137442      }
137443      continue;
137444    }
137445
137446    bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
137447
137448    /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
137449    if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
137450      pInfo->idxNum = FTS3_DOCID_SEARCH;
137451      pInfo->estimatedCost = 1.0;
137452      iCons = i;
137453    }
137454
137455    /* A MATCH constraint. Use a full-text search.
137456    **
137457    ** If there is more than one MATCH constraint available, use the first
137458    ** one encountered. If there is both a MATCH constraint and a direct
137459    ** rowid/docid lookup, prefer the MATCH strategy. This is done even
137460    ** though the rowid/docid lookup is faster than a MATCH query, selecting
137461    ** it would lead to an "unable to use function MATCH in the requested
137462    ** context" error.
137463    */
137464    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
137465     && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
137466    ){
137467      pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
137468      pInfo->estimatedCost = 2.0;
137469      iCons = i;
137470    }
137471
137472    /* Equality constraint on the langid column */
137473    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
137474     && pCons->iColumn==p->nColumn + 2
137475    ){
137476      iLangidCons = i;
137477    }
137478
137479    if( bDocid ){
137480      switch( pCons->op ){
137481        case SQLITE_INDEX_CONSTRAINT_GE:
137482        case SQLITE_INDEX_CONSTRAINT_GT:
137483          iDocidGe = i;
137484          break;
137485
137486        case SQLITE_INDEX_CONSTRAINT_LE:
137487        case SQLITE_INDEX_CONSTRAINT_LT:
137488          iDocidLe = i;
137489          break;
137490      }
137491    }
137492  }
137493
137494  /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
137495  if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
137496
137497  iIdx = 1;
137498  if( iCons>=0 ){
137499    pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
137500    pInfo->aConstraintUsage[iCons].omit = 1;
137501  }
137502  if( iLangidCons>=0 ){
137503    pInfo->idxNum |= FTS3_HAVE_LANGID;
137504    pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
137505  }
137506  if( iDocidGe>=0 ){
137507    pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
137508    pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
137509  }
137510  if( iDocidLe>=0 ){
137511    pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
137512    pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
137513  }
137514
137515  /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
137516  ** docid) order. Both ascending and descending are possible.
137517  */
137518  if( pInfo->nOrderBy==1 ){
137519    struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
137520    if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
137521      if( pOrder->desc ){
137522        pInfo->idxStr = "DESC";
137523      }else{
137524        pInfo->idxStr = "ASC";
137525      }
137526      pInfo->orderByConsumed = 1;
137527    }
137528  }
137529
137530  assert( p->pSegments==0 );
137531  return SQLITE_OK;
137532}
137533
137534/*
137535** Implementation of xOpen method.
137536*/
137537static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
137538  sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
137539
137540  UNUSED_PARAMETER(pVTab);
137541
137542  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
137543  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
137544  ** if the allocation fails, return SQLITE_NOMEM.
137545  */
137546  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
137547  if( !pCsr ){
137548    return SQLITE_NOMEM;
137549  }
137550  memset(pCsr, 0, sizeof(Fts3Cursor));
137551  return SQLITE_OK;
137552}
137553
137554/*
137555** Close the cursor.  For additional information see the documentation
137556** on the xClose method of the virtual table interface.
137557*/
137558static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
137559  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
137560  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
137561  sqlite3_finalize(pCsr->pStmt);
137562  sqlite3Fts3ExprFree(pCsr->pExpr);
137563  sqlite3Fts3FreeDeferredTokens(pCsr);
137564  sqlite3_free(pCsr->aDoclist);
137565  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
137566  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
137567  sqlite3_free(pCsr);
137568  return SQLITE_OK;
137569}
137570
137571/*
137572** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
137573** compose and prepare an SQL statement of the form:
137574**
137575**    "SELECT <columns> FROM %_content WHERE rowid = ?"
137576**
137577** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
137578** it. If an error occurs, return an SQLite error code.
137579**
137580** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
137581*/
137582static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
137583  int rc = SQLITE_OK;
137584  if( pCsr->pStmt==0 ){
137585    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
137586    char *zSql;
137587    zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
137588    if( !zSql ) return SQLITE_NOMEM;
137589    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
137590    sqlite3_free(zSql);
137591  }
137592  *ppStmt = pCsr->pStmt;
137593  return rc;
137594}
137595
137596/*
137597** Position the pCsr->pStmt statement so that it is on the row
137598** of the %_content table that contains the last match.  Return
137599** SQLITE_OK on success.
137600*/
137601static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
137602  int rc = SQLITE_OK;
137603  if( pCsr->isRequireSeek ){
137604    sqlite3_stmt *pStmt = 0;
137605
137606    rc = fts3CursorSeekStmt(pCsr, &pStmt);
137607    if( rc==SQLITE_OK ){
137608      sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
137609      pCsr->isRequireSeek = 0;
137610      if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
137611        return SQLITE_OK;
137612      }else{
137613        rc = sqlite3_reset(pCsr->pStmt);
137614        if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
137615          /* If no row was found and no error has occurred, then the %_content
137616          ** table is missing a row that is present in the full-text index.
137617          ** The data structures are corrupt.  */
137618          rc = FTS_CORRUPT_VTAB;
137619          pCsr->isEof = 1;
137620        }
137621      }
137622    }
137623  }
137624
137625  if( rc!=SQLITE_OK && pContext ){
137626    sqlite3_result_error_code(pContext, rc);
137627  }
137628  return rc;
137629}
137630
137631/*
137632** This function is used to process a single interior node when searching
137633** a b-tree for a term or term prefix. The node data is passed to this
137634** function via the zNode/nNode parameters. The term to search for is
137635** passed in zTerm/nTerm.
137636**
137637** If piFirst is not NULL, then this function sets *piFirst to the blockid
137638** of the child node that heads the sub-tree that may contain the term.
137639**
137640** If piLast is not NULL, then *piLast is set to the right-most child node
137641** that heads a sub-tree that may contain a term for which zTerm/nTerm is
137642** a prefix.
137643**
137644** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
137645*/
137646static int fts3ScanInteriorNode(
137647  const char *zTerm,              /* Term to select leaves for */
137648  int nTerm,                      /* Size of term zTerm in bytes */
137649  const char *zNode,              /* Buffer containing segment interior node */
137650  int nNode,                      /* Size of buffer at zNode */
137651  sqlite3_int64 *piFirst,         /* OUT: Selected child node */
137652  sqlite3_int64 *piLast           /* OUT: Selected child node */
137653){
137654  int rc = SQLITE_OK;             /* Return code */
137655  const char *zCsr = zNode;       /* Cursor to iterate through node */
137656  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
137657  char *zBuffer = 0;              /* Buffer to load terms into */
137658  int nAlloc = 0;                 /* Size of allocated buffer */
137659  int isFirstTerm = 1;            /* True when processing first term on page */
137660  sqlite3_int64 iChild;           /* Block id of child node to descend to */
137661
137662  /* Skip over the 'height' varint that occurs at the start of every
137663  ** interior node. Then load the blockid of the left-child of the b-tree
137664  ** node into variable iChild.
137665  **
137666  ** Even if the data structure on disk is corrupted, this (reading two
137667  ** varints from the buffer) does not risk an overread. If zNode is a
137668  ** root node, then the buffer comes from a SELECT statement. SQLite does
137669  ** not make this guarantee explicitly, but in practice there are always
137670  ** either more than 20 bytes of allocated space following the nNode bytes of
137671  ** contents, or two zero bytes. Or, if the node is read from the %_segments
137672  ** table, then there are always 20 bytes of zeroed padding following the
137673  ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
137674  */
137675  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
137676  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
137677  if( zCsr>zEnd ){
137678    return FTS_CORRUPT_VTAB;
137679  }
137680
137681  while( zCsr<zEnd && (piFirst || piLast) ){
137682    int cmp;                      /* memcmp() result */
137683    int nSuffix;                  /* Size of term suffix */
137684    int nPrefix = 0;              /* Size of term prefix */
137685    int nBuffer;                  /* Total term size */
137686
137687    /* Load the next term on the node into zBuffer. Use realloc() to expand
137688    ** the size of zBuffer if required.  */
137689    if( !isFirstTerm ){
137690      zCsr += fts3GetVarint32(zCsr, &nPrefix);
137691    }
137692    isFirstTerm = 0;
137693    zCsr += fts3GetVarint32(zCsr, &nSuffix);
137694
137695    if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
137696      rc = FTS_CORRUPT_VTAB;
137697      goto finish_scan;
137698    }
137699    if( nPrefix+nSuffix>nAlloc ){
137700      char *zNew;
137701      nAlloc = (nPrefix+nSuffix) * 2;
137702      zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
137703      if( !zNew ){
137704        rc = SQLITE_NOMEM;
137705        goto finish_scan;
137706      }
137707      zBuffer = zNew;
137708    }
137709    assert( zBuffer );
137710    memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
137711    nBuffer = nPrefix + nSuffix;
137712    zCsr += nSuffix;
137713
137714    /* Compare the term we are searching for with the term just loaded from
137715    ** the interior node. If the specified term is greater than or equal
137716    ** to the term from the interior node, then all terms on the sub-tree
137717    ** headed by node iChild are smaller than zTerm. No need to search
137718    ** iChild.
137719    **
137720    ** If the interior node term is larger than the specified term, then
137721    ** the tree headed by iChild may contain the specified term.
137722    */
137723    cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
137724    if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
137725      *piFirst = iChild;
137726      piFirst = 0;
137727    }
137728
137729    if( piLast && cmp<0 ){
137730      *piLast = iChild;
137731      piLast = 0;
137732    }
137733
137734    iChild++;
137735  };
137736
137737  if( piFirst ) *piFirst = iChild;
137738  if( piLast ) *piLast = iChild;
137739
137740 finish_scan:
137741  sqlite3_free(zBuffer);
137742  return rc;
137743}
137744
137745
137746/*
137747** The buffer pointed to by argument zNode (size nNode bytes) contains an
137748** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
137749** contains a term. This function searches the sub-tree headed by the zNode
137750** node for the range of leaf nodes that may contain the specified term
137751** or terms for which the specified term is a prefix.
137752**
137753** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
137754** left-most leaf node in the tree that may contain the specified term.
137755** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
137756** right-most leaf node that may contain a term for which the specified
137757** term is a prefix.
137758**
137759** It is possible that the range of returned leaf nodes does not contain
137760** the specified term or any terms for which it is a prefix. However, if the
137761** segment does contain any such terms, they are stored within the identified
137762** range. Because this function only inspects interior segment nodes (and
137763** never loads leaf nodes into memory), it is not possible to be sure.
137764**
137765** If an error occurs, an error code other than SQLITE_OK is returned.
137766*/
137767static int fts3SelectLeaf(
137768  Fts3Table *p,                   /* Virtual table handle */
137769  const char *zTerm,              /* Term to select leaves for */
137770  int nTerm,                      /* Size of term zTerm in bytes */
137771  const char *zNode,              /* Buffer containing segment interior node */
137772  int nNode,                      /* Size of buffer at zNode */
137773  sqlite3_int64 *piLeaf,          /* Selected leaf node */
137774  sqlite3_int64 *piLeaf2          /* Selected leaf node */
137775){
137776  int rc = SQLITE_OK;             /* Return code */
137777  int iHeight;                    /* Height of this node in tree */
137778
137779  assert( piLeaf || piLeaf2 );
137780
137781  fts3GetVarint32(zNode, &iHeight);
137782  rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
137783  assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
137784
137785  if( rc==SQLITE_OK && iHeight>1 ){
137786    char *zBlob = 0;              /* Blob read from %_segments table */
137787    int nBlob = 0;                /* Size of zBlob in bytes */
137788
137789    if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
137790      rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
137791      if( rc==SQLITE_OK ){
137792        rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
137793      }
137794      sqlite3_free(zBlob);
137795      piLeaf = 0;
137796      zBlob = 0;
137797    }
137798
137799    if( rc==SQLITE_OK ){
137800      rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
137801    }
137802    if( rc==SQLITE_OK ){
137803      rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
137804    }
137805    sqlite3_free(zBlob);
137806  }
137807
137808  return rc;
137809}
137810
137811/*
137812** This function is used to create delta-encoded serialized lists of FTS3
137813** varints. Each call to this function appends a single varint to a list.
137814*/
137815static void fts3PutDeltaVarint(
137816  char **pp,                      /* IN/OUT: Output pointer */
137817  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
137818  sqlite3_int64 iVal              /* Write this value to the list */
137819){
137820  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
137821  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
137822  *piPrev = iVal;
137823}
137824
137825/*
137826** When this function is called, *ppPoslist is assumed to point to the
137827** start of a position-list. After it returns, *ppPoslist points to the
137828** first byte after the position-list.
137829**
137830** A position list is list of positions (delta encoded) and columns for
137831** a single document record of a doclist.  So, in other words, this
137832** routine advances *ppPoslist so that it points to the next docid in
137833** the doclist, or to the first byte past the end of the doclist.
137834**
137835** If pp is not NULL, then the contents of the position list are copied
137836** to *pp. *pp is set to point to the first byte past the last byte copied
137837** before this function returns.
137838*/
137839static void fts3PoslistCopy(char **pp, char **ppPoslist){
137840  char *pEnd = *ppPoslist;
137841  char c = 0;
137842
137843  /* The end of a position list is marked by a zero encoded as an FTS3
137844  ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
137845  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
137846  ** of some other, multi-byte, value.
137847  **
137848  ** The following while-loop moves pEnd to point to the first byte that is not
137849  ** immediately preceded by a byte with the 0x80 bit set. Then increments
137850  ** pEnd once more so that it points to the byte immediately following the
137851  ** last byte in the position-list.
137852  */
137853  while( *pEnd | c ){
137854    c = *pEnd++ & 0x80;
137855    testcase( c!=0 && (*pEnd)==0 );
137856  }
137857  pEnd++;  /* Advance past the POS_END terminator byte */
137858
137859  if( pp ){
137860    int n = (int)(pEnd - *ppPoslist);
137861    char *p = *pp;
137862    memcpy(p, *ppPoslist, n);
137863    p += n;
137864    *pp = p;
137865  }
137866  *ppPoslist = pEnd;
137867}
137868
137869/*
137870** When this function is called, *ppPoslist is assumed to point to the
137871** start of a column-list. After it returns, *ppPoslist points to the
137872** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
137873**
137874** A column-list is list of delta-encoded positions for a single column
137875** within a single document within a doclist.
137876**
137877** The column-list is terminated either by a POS_COLUMN varint (1) or
137878** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
137879** the POS_COLUMN or POS_END that terminates the column-list.
137880**
137881** If pp is not NULL, then the contents of the column-list are copied
137882** to *pp. *pp is set to point to the first byte past the last byte copied
137883** before this function returns.  The POS_COLUMN or POS_END terminator
137884** is not copied into *pp.
137885*/
137886static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
137887  char *pEnd = *ppPoslist;
137888  char c = 0;
137889
137890  /* A column-list is terminated by either a 0x01 or 0x00 byte that is
137891  ** not part of a multi-byte varint.
137892  */
137893  while( 0xFE & (*pEnd | c) ){
137894    c = *pEnd++ & 0x80;
137895    testcase( c!=0 && ((*pEnd)&0xfe)==0 );
137896  }
137897  if( pp ){
137898    int n = (int)(pEnd - *ppPoslist);
137899    char *p = *pp;
137900    memcpy(p, *ppPoslist, n);
137901    p += n;
137902    *pp = p;
137903  }
137904  *ppPoslist = pEnd;
137905}
137906
137907/*
137908** Value used to signify the end of an position-list. This is safe because
137909** it is not possible to have a document with 2^31 terms.
137910*/
137911#define POSITION_LIST_END 0x7fffffff
137912
137913/*
137914** This function is used to help parse position-lists. When this function is
137915** called, *pp may point to the start of the next varint in the position-list
137916** being parsed, or it may point to 1 byte past the end of the position-list
137917** (in which case **pp will be a terminator bytes POS_END (0) or
137918** (1)).
137919**
137920** If *pp points past the end of the current position-list, set *pi to
137921** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
137922** increment the current value of *pi by the value read, and set *pp to
137923** point to the next value before returning.
137924**
137925** Before calling this routine *pi must be initialized to the value of
137926** the previous position, or zero if we are reading the first position
137927** in the position-list.  Because positions are delta-encoded, the value
137928** of the previous position is needed in order to compute the value of
137929** the next position.
137930*/
137931static void fts3ReadNextPos(
137932  char **pp,                    /* IN/OUT: Pointer into position-list buffer */
137933  sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
137934){
137935  if( (**pp)&0xFE ){
137936    fts3GetDeltaVarint(pp, pi);
137937    *pi -= 2;
137938  }else{
137939    *pi = POSITION_LIST_END;
137940  }
137941}
137942
137943/*
137944** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
137945** the value of iCol encoded as a varint to *pp.   This will start a new
137946** column list.
137947**
137948** Set *pp to point to the byte just after the last byte written before
137949** returning (do not modify it if iCol==0). Return the total number of bytes
137950** written (0 if iCol==0).
137951*/
137952static int fts3PutColNumber(char **pp, int iCol){
137953  int n = 0;                      /* Number of bytes written */
137954  if( iCol ){
137955    char *p = *pp;                /* Output pointer */
137956    n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
137957    *p = 0x01;
137958    *pp = &p[n];
137959  }
137960  return n;
137961}
137962
137963/*
137964** Compute the union of two position lists.  The output written
137965** into *pp contains all positions of both *pp1 and *pp2 in sorted
137966** order and with any duplicates removed.  All pointers are
137967** updated appropriately.   The caller is responsible for insuring
137968** that there is enough space in *pp to hold the complete output.
137969*/
137970static void fts3PoslistMerge(
137971  char **pp,                      /* Output buffer */
137972  char **pp1,                     /* Left input list */
137973  char **pp2                      /* Right input list */
137974){
137975  char *p = *pp;
137976  char *p1 = *pp1;
137977  char *p2 = *pp2;
137978
137979  while( *p1 || *p2 ){
137980    int iCol1;         /* The current column index in pp1 */
137981    int iCol2;         /* The current column index in pp2 */
137982
137983    if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
137984    else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
137985    else iCol1 = 0;
137986
137987    if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
137988    else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
137989    else iCol2 = 0;
137990
137991    if( iCol1==iCol2 ){
137992      sqlite3_int64 i1 = 0;       /* Last position from pp1 */
137993      sqlite3_int64 i2 = 0;       /* Last position from pp2 */
137994      sqlite3_int64 iPrev = 0;
137995      int n = fts3PutColNumber(&p, iCol1);
137996      p1 += n;
137997      p2 += n;
137998
137999      /* At this point, both p1 and p2 point to the start of column-lists
138000      ** for the same column (the column with index iCol1 and iCol2).
138001      ** A column-list is a list of non-negative delta-encoded varints, each
138002      ** incremented by 2 before being stored. Each list is terminated by a
138003      ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
138004      ** and writes the results to buffer p. p is left pointing to the byte
138005      ** after the list written. No terminator (POS_END or POS_COLUMN) is
138006      ** written to the output.
138007      */
138008      fts3GetDeltaVarint(&p1, &i1);
138009      fts3GetDeltaVarint(&p2, &i2);
138010      do {
138011        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
138012        iPrev -= 2;
138013        if( i1==i2 ){
138014          fts3ReadNextPos(&p1, &i1);
138015          fts3ReadNextPos(&p2, &i2);
138016        }else if( i1<i2 ){
138017          fts3ReadNextPos(&p1, &i1);
138018        }else{
138019          fts3ReadNextPos(&p2, &i2);
138020        }
138021      }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
138022    }else if( iCol1<iCol2 ){
138023      p1 += fts3PutColNumber(&p, iCol1);
138024      fts3ColumnlistCopy(&p, &p1);
138025    }else{
138026      p2 += fts3PutColNumber(&p, iCol2);
138027      fts3ColumnlistCopy(&p, &p2);
138028    }
138029  }
138030
138031  *p++ = POS_END;
138032  *pp = p;
138033  *pp1 = p1 + 1;
138034  *pp2 = p2 + 1;
138035}
138036
138037/*
138038** This function is used to merge two position lists into one. When it is
138039** called, *pp1 and *pp2 must both point to position lists. A position-list is
138040** the part of a doclist that follows each document id. For example, if a row
138041** contains:
138042**
138043**     'a b c'|'x y z'|'a b b a'
138044**
138045** Then the position list for this row for token 'b' would consist of:
138046**
138047**     0x02 0x01 0x02 0x03 0x03 0x00
138048**
138049** When this function returns, both *pp1 and *pp2 are left pointing to the
138050** byte following the 0x00 terminator of their respective position lists.
138051**
138052** If isSaveLeft is 0, an entry is added to the output position list for
138053** each position in *pp2 for which there exists one or more positions in
138054** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
138055** when the *pp1 token appears before the *pp2 token, but not more than nToken
138056** slots before it.
138057**
138058** e.g. nToken==1 searches for adjacent positions.
138059*/
138060static int fts3PoslistPhraseMerge(
138061  char **pp,                      /* IN/OUT: Preallocated output buffer */
138062  int nToken,                     /* Maximum difference in token positions */
138063  int isSaveLeft,                 /* Save the left position */
138064  int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
138065  char **pp1,                     /* IN/OUT: Left input list */
138066  char **pp2                      /* IN/OUT: Right input list */
138067){
138068  char *p = *pp;
138069  char *p1 = *pp1;
138070  char *p2 = *pp2;
138071  int iCol1 = 0;
138072  int iCol2 = 0;
138073
138074  /* Never set both isSaveLeft and isExact for the same invocation. */
138075  assert( isSaveLeft==0 || isExact==0 );
138076
138077  assert( p!=0 && *p1!=0 && *p2!=0 );
138078  if( *p1==POS_COLUMN ){
138079    p1++;
138080    p1 += fts3GetVarint32(p1, &iCol1);
138081  }
138082  if( *p2==POS_COLUMN ){
138083    p2++;
138084    p2 += fts3GetVarint32(p2, &iCol2);
138085  }
138086
138087  while( 1 ){
138088    if( iCol1==iCol2 ){
138089      char *pSave = p;
138090      sqlite3_int64 iPrev = 0;
138091      sqlite3_int64 iPos1 = 0;
138092      sqlite3_int64 iPos2 = 0;
138093
138094      if( iCol1 ){
138095        *p++ = POS_COLUMN;
138096        p += sqlite3Fts3PutVarint(p, iCol1);
138097      }
138098
138099      assert( *p1!=POS_END && *p1!=POS_COLUMN );
138100      assert( *p2!=POS_END && *p2!=POS_COLUMN );
138101      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
138102      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
138103
138104      while( 1 ){
138105        if( iPos2==iPos1+nToken
138106         || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
138107        ){
138108          sqlite3_int64 iSave;
138109          iSave = isSaveLeft ? iPos1 : iPos2;
138110          fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
138111          pSave = 0;
138112          assert( p );
138113        }
138114        if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
138115          if( (*p2&0xFE)==0 ) break;
138116          fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
138117        }else{
138118          if( (*p1&0xFE)==0 ) break;
138119          fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
138120        }
138121      }
138122
138123      if( pSave ){
138124        assert( pp && p );
138125        p = pSave;
138126      }
138127
138128      fts3ColumnlistCopy(0, &p1);
138129      fts3ColumnlistCopy(0, &p2);
138130      assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
138131      if( 0==*p1 || 0==*p2 ) break;
138132
138133      p1++;
138134      p1 += fts3GetVarint32(p1, &iCol1);
138135      p2++;
138136      p2 += fts3GetVarint32(p2, &iCol2);
138137    }
138138
138139    /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
138140    ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
138141    ** end of the position list, or the 0x01 that precedes the next
138142    ** column-number in the position list.
138143    */
138144    else if( iCol1<iCol2 ){
138145      fts3ColumnlistCopy(0, &p1);
138146      if( 0==*p1 ) break;
138147      p1++;
138148      p1 += fts3GetVarint32(p1, &iCol1);
138149    }else{
138150      fts3ColumnlistCopy(0, &p2);
138151      if( 0==*p2 ) break;
138152      p2++;
138153      p2 += fts3GetVarint32(p2, &iCol2);
138154    }
138155  }
138156
138157  fts3PoslistCopy(0, &p2);
138158  fts3PoslistCopy(0, &p1);
138159  *pp1 = p1;
138160  *pp2 = p2;
138161  if( *pp==p ){
138162    return 0;
138163  }
138164  *p++ = 0x00;
138165  *pp = p;
138166  return 1;
138167}
138168
138169/*
138170** Merge two position-lists as required by the NEAR operator. The argument
138171** position lists correspond to the left and right phrases of an expression
138172** like:
138173**
138174**     "phrase 1" NEAR "phrase number 2"
138175**
138176** Position list *pp1 corresponds to the left-hand side of the NEAR
138177** expression and *pp2 to the right. As usual, the indexes in the position
138178** lists are the offsets of the last token in each phrase (tokens "1" and "2"
138179** in the example above).
138180**
138181** The output position list - written to *pp - is a copy of *pp2 with those
138182** entries that are not sufficiently NEAR entries in *pp1 removed.
138183*/
138184static int fts3PoslistNearMerge(
138185  char **pp,                      /* Output buffer */
138186  char *aTmp,                     /* Temporary buffer space */
138187  int nRight,                     /* Maximum difference in token positions */
138188  int nLeft,                      /* Maximum difference in token positions */
138189  char **pp1,                     /* IN/OUT: Left input list */
138190  char **pp2                      /* IN/OUT: Right input list */
138191){
138192  char *p1 = *pp1;
138193  char *p2 = *pp2;
138194
138195  char *pTmp1 = aTmp;
138196  char *pTmp2;
138197  char *aTmp2;
138198  int res = 1;
138199
138200  fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
138201  aTmp2 = pTmp2 = pTmp1;
138202  *pp1 = p1;
138203  *pp2 = p2;
138204  fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
138205  if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
138206    fts3PoslistMerge(pp, &aTmp, &aTmp2);
138207  }else if( pTmp1!=aTmp ){
138208    fts3PoslistCopy(pp, &aTmp);
138209  }else if( pTmp2!=aTmp2 ){
138210    fts3PoslistCopy(pp, &aTmp2);
138211  }else{
138212    res = 0;
138213  }
138214
138215  return res;
138216}
138217
138218/*
138219** An instance of this function is used to merge together the (potentially
138220** large number of) doclists for each term that matches a prefix query.
138221** See function fts3TermSelectMerge() for details.
138222*/
138223typedef struct TermSelect TermSelect;
138224struct TermSelect {
138225  char *aaOutput[16];             /* Malloc'd output buffers */
138226  int anOutput[16];               /* Size each output buffer in bytes */
138227};
138228
138229/*
138230** This function is used to read a single varint from a buffer. Parameter
138231** pEnd points 1 byte past the end of the buffer. When this function is
138232** called, if *pp points to pEnd or greater, then the end of the buffer
138233** has been reached. In this case *pp is set to 0 and the function returns.
138234**
138235** If *pp does not point to or past pEnd, then a single varint is read
138236** from *pp. *pp is then set to point 1 byte past the end of the read varint.
138237**
138238** If bDescIdx is false, the value read is added to *pVal before returning.
138239** If it is true, the value read is subtracted from *pVal before this
138240** function returns.
138241*/
138242static void fts3GetDeltaVarint3(
138243  char **pp,                      /* IN/OUT: Point to read varint from */
138244  char *pEnd,                     /* End of buffer */
138245  int bDescIdx,                   /* True if docids are descending */
138246  sqlite3_int64 *pVal             /* IN/OUT: Integer value */
138247){
138248  if( *pp>=pEnd ){
138249    *pp = 0;
138250  }else{
138251    sqlite3_int64 iVal;
138252    *pp += sqlite3Fts3GetVarint(*pp, &iVal);
138253    if( bDescIdx ){
138254      *pVal -= iVal;
138255    }else{
138256      *pVal += iVal;
138257    }
138258  }
138259}
138260
138261/*
138262** This function is used to write a single varint to a buffer. The varint
138263** is written to *pp. Before returning, *pp is set to point 1 byte past the
138264** end of the value written.
138265**
138266** If *pbFirst is zero when this function is called, the value written to
138267** the buffer is that of parameter iVal.
138268**
138269** If *pbFirst is non-zero when this function is called, then the value
138270** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
138271** (if bDescIdx is non-zero).
138272**
138273** Before returning, this function always sets *pbFirst to 1 and *piPrev
138274** to the value of parameter iVal.
138275*/
138276static void fts3PutDeltaVarint3(
138277  char **pp,                      /* IN/OUT: Output pointer */
138278  int bDescIdx,                   /* True for descending docids */
138279  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
138280  int *pbFirst,                   /* IN/OUT: True after first int written */
138281  sqlite3_int64 iVal              /* Write this value to the list */
138282){
138283  sqlite3_int64 iWrite;
138284  if( bDescIdx==0 || *pbFirst==0 ){
138285    iWrite = iVal - *piPrev;
138286  }else{
138287    iWrite = *piPrev - iVal;
138288  }
138289  assert( *pbFirst || *piPrev==0 );
138290  assert( *pbFirst==0 || iWrite>0 );
138291  *pp += sqlite3Fts3PutVarint(*pp, iWrite);
138292  *piPrev = iVal;
138293  *pbFirst = 1;
138294}
138295
138296
138297/*
138298** This macro is used by various functions that merge doclists. The two
138299** arguments are 64-bit docid values. If the value of the stack variable
138300** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
138301** Otherwise, (i2-i1).
138302**
138303** Using this makes it easier to write code that can merge doclists that are
138304** sorted in either ascending or descending order.
138305*/
138306#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
138307
138308/*
138309** This function does an "OR" merge of two doclists (output contains all
138310** positions contained in either argument doclist). If the docids in the
138311** input doclists are sorted in ascending order, parameter bDescDoclist
138312** should be false. If they are sorted in ascending order, it should be
138313** passed a non-zero value.
138314**
138315** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
138316** containing the output doclist and SQLITE_OK is returned. In this case
138317** *pnOut is set to the number of bytes in the output doclist.
138318**
138319** If an error occurs, an SQLite error code is returned. The output values
138320** are undefined in this case.
138321*/
138322static int fts3DoclistOrMerge(
138323  int bDescDoclist,               /* True if arguments are desc */
138324  char *a1, int n1,               /* First doclist */
138325  char *a2, int n2,               /* Second doclist */
138326  char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
138327){
138328  sqlite3_int64 i1 = 0;
138329  sqlite3_int64 i2 = 0;
138330  sqlite3_int64 iPrev = 0;
138331  char *pEnd1 = &a1[n1];
138332  char *pEnd2 = &a2[n2];
138333  char *p1 = a1;
138334  char *p2 = a2;
138335  char *p;
138336  char *aOut;
138337  int bFirstOut = 0;
138338
138339  *paOut = 0;
138340  *pnOut = 0;
138341
138342  /* Allocate space for the output. Both the input and output doclists
138343  ** are delta encoded. If they are in ascending order (bDescDoclist==0),
138344  ** then the first docid in each list is simply encoded as a varint. For
138345  ** each subsequent docid, the varint stored is the difference between the
138346  ** current and previous docid (a positive number - since the list is in
138347  ** ascending order).
138348  **
138349  ** The first docid written to the output is therefore encoded using the
138350  ** same number of bytes as it is in whichever of the input lists it is
138351  ** read from. And each subsequent docid read from the same input list
138352  ** consumes either the same or less bytes as it did in the input (since
138353  ** the difference between it and the previous value in the output must
138354  ** be a positive value less than or equal to the delta value read from
138355  ** the input list). The same argument applies to all but the first docid
138356  ** read from the 'other' list. And to the contents of all position lists
138357  ** that will be copied and merged from the input to the output.
138358  **
138359  ** However, if the first docid copied to the output is a negative number,
138360  ** then the encoding of the first docid from the 'other' input list may
138361  ** be larger in the output than it was in the input (since the delta value
138362  ** may be a larger positive integer than the actual docid).
138363  **
138364  ** The space required to store the output is therefore the sum of the
138365  ** sizes of the two inputs, plus enough space for exactly one of the input
138366  ** docids to grow.
138367  **
138368  ** A symetric argument may be made if the doclists are in descending
138369  ** order.
138370  */
138371  aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
138372  if( !aOut ) return SQLITE_NOMEM;
138373
138374  p = aOut;
138375  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
138376  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
138377  while( p1 || p2 ){
138378    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
138379
138380    if( p2 && p1 && iDiff==0 ){
138381      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
138382      fts3PoslistMerge(&p, &p1, &p2);
138383      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
138384      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
138385    }else if( !p2 || (p1 && iDiff<0) ){
138386      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
138387      fts3PoslistCopy(&p, &p1);
138388      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
138389    }else{
138390      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
138391      fts3PoslistCopy(&p, &p2);
138392      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
138393    }
138394  }
138395
138396  *paOut = aOut;
138397  *pnOut = (int)(p-aOut);
138398  assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
138399  return SQLITE_OK;
138400}
138401
138402/*
138403** This function does a "phrase" merge of two doclists. In a phrase merge,
138404** the output contains a copy of each position from the right-hand input
138405** doclist for which there is a position in the left-hand input doclist
138406** exactly nDist tokens before it.
138407**
138408** If the docids in the input doclists are sorted in ascending order,
138409** parameter bDescDoclist should be false. If they are sorted in ascending
138410** order, it should be passed a non-zero value.
138411**
138412** The right-hand input doclist is overwritten by this function.
138413*/
138414static int fts3DoclistPhraseMerge(
138415  int bDescDoclist,               /* True if arguments are desc */
138416  int nDist,                      /* Distance from left to right (1=adjacent) */
138417  char *aLeft, int nLeft,         /* Left doclist */
138418  char **paRight, int *pnRight    /* IN/OUT: Right/output doclist */
138419){
138420  sqlite3_int64 i1 = 0;
138421  sqlite3_int64 i2 = 0;
138422  sqlite3_int64 iPrev = 0;
138423  char *aRight = *paRight;
138424  char *pEnd1 = &aLeft[nLeft];
138425  char *pEnd2 = &aRight[*pnRight];
138426  char *p1 = aLeft;
138427  char *p2 = aRight;
138428  char *p;
138429  int bFirstOut = 0;
138430  char *aOut;
138431
138432  assert( nDist>0 );
138433  if( bDescDoclist ){
138434    aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
138435    if( aOut==0 ) return SQLITE_NOMEM;
138436  }else{
138437    aOut = aRight;
138438  }
138439  p = aOut;
138440
138441  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
138442  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
138443
138444  while( p1 && p2 ){
138445    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
138446    if( iDiff==0 ){
138447      char *pSave = p;
138448      sqlite3_int64 iPrevSave = iPrev;
138449      int bFirstOutSave = bFirstOut;
138450
138451      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
138452      if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
138453        p = pSave;
138454        iPrev = iPrevSave;
138455        bFirstOut = bFirstOutSave;
138456      }
138457      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
138458      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
138459    }else if( iDiff<0 ){
138460      fts3PoslistCopy(0, &p1);
138461      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
138462    }else{
138463      fts3PoslistCopy(0, &p2);
138464      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
138465    }
138466  }
138467
138468  *pnRight = (int)(p - aOut);
138469  if( bDescDoclist ){
138470    sqlite3_free(aRight);
138471    *paRight = aOut;
138472  }
138473
138474  return SQLITE_OK;
138475}
138476
138477/*
138478** Argument pList points to a position list nList bytes in size. This
138479** function checks to see if the position list contains any entries for
138480** a token in position 0 (of any column). If so, it writes argument iDelta
138481** to the output buffer pOut, followed by a position list consisting only
138482** of the entries from pList at position 0, and terminated by an 0x00 byte.
138483** The value returned is the number of bytes written to pOut (if any).
138484*/
138485SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
138486  sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
138487  char *pList,                    /* Position list (no 0x00 term) */
138488  int nList,                      /* Size of pList in bytes */
138489  char *pOut                      /* Write output here */
138490){
138491  int nOut = 0;
138492  int bWritten = 0;               /* True once iDelta has been written */
138493  char *p = pList;
138494  char *pEnd = &pList[nList];
138495
138496  if( *p!=0x01 ){
138497    if( *p==0x02 ){
138498      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
138499      pOut[nOut++] = 0x02;
138500      bWritten = 1;
138501    }
138502    fts3ColumnlistCopy(0, &p);
138503  }
138504
138505  while( p<pEnd && *p==0x01 ){
138506    sqlite3_int64 iCol;
138507    p++;
138508    p += sqlite3Fts3GetVarint(p, &iCol);
138509    if( *p==0x02 ){
138510      if( bWritten==0 ){
138511        nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
138512        bWritten = 1;
138513      }
138514      pOut[nOut++] = 0x01;
138515      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
138516      pOut[nOut++] = 0x02;
138517    }
138518    fts3ColumnlistCopy(0, &p);
138519  }
138520  if( bWritten ){
138521    pOut[nOut++] = 0x00;
138522  }
138523
138524  return nOut;
138525}
138526
138527
138528/*
138529** Merge all doclists in the TermSelect.aaOutput[] array into a single
138530** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
138531** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
138532**
138533** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
138534** the responsibility of the caller to free any doclists left in the
138535** TermSelect.aaOutput[] array.
138536*/
138537static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
138538  char *aOut = 0;
138539  int nOut = 0;
138540  int i;
138541
138542  /* Loop through the doclists in the aaOutput[] array. Merge them all
138543  ** into a single doclist.
138544  */
138545  for(i=0; i<SizeofArray(pTS->aaOutput); i++){
138546    if( pTS->aaOutput[i] ){
138547      if( !aOut ){
138548        aOut = pTS->aaOutput[i];
138549        nOut = pTS->anOutput[i];
138550        pTS->aaOutput[i] = 0;
138551      }else{
138552        int nNew;
138553        char *aNew;
138554
138555        int rc = fts3DoclistOrMerge(p->bDescIdx,
138556            pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
138557        );
138558        if( rc!=SQLITE_OK ){
138559          sqlite3_free(aOut);
138560          return rc;
138561        }
138562
138563        sqlite3_free(pTS->aaOutput[i]);
138564        sqlite3_free(aOut);
138565        pTS->aaOutput[i] = 0;
138566        aOut = aNew;
138567        nOut = nNew;
138568      }
138569    }
138570  }
138571
138572  pTS->aaOutput[0] = aOut;
138573  pTS->anOutput[0] = nOut;
138574  return SQLITE_OK;
138575}
138576
138577/*
138578** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
138579** as the first argument. The merge is an "OR" merge (see function
138580** fts3DoclistOrMerge() for details).
138581**
138582** This function is called with the doclist for each term that matches
138583** a queried prefix. It merges all these doclists into one, the doclist
138584** for the specified prefix. Since there can be a very large number of
138585** doclists to merge, the merging is done pair-wise using the TermSelect
138586** object.
138587**
138588** This function returns SQLITE_OK if the merge is successful, or an
138589** SQLite error code (SQLITE_NOMEM) if an error occurs.
138590*/
138591static int fts3TermSelectMerge(
138592  Fts3Table *p,                   /* FTS table handle */
138593  TermSelect *pTS,                /* TermSelect object to merge into */
138594  char *aDoclist,                 /* Pointer to doclist */
138595  int nDoclist                    /* Size of aDoclist in bytes */
138596){
138597  if( pTS->aaOutput[0]==0 ){
138598    /* If this is the first term selected, copy the doclist to the output
138599    ** buffer using memcpy().
138600    **
138601    ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
138602    ** allocation. This is so as to ensure that the buffer is big enough
138603    ** to hold the current doclist AND'd with any other doclist. If the
138604    ** doclists are stored in order=ASC order, this padding would not be
138605    ** required (since the size of [doclistA AND doclistB] is always less
138606    ** than or equal to the size of [doclistA] in that case). But this is
138607    ** not true for order=DESC. For example, a doclist containing (1, -1)
138608    ** may be smaller than (-1), as in the first example the -1 may be stored
138609    ** as a single-byte delta, whereas in the second it must be stored as a
138610    ** FTS3_VARINT_MAX byte varint.
138611    **
138612    ** Similar padding is added in the fts3DoclistOrMerge() function.
138613    */
138614    pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
138615    pTS->anOutput[0] = nDoclist;
138616    if( pTS->aaOutput[0] ){
138617      memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
138618    }else{
138619      return SQLITE_NOMEM;
138620    }
138621  }else{
138622    char *aMerge = aDoclist;
138623    int nMerge = nDoclist;
138624    int iOut;
138625
138626    for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
138627      if( pTS->aaOutput[iOut]==0 ){
138628        assert( iOut>0 );
138629        pTS->aaOutput[iOut] = aMerge;
138630        pTS->anOutput[iOut] = nMerge;
138631        break;
138632      }else{
138633        char *aNew;
138634        int nNew;
138635
138636        int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
138637            pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
138638        );
138639        if( rc!=SQLITE_OK ){
138640          if( aMerge!=aDoclist ) sqlite3_free(aMerge);
138641          return rc;
138642        }
138643
138644        if( aMerge!=aDoclist ) sqlite3_free(aMerge);
138645        sqlite3_free(pTS->aaOutput[iOut]);
138646        pTS->aaOutput[iOut] = 0;
138647
138648        aMerge = aNew;
138649        nMerge = nNew;
138650        if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
138651          pTS->aaOutput[iOut] = aMerge;
138652          pTS->anOutput[iOut] = nMerge;
138653        }
138654      }
138655    }
138656  }
138657  return SQLITE_OK;
138658}
138659
138660/*
138661** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
138662*/
138663static int fts3SegReaderCursorAppend(
138664  Fts3MultiSegReader *pCsr,
138665  Fts3SegReader *pNew
138666){
138667  if( (pCsr->nSegment%16)==0 ){
138668    Fts3SegReader **apNew;
138669    int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
138670    apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
138671    if( !apNew ){
138672      sqlite3Fts3SegReaderFree(pNew);
138673      return SQLITE_NOMEM;
138674    }
138675    pCsr->apSegment = apNew;
138676  }
138677  pCsr->apSegment[pCsr->nSegment++] = pNew;
138678  return SQLITE_OK;
138679}
138680
138681/*
138682** Add seg-reader objects to the Fts3MultiSegReader object passed as the
138683** 8th argument.
138684**
138685** This function returns SQLITE_OK if successful, or an SQLite error code
138686** otherwise.
138687*/
138688static int fts3SegReaderCursor(
138689  Fts3Table *p,                   /* FTS3 table handle */
138690  int iLangid,                    /* Language id */
138691  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
138692  int iLevel,                     /* Level of segments to scan */
138693  const char *zTerm,              /* Term to query for */
138694  int nTerm,                      /* Size of zTerm in bytes */
138695  int isPrefix,                   /* True for a prefix search */
138696  int isScan,                     /* True to scan from zTerm to EOF */
138697  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
138698){
138699  int rc = SQLITE_OK;             /* Error code */
138700  sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
138701  int rc2;                        /* Result of sqlite3_reset() */
138702
138703  /* If iLevel is less than 0 and this is not a scan, include a seg-reader
138704  ** for the pending-terms. If this is a scan, then this call must be being
138705  ** made by an fts4aux module, not an FTS table. In this case calling
138706  ** Fts3SegReaderPending might segfault, as the data structures used by
138707  ** fts4aux are not completely populated. So it's easiest to filter these
138708  ** calls out here.  */
138709  if( iLevel<0 && p->aIndex ){
138710    Fts3SegReader *pSeg = 0;
138711    rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
138712    if( rc==SQLITE_OK && pSeg ){
138713      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
138714    }
138715  }
138716
138717  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
138718    if( rc==SQLITE_OK ){
138719      rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
138720    }
138721
138722    while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
138723      Fts3SegReader *pSeg = 0;
138724
138725      /* Read the values returned by the SELECT into local variables. */
138726      sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
138727      sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
138728      sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
138729      int nRoot = sqlite3_column_bytes(pStmt, 4);
138730      char const *zRoot = sqlite3_column_blob(pStmt, 4);
138731
138732      /* If zTerm is not NULL, and this segment is not stored entirely on its
138733      ** root node, the range of leaves scanned can be reduced. Do this. */
138734      if( iStartBlock && zTerm ){
138735        sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
138736        rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
138737        if( rc!=SQLITE_OK ) goto finished;
138738        if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
138739      }
138740
138741      rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
138742          (isPrefix==0 && isScan==0),
138743          iStartBlock, iLeavesEndBlock,
138744          iEndBlock, zRoot, nRoot, &pSeg
138745      );
138746      if( rc!=SQLITE_OK ) goto finished;
138747      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
138748    }
138749  }
138750
138751 finished:
138752  rc2 = sqlite3_reset(pStmt);
138753  if( rc==SQLITE_DONE ) rc = rc2;
138754
138755  return rc;
138756}
138757
138758/*
138759** Set up a cursor object for iterating through a full-text index or a
138760** single level therein.
138761*/
138762SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
138763  Fts3Table *p,                   /* FTS3 table handle */
138764  int iLangid,                    /* Language-id to search */
138765  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
138766  int iLevel,                     /* Level of segments to scan */
138767  const char *zTerm,              /* Term to query for */
138768  int nTerm,                      /* Size of zTerm in bytes */
138769  int isPrefix,                   /* True for a prefix search */
138770  int isScan,                     /* True to scan from zTerm to EOF */
138771  Fts3MultiSegReader *pCsr       /* Cursor object to populate */
138772){
138773  assert( iIndex>=0 && iIndex<p->nIndex );
138774  assert( iLevel==FTS3_SEGCURSOR_ALL
138775      ||  iLevel==FTS3_SEGCURSOR_PENDING
138776      ||  iLevel>=0
138777  );
138778  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
138779  assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
138780  assert( isPrefix==0 || isScan==0 );
138781
138782  memset(pCsr, 0, sizeof(Fts3MultiSegReader));
138783  return fts3SegReaderCursor(
138784      p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
138785  );
138786}
138787
138788/*
138789** In addition to its current configuration, have the Fts3MultiSegReader
138790** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
138791**
138792** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
138793*/
138794static int fts3SegReaderCursorAddZero(
138795  Fts3Table *p,                   /* FTS virtual table handle */
138796  int iLangid,
138797  const char *zTerm,              /* Term to scan doclist of */
138798  int nTerm,                      /* Number of bytes in zTerm */
138799  Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
138800){
138801  return fts3SegReaderCursor(p,
138802      iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
138803  );
138804}
138805
138806/*
138807** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
138808** if isPrefix is true, to scan the doclist for all terms for which
138809** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
138810** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
138811** an SQLite error code.
138812**
138813** It is the responsibility of the caller to free this object by eventually
138814** passing it to fts3SegReaderCursorFree()
138815**
138816** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
138817** Output parameter *ppSegcsr is set to 0 if an error occurs.
138818*/
138819static int fts3TermSegReaderCursor(
138820  Fts3Cursor *pCsr,               /* Virtual table cursor handle */
138821  const char *zTerm,              /* Term to query for */
138822  int nTerm,                      /* Size of zTerm in bytes */
138823  int isPrefix,                   /* True for a prefix search */
138824  Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
138825){
138826  Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
138827  int rc = SQLITE_NOMEM;          /* Return code */
138828
138829  pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
138830  if( pSegcsr ){
138831    int i;
138832    int bFound = 0;               /* True once an index has been found */
138833    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
138834
138835    if( isPrefix ){
138836      for(i=1; bFound==0 && i<p->nIndex; i++){
138837        if( p->aIndex[i].nPrefix==nTerm ){
138838          bFound = 1;
138839          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
138840              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
138841          );
138842          pSegcsr->bLookup = 1;
138843        }
138844      }
138845
138846      for(i=1; bFound==0 && i<p->nIndex; i++){
138847        if( p->aIndex[i].nPrefix==nTerm+1 ){
138848          bFound = 1;
138849          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
138850              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
138851          );
138852          if( rc==SQLITE_OK ){
138853            rc = fts3SegReaderCursorAddZero(
138854                p, pCsr->iLangid, zTerm, nTerm, pSegcsr
138855            );
138856          }
138857        }
138858      }
138859    }
138860
138861    if( bFound==0 ){
138862      rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
138863          0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
138864      );
138865      pSegcsr->bLookup = !isPrefix;
138866    }
138867  }
138868
138869  *ppSegcsr = pSegcsr;
138870  return rc;
138871}
138872
138873/*
138874** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
138875*/
138876static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
138877  sqlite3Fts3SegReaderFinish(pSegcsr);
138878  sqlite3_free(pSegcsr);
138879}
138880
138881/*
138882** This function retrieves the doclist for the specified term (or term
138883** prefix) from the database.
138884*/
138885static int fts3TermSelect(
138886  Fts3Table *p,                   /* Virtual table handle */
138887  Fts3PhraseToken *pTok,          /* Token to query for */
138888  int iColumn,                    /* Column to query (or -ve for all columns) */
138889  int *pnOut,                     /* OUT: Size of buffer at *ppOut */
138890  char **ppOut                    /* OUT: Malloced result buffer */
138891){
138892  int rc;                         /* Return code */
138893  Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
138894  TermSelect tsc;                 /* Object for pair-wise doclist merging */
138895  Fts3SegFilter filter;           /* Segment term filter configuration */
138896
138897  pSegcsr = pTok->pSegcsr;
138898  memset(&tsc, 0, sizeof(TermSelect));
138899
138900  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
138901        | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
138902        | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
138903        | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
138904  filter.iCol = iColumn;
138905  filter.zTerm = pTok->z;
138906  filter.nTerm = pTok->n;
138907
138908  rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
138909  while( SQLITE_OK==rc
138910      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
138911  ){
138912    rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
138913  }
138914
138915  if( rc==SQLITE_OK ){
138916    rc = fts3TermSelectFinishMerge(p, &tsc);
138917  }
138918  if( rc==SQLITE_OK ){
138919    *ppOut = tsc.aaOutput[0];
138920    *pnOut = tsc.anOutput[0];
138921  }else{
138922    int i;
138923    for(i=0; i<SizeofArray(tsc.aaOutput); i++){
138924      sqlite3_free(tsc.aaOutput[i]);
138925    }
138926  }
138927
138928  fts3SegReaderCursorFree(pSegcsr);
138929  pTok->pSegcsr = 0;
138930  return rc;
138931}
138932
138933/*
138934** This function counts the total number of docids in the doclist stored
138935** in buffer aList[], size nList bytes.
138936**
138937** If the isPoslist argument is true, then it is assumed that the doclist
138938** contains a position-list following each docid. Otherwise, it is assumed
138939** that the doclist is simply a list of docids stored as delta encoded
138940** varints.
138941*/
138942static int fts3DoclistCountDocids(char *aList, int nList){
138943  int nDoc = 0;                   /* Return value */
138944  if( aList ){
138945    char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
138946    char *p = aList;              /* Cursor */
138947    while( p<aEnd ){
138948      nDoc++;
138949      while( (*p++)&0x80 );     /* Skip docid varint */
138950      fts3PoslistCopy(0, &p);   /* Skip over position list */
138951    }
138952  }
138953
138954  return nDoc;
138955}
138956
138957/*
138958** Advance the cursor to the next row in the %_content table that
138959** matches the search criteria.  For a MATCH search, this will be
138960** the next row that matches. For a full-table scan, this will be
138961** simply the next row in the %_content table.  For a docid lookup,
138962** this routine simply sets the EOF flag.
138963**
138964** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
138965** even if we reach end-of-file.  The fts3EofMethod() will be called
138966** subsequently to determine whether or not an EOF was hit.
138967*/
138968static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
138969  int rc;
138970  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
138971  if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
138972    if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
138973      pCsr->isEof = 1;
138974      rc = sqlite3_reset(pCsr->pStmt);
138975    }else{
138976      pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
138977      rc = SQLITE_OK;
138978    }
138979  }else{
138980    rc = fts3EvalNext((Fts3Cursor *)pCursor);
138981  }
138982  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
138983  return rc;
138984}
138985
138986/*
138987** The following are copied from sqliteInt.h.
138988**
138989** Constants for the largest and smallest possible 64-bit signed integers.
138990** These macros are designed to work correctly on both 32-bit and 64-bit
138991** compilers.
138992*/
138993#ifndef SQLITE_AMALGAMATION
138994# define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
138995# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
138996#endif
138997
138998/*
138999** If the numeric type of argument pVal is "integer", then return it
139000** converted to a 64-bit signed integer. Otherwise, return a copy of
139001** the second parameter, iDefault.
139002*/
139003static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
139004  if( pVal ){
139005    int eType = sqlite3_value_numeric_type(pVal);
139006    if( eType==SQLITE_INTEGER ){
139007      return sqlite3_value_int64(pVal);
139008    }
139009  }
139010  return iDefault;
139011}
139012
139013/*
139014** This is the xFilter interface for the virtual table.  See
139015** the virtual table xFilter method documentation for additional
139016** information.
139017**
139018** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
139019** the %_content table.
139020**
139021** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
139022** in the %_content table.
139023**
139024** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
139025** column on the left-hand side of the MATCH operator is column
139026** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
139027** side of the MATCH operator.
139028*/
139029static int fts3FilterMethod(
139030  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
139031  int idxNum,                     /* Strategy index */
139032  const char *idxStr,             /* Unused */
139033  int nVal,                       /* Number of elements in apVal */
139034  sqlite3_value **apVal           /* Arguments for the indexing scheme */
139035){
139036  int rc = SQLITE_OK;
139037  char *zSql;                     /* SQL statement used to access %_content */
139038  int eSearch;
139039  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
139040  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
139041
139042  sqlite3_value *pCons = 0;       /* The MATCH or rowid constraint, if any */
139043  sqlite3_value *pLangid = 0;     /* The "langid = ?" constraint, if any */
139044  sqlite3_value *pDocidGe = 0;    /* The "docid >= ?" constraint, if any */
139045  sqlite3_value *pDocidLe = 0;    /* The "docid <= ?" constraint, if any */
139046  int iIdx;
139047
139048  UNUSED_PARAMETER(idxStr);
139049  UNUSED_PARAMETER(nVal);
139050
139051  eSearch = (idxNum & 0x0000FFFF);
139052  assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
139053  assert( p->pSegments==0 );
139054
139055  /* Collect arguments into local variables */
139056  iIdx = 0;
139057  if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
139058  if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
139059  if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
139060  if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
139061  assert( iIdx==nVal );
139062
139063  /* In case the cursor has been used before, clear it now. */
139064  sqlite3_finalize(pCsr->pStmt);
139065  sqlite3_free(pCsr->aDoclist);
139066  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
139067  sqlite3Fts3ExprFree(pCsr->pExpr);
139068  memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
139069
139070  /* Set the lower and upper bounds on docids to return */
139071  pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
139072  pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
139073
139074  if( idxStr ){
139075    pCsr->bDesc = (idxStr[0]=='D');
139076  }else{
139077    pCsr->bDesc = p->bDescIdx;
139078  }
139079  pCsr->eSearch = (i16)eSearch;
139080
139081  if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
139082    int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
139083    const char *zQuery = (const char *)sqlite3_value_text(pCons);
139084
139085    if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
139086      return SQLITE_NOMEM;
139087    }
139088
139089    pCsr->iLangid = 0;
139090    if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
139091
139092    assert( p->base.zErrMsg==0 );
139093    rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
139094        p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
139095        &p->base.zErrMsg
139096    );
139097    if( rc!=SQLITE_OK ){
139098      return rc;
139099    }
139100
139101    rc = fts3EvalStart(pCsr);
139102    sqlite3Fts3SegmentsClose(p);
139103    if( rc!=SQLITE_OK ) return rc;
139104    pCsr->pNextId = pCsr->aDoclist;
139105    pCsr->iPrevId = 0;
139106  }
139107
139108  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
139109  ** statement loops through all rows of the %_content table. For a
139110  ** full-text query or docid lookup, the statement retrieves a single
139111  ** row by docid.
139112  */
139113  if( eSearch==FTS3_FULLSCAN_SEARCH ){
139114    if( pDocidGe || pDocidLe ){
139115      zSql = sqlite3_mprintf(
139116          "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
139117          p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
139118          (pCsr->bDesc ? "DESC" : "ASC")
139119      );
139120    }else{
139121      zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
139122          p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
139123      );
139124    }
139125    if( zSql ){
139126      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
139127      sqlite3_free(zSql);
139128    }else{
139129      rc = SQLITE_NOMEM;
139130    }
139131  }else if( eSearch==FTS3_DOCID_SEARCH ){
139132    rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
139133    if( rc==SQLITE_OK ){
139134      rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
139135    }
139136  }
139137  if( rc!=SQLITE_OK ) return rc;
139138
139139  return fts3NextMethod(pCursor);
139140}
139141
139142/*
139143** This is the xEof method of the virtual table. SQLite calls this
139144** routine to find out if it has reached the end of a result set.
139145*/
139146static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
139147  return ((Fts3Cursor *)pCursor)->isEof;
139148}
139149
139150/*
139151** This is the xRowid method. The SQLite core calls this routine to
139152** retrieve the rowid for the current row of the result set. fts3
139153** exposes %_content.docid as the rowid for the virtual table. The
139154** rowid should be written to *pRowid.
139155*/
139156static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
139157  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
139158  *pRowid = pCsr->iPrevId;
139159  return SQLITE_OK;
139160}
139161
139162/*
139163** This is the xColumn method, called by SQLite to request a value from
139164** the row that the supplied cursor currently points to.
139165**
139166** If:
139167**
139168**   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
139169**   (iCol == p->nColumn)   -> Magic column with the same name as the table.
139170**   (iCol == p->nColumn+1) -> Docid column
139171**   (iCol == p->nColumn+2) -> Langid column
139172*/
139173static int fts3ColumnMethod(
139174  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
139175  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
139176  int iCol                        /* Index of column to read value from */
139177){
139178  int rc = SQLITE_OK;             /* Return Code */
139179  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
139180  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
139181
139182  /* The column value supplied by SQLite must be in range. */
139183  assert( iCol>=0 && iCol<=p->nColumn+2 );
139184
139185  if( iCol==p->nColumn+1 ){
139186    /* This call is a request for the "docid" column. Since "docid" is an
139187    ** alias for "rowid", use the xRowid() method to obtain the value.
139188    */
139189    sqlite3_result_int64(pCtx, pCsr->iPrevId);
139190  }else if( iCol==p->nColumn ){
139191    /* The extra column whose name is the same as the table.
139192    ** Return a blob which is a pointer to the cursor.  */
139193    sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
139194  }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
139195    sqlite3_result_int64(pCtx, pCsr->iLangid);
139196  }else{
139197    /* The requested column is either a user column (one that contains
139198    ** indexed data), or the language-id column.  */
139199    rc = fts3CursorSeek(0, pCsr);
139200
139201    if( rc==SQLITE_OK ){
139202      if( iCol==p->nColumn+2 ){
139203        int iLangid = 0;
139204        if( p->zLanguageid ){
139205          iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
139206        }
139207        sqlite3_result_int(pCtx, iLangid);
139208      }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
139209        sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
139210      }
139211    }
139212  }
139213
139214  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
139215  return rc;
139216}
139217
139218/*
139219** This function is the implementation of the xUpdate callback used by
139220** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
139221** inserted, updated or deleted.
139222*/
139223static int fts3UpdateMethod(
139224  sqlite3_vtab *pVtab,            /* Virtual table handle */
139225  int nArg,                       /* Size of argument array */
139226  sqlite3_value **apVal,          /* Array of arguments */
139227  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
139228){
139229  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
139230}
139231
139232/*
139233** Implementation of xSync() method. Flush the contents of the pending-terms
139234** hash-table to the database.
139235*/
139236static int fts3SyncMethod(sqlite3_vtab *pVtab){
139237
139238  /* Following an incremental-merge operation, assuming that the input
139239  ** segments are not completely consumed (the usual case), they are updated
139240  ** in place to remove the entries that have already been merged. This
139241  ** involves updating the leaf block that contains the smallest unmerged
139242  ** entry and each block (if any) between the leaf and the root node. So
139243  ** if the height of the input segment b-trees is N, and input segments
139244  ** are merged eight at a time, updating the input segments at the end
139245  ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
139246  ** small - often between 0 and 2. So the overhead of the incremental
139247  ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
139248  ** dwarfing the actual productive work accomplished, the incremental merge
139249  ** is only attempted if it will write at least 64 leaf blocks. Hence
139250  ** nMinMerge.
139251  **
139252  ** Of course, updating the input segments also involves deleting a bunch
139253  ** of blocks from the segments table. But this is not considered overhead
139254  ** as it would also be required by a crisis-merge that used the same input
139255  ** segments.
139256  */
139257  const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
139258
139259  Fts3Table *p = (Fts3Table*)pVtab;
139260  int rc = sqlite3Fts3PendingTermsFlush(p);
139261
139262  if( rc==SQLITE_OK
139263   && p->nLeafAdd>(nMinMerge/16)
139264   && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
139265  ){
139266    int mxLevel = 0;              /* Maximum relative level value in db */
139267    int A;                        /* Incr-merge parameter A */
139268
139269    rc = sqlite3Fts3MaxLevel(p, &mxLevel);
139270    assert( rc==SQLITE_OK || mxLevel==0 );
139271    A = p->nLeafAdd * mxLevel;
139272    A += (A/2);
139273    if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
139274  }
139275  sqlite3Fts3SegmentsClose(p);
139276  return rc;
139277}
139278
139279/*
139280** If it is currently unknown whether or not the FTS table has an %_stat
139281** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
139282** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
139283** if an error occurs.
139284*/
139285static int fts3SetHasStat(Fts3Table *p){
139286  int rc = SQLITE_OK;
139287  if( p->bHasStat==2 ){
139288    const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
139289    char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
139290    if( zSql ){
139291      sqlite3_stmt *pStmt = 0;
139292      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
139293      if( rc==SQLITE_OK ){
139294        int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
139295        rc = sqlite3_finalize(pStmt);
139296        if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
139297      }
139298      sqlite3_free(zSql);
139299    }else{
139300      rc = SQLITE_NOMEM;
139301    }
139302  }
139303  return rc;
139304}
139305
139306/*
139307** Implementation of xBegin() method.
139308*/
139309static int fts3BeginMethod(sqlite3_vtab *pVtab){
139310  Fts3Table *p = (Fts3Table*)pVtab;
139311  UNUSED_PARAMETER(pVtab);
139312  assert( p->pSegments==0 );
139313  assert( p->nPendingData==0 );
139314  assert( p->inTransaction!=1 );
139315  TESTONLY( p->inTransaction = 1 );
139316  TESTONLY( p->mxSavepoint = -1; );
139317  p->nLeafAdd = 0;
139318  return fts3SetHasStat(p);
139319}
139320
139321/*
139322** Implementation of xCommit() method. This is a no-op. The contents of
139323** the pending-terms hash-table have already been flushed into the database
139324** by fts3SyncMethod().
139325*/
139326static int fts3CommitMethod(sqlite3_vtab *pVtab){
139327  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
139328  UNUSED_PARAMETER(pVtab);
139329  assert( p->nPendingData==0 );
139330  assert( p->inTransaction!=0 );
139331  assert( p->pSegments==0 );
139332  TESTONLY( p->inTransaction = 0 );
139333  TESTONLY( p->mxSavepoint = -1; );
139334  return SQLITE_OK;
139335}
139336
139337/*
139338** Implementation of xRollback(). Discard the contents of the pending-terms
139339** hash-table. Any changes made to the database are reverted by SQLite.
139340*/
139341static int fts3RollbackMethod(sqlite3_vtab *pVtab){
139342  Fts3Table *p = (Fts3Table*)pVtab;
139343  sqlite3Fts3PendingTermsClear(p);
139344  assert( p->inTransaction!=0 );
139345  TESTONLY( p->inTransaction = 0 );
139346  TESTONLY( p->mxSavepoint = -1; );
139347  return SQLITE_OK;
139348}
139349
139350/*
139351** When called, *ppPoslist must point to the byte immediately following the
139352** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
139353** moves *ppPoslist so that it instead points to the first byte of the
139354** same position list.
139355*/
139356static void fts3ReversePoslist(char *pStart, char **ppPoslist){
139357  char *p = &(*ppPoslist)[-2];
139358  char c = 0;
139359
139360  /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
139361  while( p>pStart && (c=*p--)==0 );
139362
139363  /* Search backwards for a varint with value zero (the end of the previous
139364  ** poslist). This is an 0x00 byte preceded by some byte that does not
139365  ** have the 0x80 bit set.  */
139366  while( p>pStart && (*p & 0x80) | c ){
139367    c = *p--;
139368  }
139369  assert( p==pStart || c==0 );
139370
139371  /* At this point p points to that preceding byte without the 0x80 bit
139372  ** set. So to find the start of the poslist, skip forward 2 bytes then
139373  ** over a varint.
139374  **
139375  ** Normally. The other case is that p==pStart and the poslist to return
139376  ** is the first in the doclist. In this case do not skip forward 2 bytes.
139377  ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
139378  ** is required for cases where the first byte of a doclist and the
139379  ** doclist is empty. For example, if the first docid is 10, a doclist
139380  ** that begins with:
139381  **
139382  **   0x0A 0x00 <next docid delta varint>
139383  */
139384  if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
139385  while( *p++&0x80 );
139386  *ppPoslist = p;
139387}
139388
139389/*
139390** Helper function used by the implementation of the overloaded snippet(),
139391** offsets() and optimize() SQL functions.
139392**
139393** If the value passed as the third argument is a blob of size
139394** sizeof(Fts3Cursor*), then the blob contents are copied to the
139395** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
139396** message is written to context pContext and SQLITE_ERROR returned. The
139397** string passed via zFunc is used as part of the error message.
139398*/
139399static int fts3FunctionArg(
139400  sqlite3_context *pContext,      /* SQL function call context */
139401  const char *zFunc,              /* Function name */
139402  sqlite3_value *pVal,            /* argv[0] passed to function */
139403  Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
139404){
139405  Fts3Cursor *pRet;
139406  if( sqlite3_value_type(pVal)!=SQLITE_BLOB
139407   || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
139408  ){
139409    char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
139410    sqlite3_result_error(pContext, zErr, -1);
139411    sqlite3_free(zErr);
139412    return SQLITE_ERROR;
139413  }
139414  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
139415  *ppCsr = pRet;
139416  return SQLITE_OK;
139417}
139418
139419/*
139420** Implementation of the snippet() function for FTS3
139421*/
139422static void fts3SnippetFunc(
139423  sqlite3_context *pContext,      /* SQLite function call context */
139424  int nVal,                       /* Size of apVal[] array */
139425  sqlite3_value **apVal           /* Array of arguments */
139426){
139427  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
139428  const char *zStart = "<b>";
139429  const char *zEnd = "</b>";
139430  const char *zEllipsis = "<b>...</b>";
139431  int iCol = -1;
139432  int nToken = 15;                /* Default number of tokens in snippet */
139433
139434  /* There must be at least one argument passed to this function (otherwise
139435  ** the non-overloaded version would have been called instead of this one).
139436  */
139437  assert( nVal>=1 );
139438
139439  if( nVal>6 ){
139440    sqlite3_result_error(pContext,
139441        "wrong number of arguments to function snippet()", -1);
139442    return;
139443  }
139444  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
139445
139446  switch( nVal ){
139447    case 6: nToken = sqlite3_value_int(apVal[5]);
139448    case 5: iCol = sqlite3_value_int(apVal[4]);
139449    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
139450    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
139451    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
139452  }
139453  if( !zEllipsis || !zEnd || !zStart ){
139454    sqlite3_result_error_nomem(pContext);
139455  }else if( nToken==0 ){
139456    sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
139457  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
139458    sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
139459  }
139460}
139461
139462/*
139463** Implementation of the offsets() function for FTS3
139464*/
139465static void fts3OffsetsFunc(
139466  sqlite3_context *pContext,      /* SQLite function call context */
139467  int nVal,                       /* Size of argument array */
139468  sqlite3_value **apVal           /* Array of arguments */
139469){
139470  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
139471
139472  UNUSED_PARAMETER(nVal);
139473
139474  assert( nVal==1 );
139475  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
139476  assert( pCsr );
139477  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
139478    sqlite3Fts3Offsets(pContext, pCsr);
139479  }
139480}
139481
139482/*
139483** Implementation of the special optimize() function for FTS3. This
139484** function merges all segments in the database to a single segment.
139485** Example usage is:
139486**
139487**   SELECT optimize(t) FROM t LIMIT 1;
139488**
139489** where 't' is the name of an FTS3 table.
139490*/
139491static void fts3OptimizeFunc(
139492  sqlite3_context *pContext,      /* SQLite function call context */
139493  int nVal,                       /* Size of argument array */
139494  sqlite3_value **apVal           /* Array of arguments */
139495){
139496  int rc;                         /* Return code */
139497  Fts3Table *p;                   /* Virtual table handle */
139498  Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
139499
139500  UNUSED_PARAMETER(nVal);
139501
139502  assert( nVal==1 );
139503  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
139504  p = (Fts3Table *)pCursor->base.pVtab;
139505  assert( p );
139506
139507  rc = sqlite3Fts3Optimize(p);
139508
139509  switch( rc ){
139510    case SQLITE_OK:
139511      sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
139512      break;
139513    case SQLITE_DONE:
139514      sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
139515      break;
139516    default:
139517      sqlite3_result_error_code(pContext, rc);
139518      break;
139519  }
139520}
139521
139522/*
139523** Implementation of the matchinfo() function for FTS3
139524*/
139525static void fts3MatchinfoFunc(
139526  sqlite3_context *pContext,      /* SQLite function call context */
139527  int nVal,                       /* Size of argument array */
139528  sqlite3_value **apVal           /* Array of arguments */
139529){
139530  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
139531  assert( nVal==1 || nVal==2 );
139532  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
139533    const char *zArg = 0;
139534    if( nVal>1 ){
139535      zArg = (const char *)sqlite3_value_text(apVal[1]);
139536    }
139537    sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
139538  }
139539}
139540
139541/*
139542** This routine implements the xFindFunction method for the FTS3
139543** virtual table.
139544*/
139545static int fts3FindFunctionMethod(
139546  sqlite3_vtab *pVtab,            /* Virtual table handle */
139547  int nArg,                       /* Number of SQL function arguments */
139548  const char *zName,              /* Name of SQL function */
139549  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
139550  void **ppArg                    /* Unused */
139551){
139552  struct Overloaded {
139553    const char *zName;
139554    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
139555  } aOverload[] = {
139556    { "snippet", fts3SnippetFunc },
139557    { "offsets", fts3OffsetsFunc },
139558    { "optimize", fts3OptimizeFunc },
139559    { "matchinfo", fts3MatchinfoFunc },
139560  };
139561  int i;                          /* Iterator variable */
139562
139563  UNUSED_PARAMETER(pVtab);
139564  UNUSED_PARAMETER(nArg);
139565  UNUSED_PARAMETER(ppArg);
139566
139567  for(i=0; i<SizeofArray(aOverload); i++){
139568    if( strcmp(zName, aOverload[i].zName)==0 ){
139569      *pxFunc = aOverload[i].xFunc;
139570      return 1;
139571    }
139572  }
139573
139574  /* No function of the specified name was found. Return 0. */
139575  return 0;
139576}
139577
139578/*
139579** Implementation of FTS3 xRename method. Rename an fts3 table.
139580*/
139581static int fts3RenameMethod(
139582  sqlite3_vtab *pVtab,            /* Virtual table handle */
139583  const char *zName               /* New name of table */
139584){
139585  Fts3Table *p = (Fts3Table *)pVtab;
139586  sqlite3 *db = p->db;            /* Database connection */
139587  int rc;                         /* Return Code */
139588
139589  /* At this point it must be known if the %_stat table exists or not.
139590  ** So bHasStat may not be 2.  */
139591  rc = fts3SetHasStat(p);
139592
139593  /* As it happens, the pending terms table is always empty here. This is
139594  ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
139595  ** always opens a savepoint transaction. And the xSavepoint() method
139596  ** flushes the pending terms table. But leave the (no-op) call to
139597  ** PendingTermsFlush() in in case that changes.
139598  */
139599  assert( p->nPendingData==0 );
139600  if( rc==SQLITE_OK ){
139601    rc = sqlite3Fts3PendingTermsFlush(p);
139602  }
139603
139604  if( p->zContentTbl==0 ){
139605    fts3DbExec(&rc, db,
139606      "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
139607      p->zDb, p->zName, zName
139608    );
139609  }
139610
139611  if( p->bHasDocsize ){
139612    fts3DbExec(&rc, db,
139613      "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
139614      p->zDb, p->zName, zName
139615    );
139616  }
139617  if( p->bHasStat ){
139618    fts3DbExec(&rc, db,
139619      "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
139620      p->zDb, p->zName, zName
139621    );
139622  }
139623  fts3DbExec(&rc, db,
139624    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
139625    p->zDb, p->zName, zName
139626  );
139627  fts3DbExec(&rc, db,
139628    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
139629    p->zDb, p->zName, zName
139630  );
139631  return rc;
139632}
139633
139634/*
139635** The xSavepoint() method.
139636**
139637** Flush the contents of the pending-terms table to disk.
139638*/
139639static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
139640  int rc = SQLITE_OK;
139641  UNUSED_PARAMETER(iSavepoint);
139642  assert( ((Fts3Table *)pVtab)->inTransaction );
139643  assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
139644  TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
139645  if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
139646    rc = fts3SyncMethod(pVtab);
139647  }
139648  return rc;
139649}
139650
139651/*
139652** The xRelease() method.
139653**
139654** This is a no-op.
139655*/
139656static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
139657  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
139658  UNUSED_PARAMETER(iSavepoint);
139659  UNUSED_PARAMETER(pVtab);
139660  assert( p->inTransaction );
139661  assert( p->mxSavepoint >= iSavepoint );
139662  TESTONLY( p->mxSavepoint = iSavepoint-1 );
139663  return SQLITE_OK;
139664}
139665
139666/*
139667** The xRollbackTo() method.
139668**
139669** Discard the contents of the pending terms table.
139670*/
139671static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
139672  Fts3Table *p = (Fts3Table*)pVtab;
139673  UNUSED_PARAMETER(iSavepoint);
139674  assert( p->inTransaction );
139675  assert( p->mxSavepoint >= iSavepoint );
139676  TESTONLY( p->mxSavepoint = iSavepoint );
139677  sqlite3Fts3PendingTermsClear(p);
139678  return SQLITE_OK;
139679}
139680
139681static const sqlite3_module fts3Module = {
139682  /* iVersion      */ 2,
139683  /* xCreate       */ fts3CreateMethod,
139684  /* xConnect      */ fts3ConnectMethod,
139685  /* xBestIndex    */ fts3BestIndexMethod,
139686  /* xDisconnect   */ fts3DisconnectMethod,
139687  /* xDestroy      */ fts3DestroyMethod,
139688  /* xOpen         */ fts3OpenMethod,
139689  /* xClose        */ fts3CloseMethod,
139690  /* xFilter       */ fts3FilterMethod,
139691  /* xNext         */ fts3NextMethod,
139692  /* xEof          */ fts3EofMethod,
139693  /* xColumn       */ fts3ColumnMethod,
139694  /* xRowid        */ fts3RowidMethod,
139695  /* xUpdate       */ fts3UpdateMethod,
139696  /* xBegin        */ fts3BeginMethod,
139697  /* xSync         */ fts3SyncMethod,
139698  /* xCommit       */ fts3CommitMethod,
139699  /* xRollback     */ fts3RollbackMethod,
139700  /* xFindFunction */ fts3FindFunctionMethod,
139701  /* xRename */       fts3RenameMethod,
139702  /* xSavepoint    */ fts3SavepointMethod,
139703  /* xRelease      */ fts3ReleaseMethod,
139704  /* xRollbackTo   */ fts3RollbackToMethod,
139705};
139706
139707/*
139708** This function is registered as the module destructor (called when an
139709** FTS3 enabled database connection is closed). It frees the memory
139710** allocated for the tokenizer hash table.
139711*/
139712static void hashDestroy(void *p){
139713  Fts3Hash *pHash = (Fts3Hash *)p;
139714  sqlite3Fts3HashClear(pHash);
139715  sqlite3_free(pHash);
139716}
139717
139718/*
139719** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
139720** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
139721** respectively. The following three forward declarations are for functions
139722** declared in these files used to retrieve the respective implementations.
139723**
139724** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
139725** to by the argument to point to the "simple" tokenizer implementation.
139726** And so on.
139727*/
139728SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
139729SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
139730#ifndef SQLITE_DISABLE_FTS3_UNICODE
139731SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
139732#endif
139733#ifdef SQLITE_ENABLE_ICU
139734SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
139735#endif
139736
139737/*
139738** Initialize the fts3 extension. If this extension is built as part
139739** of the sqlite library, then this function is called directly by
139740** SQLite. If fts3 is built as a dynamically loadable extension, this
139741** function is called by the sqlite3_extension_init() entry point.
139742*/
139743SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
139744  int rc = SQLITE_OK;
139745  Fts3Hash *pHash = 0;
139746  const sqlite3_tokenizer_module *pSimple = 0;
139747  const sqlite3_tokenizer_module *pPorter = 0;
139748#ifndef SQLITE_DISABLE_FTS3_UNICODE
139749  const sqlite3_tokenizer_module *pUnicode = 0;
139750#endif
139751
139752#ifdef SQLITE_ENABLE_ICU
139753  const sqlite3_tokenizer_module *pIcu = 0;
139754  sqlite3Fts3IcuTokenizerModule(&pIcu);
139755#endif
139756
139757#ifndef SQLITE_DISABLE_FTS3_UNICODE
139758  sqlite3Fts3UnicodeTokenizer(&pUnicode);
139759#endif
139760
139761#ifdef SQLITE_TEST
139762  rc = sqlite3Fts3InitTerm(db);
139763  if( rc!=SQLITE_OK ) return rc;
139764#endif
139765
139766  rc = sqlite3Fts3InitAux(db);
139767  if( rc!=SQLITE_OK ) return rc;
139768
139769  sqlite3Fts3SimpleTokenizerModule(&pSimple);
139770  sqlite3Fts3PorterTokenizerModule(&pPorter);
139771
139772  /* Allocate and initialize the hash-table used to store tokenizers. */
139773  pHash = sqlite3_malloc(sizeof(Fts3Hash));
139774  if( !pHash ){
139775    rc = SQLITE_NOMEM;
139776  }else{
139777    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
139778  }
139779
139780  /* Load the built-in tokenizers into the hash table */
139781  if( rc==SQLITE_OK ){
139782    if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
139783     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
139784
139785#ifndef SQLITE_DISABLE_FTS3_UNICODE
139786     || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
139787#endif
139788#ifdef SQLITE_ENABLE_ICU
139789     || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
139790#endif
139791    ){
139792      rc = SQLITE_NOMEM;
139793    }
139794  }
139795
139796#ifdef SQLITE_TEST
139797  if( rc==SQLITE_OK ){
139798    rc = sqlite3Fts3ExprInitTestInterface(db);
139799  }
139800#endif
139801
139802  /* Create the virtual table wrapper around the hash-table and overload
139803  ** the two scalar functions. If this is successful, register the
139804  ** module with sqlite.
139805  */
139806  if( SQLITE_OK==rc
139807#ifndef ANDROID    /* fts3_tokenizer disabled for security reasons */
139808   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
139809#endif
139810   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
139811   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
139812   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
139813   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
139814   && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
139815  ){
139816#ifdef SQLITE_ENABLE_FTS3_BACKWARDS
139817    rc = sqlite3_create_module_v2(
139818        db, "fts1", &fts3Module, (void *)pHash, 0
139819        );
139820    if(rc) return rc;
139821    rc = sqlite3_create_module_v2(
139822        db, "fts2", &fts3Module, (void *)pHash, 0
139823        );
139824    if(rc) return rc;
139825#endif
139826    rc = sqlite3_create_module_v2(
139827        db, "fts3", &fts3Module, (void *)pHash, hashDestroy
139828        );
139829    if( rc==SQLITE_OK ){
139830      rc = sqlite3_create_module_v2(
139831          db, "fts4", &fts3Module, (void *)pHash, 0
139832      );
139833    }
139834    if( rc==SQLITE_OK ){
139835      rc = sqlite3Fts3InitTok(db, (void *)pHash);
139836    }
139837    return rc;
139838  }
139839
139840
139841  /* An error has occurred. Delete the hash table and return the error code. */
139842  assert( rc!=SQLITE_OK );
139843  if( pHash ){
139844    sqlite3Fts3HashClear(pHash);
139845    sqlite3_free(pHash);
139846  }
139847  return rc;
139848}
139849
139850/*
139851** Allocate an Fts3MultiSegReader for each token in the expression headed
139852** by pExpr.
139853**
139854** An Fts3SegReader object is a cursor that can seek or scan a range of
139855** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
139856** Fts3SegReader objects internally to provide an interface to seek or scan
139857** within the union of all segments of a b-tree. Hence the name.
139858**
139859** If the allocated Fts3MultiSegReader just seeks to a single entry in a
139860** segment b-tree (if the term is not a prefix or it is a prefix for which
139861** there exists prefix b-tree of the right length) then it may be traversed
139862** and merged incrementally. Otherwise, it has to be merged into an in-memory
139863** doclist and then traversed.
139864*/
139865static void fts3EvalAllocateReaders(
139866  Fts3Cursor *pCsr,               /* FTS cursor handle */
139867  Fts3Expr *pExpr,                /* Allocate readers for this expression */
139868  int *pnToken,                   /* OUT: Total number of tokens in phrase. */
139869  int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
139870  int *pRc                        /* IN/OUT: Error code */
139871){
139872  if( pExpr && SQLITE_OK==*pRc ){
139873    if( pExpr->eType==FTSQUERY_PHRASE ){
139874      int i;
139875      int nToken = pExpr->pPhrase->nToken;
139876      *pnToken += nToken;
139877      for(i=0; i<nToken; i++){
139878        Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
139879        int rc = fts3TermSegReaderCursor(pCsr,
139880            pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
139881        );
139882        if( rc!=SQLITE_OK ){
139883          *pRc = rc;
139884          return;
139885        }
139886      }
139887      assert( pExpr->pPhrase->iDoclistToken==0 );
139888      pExpr->pPhrase->iDoclistToken = -1;
139889    }else{
139890      *pnOr += (pExpr->eType==FTSQUERY_OR);
139891      fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
139892      fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
139893    }
139894  }
139895}
139896
139897/*
139898** Arguments pList/nList contain the doclist for token iToken of phrase p.
139899** It is merged into the main doclist stored in p->doclist.aAll/nAll.
139900**
139901** This function assumes that pList points to a buffer allocated using
139902** sqlite3_malloc(). This function takes responsibility for eventually
139903** freeing the buffer.
139904**
139905** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
139906*/
139907static int fts3EvalPhraseMergeToken(
139908  Fts3Table *pTab,                /* FTS Table pointer */
139909  Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
139910  int iToken,                     /* Token pList/nList corresponds to */
139911  char *pList,                    /* Pointer to doclist */
139912  int nList                       /* Number of bytes in pList */
139913){
139914  int rc = SQLITE_OK;
139915  assert( iToken!=p->iDoclistToken );
139916
139917  if( pList==0 ){
139918    sqlite3_free(p->doclist.aAll);
139919    p->doclist.aAll = 0;
139920    p->doclist.nAll = 0;
139921  }
139922
139923  else if( p->iDoclistToken<0 ){
139924    p->doclist.aAll = pList;
139925    p->doclist.nAll = nList;
139926  }
139927
139928  else if( p->doclist.aAll==0 ){
139929    sqlite3_free(pList);
139930  }
139931
139932  else {
139933    char *pLeft;
139934    char *pRight;
139935    int nLeft;
139936    int nRight;
139937    int nDiff;
139938
139939    if( p->iDoclistToken<iToken ){
139940      pLeft = p->doclist.aAll;
139941      nLeft = p->doclist.nAll;
139942      pRight = pList;
139943      nRight = nList;
139944      nDiff = iToken - p->iDoclistToken;
139945    }else{
139946      pRight = p->doclist.aAll;
139947      nRight = p->doclist.nAll;
139948      pLeft = pList;
139949      nLeft = nList;
139950      nDiff = p->iDoclistToken - iToken;
139951    }
139952
139953    rc = fts3DoclistPhraseMerge(
139954        pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
139955    );
139956    sqlite3_free(pLeft);
139957    p->doclist.aAll = pRight;
139958    p->doclist.nAll = nRight;
139959  }
139960
139961  if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
139962  return rc;
139963}
139964
139965/*
139966** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
139967** does not take deferred tokens into account.
139968**
139969** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
139970*/
139971static int fts3EvalPhraseLoad(
139972  Fts3Cursor *pCsr,               /* FTS Cursor handle */
139973  Fts3Phrase *p                   /* Phrase object */
139974){
139975  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
139976  int iToken;
139977  int rc = SQLITE_OK;
139978
139979  for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
139980    Fts3PhraseToken *pToken = &p->aToken[iToken];
139981    assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
139982
139983    if( pToken->pSegcsr ){
139984      int nThis = 0;
139985      char *pThis = 0;
139986      rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
139987      if( rc==SQLITE_OK ){
139988        rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
139989      }
139990    }
139991    assert( pToken->pSegcsr==0 );
139992  }
139993
139994  return rc;
139995}
139996
139997/*
139998** This function is called on each phrase after the position lists for
139999** any deferred tokens have been loaded into memory. It updates the phrases
140000** current position list to include only those positions that are really
140001** instances of the phrase (after considering deferred tokens). If this
140002** means that the phrase does not appear in the current row, doclist.pList
140003** and doclist.nList are both zeroed.
140004**
140005** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
140006*/
140007static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
140008  int iToken;                     /* Used to iterate through phrase tokens */
140009  char *aPoslist = 0;             /* Position list for deferred tokens */
140010  int nPoslist = 0;               /* Number of bytes in aPoslist */
140011  int iPrev = -1;                 /* Token number of previous deferred token */
140012
140013  assert( pPhrase->doclist.bFreeList==0 );
140014
140015  for(iToken=0; iToken<pPhrase->nToken; iToken++){
140016    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
140017    Fts3DeferredToken *pDeferred = pToken->pDeferred;
140018
140019    if( pDeferred ){
140020      char *pList;
140021      int nList;
140022      int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
140023      if( rc!=SQLITE_OK ) return rc;
140024
140025      if( pList==0 ){
140026        sqlite3_free(aPoslist);
140027        pPhrase->doclist.pList = 0;
140028        pPhrase->doclist.nList = 0;
140029        return SQLITE_OK;
140030
140031      }else if( aPoslist==0 ){
140032        aPoslist = pList;
140033        nPoslist = nList;
140034
140035      }else{
140036        char *aOut = pList;
140037        char *p1 = aPoslist;
140038        char *p2 = aOut;
140039
140040        assert( iPrev>=0 );
140041        fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
140042        sqlite3_free(aPoslist);
140043        aPoslist = pList;
140044        nPoslist = (int)(aOut - aPoslist);
140045        if( nPoslist==0 ){
140046          sqlite3_free(aPoslist);
140047          pPhrase->doclist.pList = 0;
140048          pPhrase->doclist.nList = 0;
140049          return SQLITE_OK;
140050        }
140051      }
140052      iPrev = iToken;
140053    }
140054  }
140055
140056  if( iPrev>=0 ){
140057    int nMaxUndeferred = pPhrase->iDoclistToken;
140058    if( nMaxUndeferred<0 ){
140059      pPhrase->doclist.pList = aPoslist;
140060      pPhrase->doclist.nList = nPoslist;
140061      pPhrase->doclist.iDocid = pCsr->iPrevId;
140062      pPhrase->doclist.bFreeList = 1;
140063    }else{
140064      int nDistance;
140065      char *p1;
140066      char *p2;
140067      char *aOut;
140068
140069      if( nMaxUndeferred>iPrev ){
140070        p1 = aPoslist;
140071        p2 = pPhrase->doclist.pList;
140072        nDistance = nMaxUndeferred - iPrev;
140073      }else{
140074        p1 = pPhrase->doclist.pList;
140075        p2 = aPoslist;
140076        nDistance = iPrev - nMaxUndeferred;
140077      }
140078
140079      aOut = (char *)sqlite3_malloc(nPoslist+8);
140080      if( !aOut ){
140081        sqlite3_free(aPoslist);
140082        return SQLITE_NOMEM;
140083      }
140084
140085      pPhrase->doclist.pList = aOut;
140086      if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
140087        pPhrase->doclist.bFreeList = 1;
140088        pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
140089      }else{
140090        sqlite3_free(aOut);
140091        pPhrase->doclist.pList = 0;
140092        pPhrase->doclist.nList = 0;
140093      }
140094      sqlite3_free(aPoslist);
140095    }
140096  }
140097
140098  return SQLITE_OK;
140099}
140100
140101/*
140102** Maximum number of tokens a phrase may have to be considered for the
140103** incremental doclists strategy.
140104*/
140105#define MAX_INCR_PHRASE_TOKENS 4
140106
140107/*
140108** This function is called for each Fts3Phrase in a full-text query
140109** expression to initialize the mechanism for returning rows. Once this
140110** function has been called successfully on an Fts3Phrase, it may be
140111** used with fts3EvalPhraseNext() to iterate through the matching docids.
140112**
140113** If parameter bOptOk is true, then the phrase may (or may not) use the
140114** incremental loading strategy. Otherwise, the entire doclist is loaded into
140115** memory within this call.
140116**
140117** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
140118*/
140119static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
140120  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
140121  int rc = SQLITE_OK;             /* Error code */
140122  int i;
140123
140124  /* Determine if doclists may be loaded from disk incrementally. This is
140125  ** possible if the bOptOk argument is true, the FTS doclists will be
140126  ** scanned in forward order, and the phrase consists of
140127  ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
140128  ** tokens or prefix tokens that cannot use a prefix-index.  */
140129  int bHaveIncr = 0;
140130  int bIncrOk = (bOptOk
140131   && pCsr->bDesc==pTab->bDescIdx
140132   && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
140133#ifdef SQLITE_TEST
140134   && pTab->bNoIncrDoclist==0
140135#endif
140136  );
140137  for(i=0; bIncrOk==1 && i<p->nToken; i++){
140138    Fts3PhraseToken *pToken = &p->aToken[i];
140139    if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
140140      bIncrOk = 0;
140141    }
140142    if( pToken->pSegcsr ) bHaveIncr = 1;
140143  }
140144
140145  if( bIncrOk && bHaveIncr ){
140146    /* Use the incremental approach. */
140147    int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
140148    for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
140149      Fts3PhraseToken *pToken = &p->aToken[i];
140150      Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
140151      if( pSegcsr ){
140152        rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
140153      }
140154    }
140155    p->bIncr = 1;
140156  }else{
140157    /* Load the full doclist for the phrase into memory. */
140158    rc = fts3EvalPhraseLoad(pCsr, p);
140159    p->bIncr = 0;
140160  }
140161
140162  assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
140163  return rc;
140164}
140165
140166/*
140167** This function is used to iterate backwards (from the end to start)
140168** through doclists. It is used by this module to iterate through phrase
140169** doclists in reverse and by the fts3_write.c module to iterate through
140170** pending-terms lists when writing to databases with "order=desc".
140171**
140172** The doclist may be sorted in ascending (parameter bDescIdx==0) or
140173** descending (parameter bDescIdx==1) order of docid. Regardless, this
140174** function iterates from the end of the doclist to the beginning.
140175*/
140176SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
140177  int bDescIdx,                   /* True if the doclist is desc */
140178  char *aDoclist,                 /* Pointer to entire doclist */
140179  int nDoclist,                   /* Length of aDoclist in bytes */
140180  char **ppIter,                  /* IN/OUT: Iterator pointer */
140181  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
140182  int *pnList,                    /* OUT: List length pointer */
140183  u8 *pbEof                       /* OUT: End-of-file flag */
140184){
140185  char *p = *ppIter;
140186
140187  assert( nDoclist>0 );
140188  assert( *pbEof==0 );
140189  assert( p || *piDocid==0 );
140190  assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
140191
140192  if( p==0 ){
140193    sqlite3_int64 iDocid = 0;
140194    char *pNext = 0;
140195    char *pDocid = aDoclist;
140196    char *pEnd = &aDoclist[nDoclist];
140197    int iMul = 1;
140198
140199    while( pDocid<pEnd ){
140200      sqlite3_int64 iDelta;
140201      pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
140202      iDocid += (iMul * iDelta);
140203      pNext = pDocid;
140204      fts3PoslistCopy(0, &pDocid);
140205      while( pDocid<pEnd && *pDocid==0 ) pDocid++;
140206      iMul = (bDescIdx ? -1 : 1);
140207    }
140208
140209    *pnList = (int)(pEnd - pNext);
140210    *ppIter = pNext;
140211    *piDocid = iDocid;
140212  }else{
140213    int iMul = (bDescIdx ? -1 : 1);
140214    sqlite3_int64 iDelta;
140215    fts3GetReverseVarint(&p, aDoclist, &iDelta);
140216    *piDocid -= (iMul * iDelta);
140217
140218    if( p==aDoclist ){
140219      *pbEof = 1;
140220    }else{
140221      char *pSave = p;
140222      fts3ReversePoslist(aDoclist, &p);
140223      *pnList = (int)(pSave - p);
140224    }
140225    *ppIter = p;
140226  }
140227}
140228
140229/*
140230** Iterate forwards through a doclist.
140231*/
140232SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
140233  int bDescIdx,                   /* True if the doclist is desc */
140234  char *aDoclist,                 /* Pointer to entire doclist */
140235  int nDoclist,                   /* Length of aDoclist in bytes */
140236  char **ppIter,                  /* IN/OUT: Iterator pointer */
140237  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
140238  u8 *pbEof                       /* OUT: End-of-file flag */
140239){
140240  char *p = *ppIter;
140241
140242  assert( nDoclist>0 );
140243  assert( *pbEof==0 );
140244  assert( p || *piDocid==0 );
140245  assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
140246
140247  if( p==0 ){
140248    p = aDoclist;
140249    p += sqlite3Fts3GetVarint(p, piDocid);
140250  }else{
140251    fts3PoslistCopy(0, &p);
140252    while( p<&aDoclist[nDoclist] && *p==0 ) p++;
140253    if( p>=&aDoclist[nDoclist] ){
140254      *pbEof = 1;
140255    }else{
140256      sqlite3_int64 iVar;
140257      p += sqlite3Fts3GetVarint(p, &iVar);
140258      *piDocid += ((bDescIdx ? -1 : 1) * iVar);
140259    }
140260  }
140261
140262  *ppIter = p;
140263}
140264
140265/*
140266** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
140267** to true if EOF is reached.
140268*/
140269static void fts3EvalDlPhraseNext(
140270  Fts3Table *pTab,
140271  Fts3Doclist *pDL,
140272  u8 *pbEof
140273){
140274  char *pIter;                            /* Used to iterate through aAll */
140275  char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
140276
140277  if( pDL->pNextDocid ){
140278    pIter = pDL->pNextDocid;
140279  }else{
140280    pIter = pDL->aAll;
140281  }
140282
140283  if( pIter>=pEnd ){
140284    /* We have already reached the end of this doclist. EOF. */
140285    *pbEof = 1;
140286  }else{
140287    sqlite3_int64 iDelta;
140288    pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
140289    if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
140290      pDL->iDocid += iDelta;
140291    }else{
140292      pDL->iDocid -= iDelta;
140293    }
140294    pDL->pList = pIter;
140295    fts3PoslistCopy(0, &pIter);
140296    pDL->nList = (int)(pIter - pDL->pList);
140297
140298    /* pIter now points just past the 0x00 that terminates the position-
140299    ** list for document pDL->iDocid. However, if this position-list was
140300    ** edited in place by fts3EvalNearTrim(), then pIter may not actually
140301    ** point to the start of the next docid value. The following line deals
140302    ** with this case by advancing pIter past the zero-padding added by
140303    ** fts3EvalNearTrim().  */
140304    while( pIter<pEnd && *pIter==0 ) pIter++;
140305
140306    pDL->pNextDocid = pIter;
140307    assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
140308    *pbEof = 0;
140309  }
140310}
140311
140312/*
140313** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
140314*/
140315typedef struct TokenDoclist TokenDoclist;
140316struct TokenDoclist {
140317  int bIgnore;
140318  sqlite3_int64 iDocid;
140319  char *pList;
140320  int nList;
140321};
140322
140323/*
140324** Token pToken is an incrementally loaded token that is part of a
140325** multi-token phrase. Advance it to the next matching document in the
140326** database and populate output variable *p with the details of the new
140327** entry. Or, if the iterator has reached EOF, set *pbEof to true.
140328**
140329** If an error occurs, return an SQLite error code. Otherwise, return
140330** SQLITE_OK.
140331*/
140332static int incrPhraseTokenNext(
140333  Fts3Table *pTab,                /* Virtual table handle */
140334  Fts3Phrase *pPhrase,            /* Phrase to advance token of */
140335  int iToken,                     /* Specific token to advance */
140336  TokenDoclist *p,                /* OUT: Docid and doclist for new entry */
140337  u8 *pbEof                       /* OUT: True if iterator is at EOF */
140338){
140339  int rc = SQLITE_OK;
140340
140341  if( pPhrase->iDoclistToken==iToken ){
140342    assert( p->bIgnore==0 );
140343    assert( pPhrase->aToken[iToken].pSegcsr==0 );
140344    fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
140345    p->pList = pPhrase->doclist.pList;
140346    p->nList = pPhrase->doclist.nList;
140347    p->iDocid = pPhrase->doclist.iDocid;
140348  }else{
140349    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
140350    assert( pToken->pDeferred==0 );
140351    assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
140352    if( pToken->pSegcsr ){
140353      assert( p->bIgnore==0 );
140354      rc = sqlite3Fts3MsrIncrNext(
140355          pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
140356      );
140357      if( p->pList==0 ) *pbEof = 1;
140358    }else{
140359      p->bIgnore = 1;
140360    }
140361  }
140362
140363  return rc;
140364}
140365
140366
140367/*
140368** The phrase iterator passed as the second argument:
140369**
140370**   * features at least one token that uses an incremental doclist, and
140371**
140372**   * does not contain any deferred tokens.
140373**
140374** Advance it to the next matching documnent in the database and populate
140375** the Fts3Doclist.pList and nList fields.
140376**
140377** If there is no "next" entry and no error occurs, then *pbEof is set to
140378** 1 before returning. Otherwise, if no error occurs and the iterator is
140379** successfully advanced, *pbEof is set to 0.
140380**
140381** If an error occurs, return an SQLite error code. Otherwise, return
140382** SQLITE_OK.
140383*/
140384static int fts3EvalIncrPhraseNext(
140385  Fts3Cursor *pCsr,               /* FTS Cursor handle */
140386  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
140387  u8 *pbEof                       /* OUT: Set to 1 if EOF */
140388){
140389  int rc = SQLITE_OK;
140390  Fts3Doclist *pDL = &p->doclist;
140391  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
140392  u8 bEof = 0;
140393
140394  /* This is only called if it is guaranteed that the phrase has at least
140395  ** one incremental token. In which case the bIncr flag is set. */
140396  assert( p->bIncr==1 );
140397
140398  if( p->nToken==1 && p->bIncr ){
140399    rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
140400        &pDL->iDocid, &pDL->pList, &pDL->nList
140401    );
140402    if( pDL->pList==0 ) bEof = 1;
140403  }else{
140404    int bDescDoclist = pCsr->bDesc;
140405    struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
140406
140407    memset(a, 0, sizeof(a));
140408    assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
140409    assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
140410
140411    while( bEof==0 ){
140412      int bMaxSet = 0;
140413      sqlite3_int64 iMax = 0;     /* Largest docid for all iterators */
140414      int i;                      /* Used to iterate through tokens */
140415
140416      /* Advance the iterator for each token in the phrase once. */
140417      for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
140418        rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
140419        if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
140420          iMax = a[i].iDocid;
140421          bMaxSet = 1;
140422        }
140423      }
140424      assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
140425      assert( rc!=SQLITE_OK || bMaxSet );
140426
140427      /* Keep advancing iterators until they all point to the same document */
140428      for(i=0; i<p->nToken; i++){
140429        while( rc==SQLITE_OK && bEof==0
140430            && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
140431        ){
140432          rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
140433          if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
140434            iMax = a[i].iDocid;
140435            i = 0;
140436          }
140437        }
140438      }
140439
140440      /* Check if the current entries really are a phrase match */
140441      if( bEof==0 ){
140442        int nList = 0;
140443        int nByte = a[p->nToken-1].nList;
140444        char *aDoclist = sqlite3_malloc(nByte+1);
140445        if( !aDoclist ) return SQLITE_NOMEM;
140446        memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
140447
140448        for(i=0; i<(p->nToken-1); i++){
140449          if( a[i].bIgnore==0 ){
140450            char *pL = a[i].pList;
140451            char *pR = aDoclist;
140452            char *pOut = aDoclist;
140453            int nDist = p->nToken-1-i;
140454            int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
140455            if( res==0 ) break;
140456            nList = (int)(pOut - aDoclist);
140457          }
140458        }
140459        if( i==(p->nToken-1) ){
140460          pDL->iDocid = iMax;
140461          pDL->pList = aDoclist;
140462          pDL->nList = nList;
140463          pDL->bFreeList = 1;
140464          break;
140465        }
140466        sqlite3_free(aDoclist);
140467      }
140468    }
140469  }
140470
140471  *pbEof = bEof;
140472  return rc;
140473}
140474
140475/*
140476** Attempt to move the phrase iterator to point to the next matching docid.
140477** If an error occurs, return an SQLite error code. Otherwise, return
140478** SQLITE_OK.
140479**
140480** If there is no "next" entry and no error occurs, then *pbEof is set to
140481** 1 before returning. Otherwise, if no error occurs and the iterator is
140482** successfully advanced, *pbEof is set to 0.
140483*/
140484static int fts3EvalPhraseNext(
140485  Fts3Cursor *pCsr,               /* FTS Cursor handle */
140486  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
140487  u8 *pbEof                       /* OUT: Set to 1 if EOF */
140488){
140489  int rc = SQLITE_OK;
140490  Fts3Doclist *pDL = &p->doclist;
140491  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
140492
140493  if( p->bIncr ){
140494    rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
140495  }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
140496    sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
140497        &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
140498    );
140499    pDL->pList = pDL->pNextDocid;
140500  }else{
140501    fts3EvalDlPhraseNext(pTab, pDL, pbEof);
140502  }
140503
140504  return rc;
140505}
140506
140507/*
140508**
140509** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
140510** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
140511** expression. Also the Fts3Expr.bDeferred variable is set to true for any
140512** expressions for which all descendent tokens are deferred.
140513**
140514** If parameter bOptOk is zero, then it is guaranteed that the
140515** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
140516** each phrase in the expression (subject to deferred token processing).
140517** Or, if bOptOk is non-zero, then one or more tokens within the expression
140518** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
140519**
140520** If an error occurs within this function, *pRc is set to an SQLite error
140521** code before returning.
140522*/
140523static void fts3EvalStartReaders(
140524  Fts3Cursor *pCsr,               /* FTS Cursor handle */
140525  Fts3Expr *pExpr,                /* Expression to initialize phrases in */
140526  int *pRc                        /* IN/OUT: Error code */
140527){
140528  if( pExpr && SQLITE_OK==*pRc ){
140529    if( pExpr->eType==FTSQUERY_PHRASE ){
140530      int nToken = pExpr->pPhrase->nToken;
140531      if( nToken ){
140532        int i;
140533        for(i=0; i<nToken; i++){
140534          if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
140535        }
140536        pExpr->bDeferred = (i==nToken);
140537      }
140538      *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
140539    }else{
140540      fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
140541      fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
140542      pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
140543    }
140544  }
140545}
140546
140547/*
140548** An array of the following structures is assembled as part of the process
140549** of selecting tokens to defer before the query starts executing (as part
140550** of the xFilter() method). There is one element in the array for each
140551** token in the FTS expression.
140552**
140553** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
140554** to phrases that are connected only by AND and NEAR operators (not OR or
140555** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
140556** separately. The root of a tokens AND/NEAR cluster is stored in
140557** Fts3TokenAndCost.pRoot.
140558*/
140559typedef struct Fts3TokenAndCost Fts3TokenAndCost;
140560struct Fts3TokenAndCost {
140561  Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
140562  int iToken;                     /* Position of token in phrase */
140563  Fts3PhraseToken *pToken;        /* The token itself */
140564  Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
140565  int nOvfl;                      /* Number of overflow pages to load doclist */
140566  int iCol;                       /* The column the token must match */
140567};
140568
140569/*
140570** This function is used to populate an allocated Fts3TokenAndCost array.
140571**
140572** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
140573** Otherwise, if an error occurs during execution, *pRc is set to an
140574** SQLite error code.
140575*/
140576static void fts3EvalTokenCosts(
140577  Fts3Cursor *pCsr,               /* FTS Cursor handle */
140578  Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
140579  Fts3Expr *pExpr,                /* Expression to consider */
140580  Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
140581  Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
140582  int *pRc                        /* IN/OUT: Error code */
140583){
140584  if( *pRc==SQLITE_OK ){
140585    if( pExpr->eType==FTSQUERY_PHRASE ){
140586      Fts3Phrase *pPhrase = pExpr->pPhrase;
140587      int i;
140588      for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
140589        Fts3TokenAndCost *pTC = (*ppTC)++;
140590        pTC->pPhrase = pPhrase;
140591        pTC->iToken = i;
140592        pTC->pRoot = pRoot;
140593        pTC->pToken = &pPhrase->aToken[i];
140594        pTC->iCol = pPhrase->iColumn;
140595        *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
140596      }
140597    }else if( pExpr->eType!=FTSQUERY_NOT ){
140598      assert( pExpr->eType==FTSQUERY_OR
140599           || pExpr->eType==FTSQUERY_AND
140600           || pExpr->eType==FTSQUERY_NEAR
140601      );
140602      assert( pExpr->pLeft && pExpr->pRight );
140603      if( pExpr->eType==FTSQUERY_OR ){
140604        pRoot = pExpr->pLeft;
140605        **ppOr = pRoot;
140606        (*ppOr)++;
140607      }
140608      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
140609      if( pExpr->eType==FTSQUERY_OR ){
140610        pRoot = pExpr->pRight;
140611        **ppOr = pRoot;
140612        (*ppOr)++;
140613      }
140614      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
140615    }
140616  }
140617}
140618
140619/*
140620** Determine the average document (row) size in pages. If successful,
140621** write this value to *pnPage and return SQLITE_OK. Otherwise, return
140622** an SQLite error code.
140623**
140624** The average document size in pages is calculated by first calculating
140625** determining the average size in bytes, B. If B is less than the amount
140626** of data that will fit on a single leaf page of an intkey table in
140627** this database, then the average docsize is 1. Otherwise, it is 1 plus
140628** the number of overflow pages consumed by a record B bytes in size.
140629*/
140630static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
140631  if( pCsr->nRowAvg==0 ){
140632    /* The average document size, which is required to calculate the cost
140633    ** of each doclist, has not yet been determined. Read the required
140634    ** data from the %_stat table to calculate it.
140635    **
140636    ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
140637    ** varints, where nCol is the number of columns in the FTS3 table.
140638    ** The first varint is the number of documents currently stored in
140639    ** the table. The following nCol varints contain the total amount of
140640    ** data stored in all rows of each column of the table, from left
140641    ** to right.
140642    */
140643    int rc;
140644    Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
140645    sqlite3_stmt *pStmt;
140646    sqlite3_int64 nDoc = 0;
140647    sqlite3_int64 nByte = 0;
140648    const char *pEnd;
140649    const char *a;
140650
140651    rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
140652    if( rc!=SQLITE_OK ) return rc;
140653    a = sqlite3_column_blob(pStmt, 0);
140654    assert( a );
140655
140656    pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
140657    a += sqlite3Fts3GetVarint(a, &nDoc);
140658    while( a<pEnd ){
140659      a += sqlite3Fts3GetVarint(a, &nByte);
140660    }
140661    if( nDoc==0 || nByte==0 ){
140662      sqlite3_reset(pStmt);
140663      return FTS_CORRUPT_VTAB;
140664    }
140665
140666    pCsr->nDoc = nDoc;
140667    pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
140668    assert( pCsr->nRowAvg>0 );
140669    rc = sqlite3_reset(pStmt);
140670    if( rc!=SQLITE_OK ) return rc;
140671  }
140672
140673  *pnPage = pCsr->nRowAvg;
140674  return SQLITE_OK;
140675}
140676
140677/*
140678** This function is called to select the tokens (if any) that will be
140679** deferred. The array aTC[] has already been populated when this is
140680** called.
140681**
140682** This function is called once for each AND/NEAR cluster in the
140683** expression. Each invocation determines which tokens to defer within
140684** the cluster with root node pRoot. See comments above the definition
140685** of struct Fts3TokenAndCost for more details.
140686**
140687** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
140688** called on each token to defer. Otherwise, an SQLite error code is
140689** returned.
140690*/
140691static int fts3EvalSelectDeferred(
140692  Fts3Cursor *pCsr,               /* FTS Cursor handle */
140693  Fts3Expr *pRoot,                /* Consider tokens with this root node */
140694  Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
140695  int nTC                         /* Number of entries in aTC[] */
140696){
140697  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
140698  int nDocSize = 0;               /* Number of pages per doc loaded */
140699  int rc = SQLITE_OK;             /* Return code */
140700  int ii;                         /* Iterator variable for various purposes */
140701  int nOvfl = 0;                  /* Total overflow pages used by doclists */
140702  int nToken = 0;                 /* Total number of tokens in cluster */
140703
140704  int nMinEst = 0;                /* The minimum count for any phrase so far. */
140705  int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
140706
140707  /* Tokens are never deferred for FTS tables created using the content=xxx
140708  ** option. The reason being that it is not guaranteed that the content
140709  ** table actually contains the same data as the index. To prevent this from
140710  ** causing any problems, the deferred token optimization is completely
140711  ** disabled for content=xxx tables. */
140712  if( pTab->zContentTbl ){
140713    return SQLITE_OK;
140714  }
140715
140716  /* Count the tokens in this AND/NEAR cluster. If none of the doclists
140717  ** associated with the tokens spill onto overflow pages, or if there is
140718  ** only 1 token, exit early. No tokens to defer in this case. */
140719  for(ii=0; ii<nTC; ii++){
140720    if( aTC[ii].pRoot==pRoot ){
140721      nOvfl += aTC[ii].nOvfl;
140722      nToken++;
140723    }
140724  }
140725  if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
140726
140727  /* Obtain the average docsize (in pages). */
140728  rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
140729  assert( rc!=SQLITE_OK || nDocSize>0 );
140730
140731
140732  /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
140733  ** of the number of overflow pages that will be loaded by the pager layer
140734  ** to retrieve the entire doclist for the token from the full-text index.
140735  ** Load the doclists for tokens that are either:
140736  **
140737  **   a. The cheapest token in the entire query (i.e. the one visited by the
140738  **      first iteration of this loop), or
140739  **
140740  **   b. Part of a multi-token phrase.
140741  **
140742  ** After each token doclist is loaded, merge it with the others from the
140743  ** same phrase and count the number of documents that the merged doclist
140744  ** contains. Set variable "nMinEst" to the smallest number of documents in
140745  ** any phrase doclist for which 1 or more token doclists have been loaded.
140746  ** Let nOther be the number of other phrases for which it is certain that
140747  ** one or more tokens will not be deferred.
140748  **
140749  ** Then, for each token, defer it if loading the doclist would result in
140750  ** loading N or more overflow pages into memory, where N is computed as:
140751  **
140752  **    (nMinEst + 4^nOther - 1) / (4^nOther)
140753  */
140754  for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
140755    int iTC;                      /* Used to iterate through aTC[] array. */
140756    Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
140757
140758    /* Set pTC to point to the cheapest remaining token. */
140759    for(iTC=0; iTC<nTC; iTC++){
140760      if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
140761       && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
140762      ){
140763        pTC = &aTC[iTC];
140764      }
140765    }
140766    assert( pTC );
140767
140768    if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
140769      /* The number of overflow pages to load for this (and therefore all
140770      ** subsequent) tokens is greater than the estimated number of pages
140771      ** that will be loaded if all subsequent tokens are deferred.
140772      */
140773      Fts3PhraseToken *pToken = pTC->pToken;
140774      rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
140775      fts3SegReaderCursorFree(pToken->pSegcsr);
140776      pToken->pSegcsr = 0;
140777    }else{
140778      /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
140779      ** for-loop. Except, limit the value to 2^24 to prevent it from
140780      ** overflowing the 32-bit integer it is stored in. */
140781      if( ii<12 ) nLoad4 = nLoad4*4;
140782
140783      if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
140784        /* Either this is the cheapest token in the entire query, or it is
140785        ** part of a multi-token phrase. Either way, the entire doclist will
140786        ** (eventually) be loaded into memory. It may as well be now. */
140787        Fts3PhraseToken *pToken = pTC->pToken;
140788        int nList = 0;
140789        char *pList = 0;
140790        rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
140791        assert( rc==SQLITE_OK || pList==0 );
140792        if( rc==SQLITE_OK ){
140793          rc = fts3EvalPhraseMergeToken(
140794              pTab, pTC->pPhrase, pTC->iToken,pList,nList
140795          );
140796        }
140797        if( rc==SQLITE_OK ){
140798          int nCount;
140799          nCount = fts3DoclistCountDocids(
140800              pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
140801          );
140802          if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
140803        }
140804      }
140805    }
140806    pTC->pToken = 0;
140807  }
140808
140809  return rc;
140810}
140811
140812/*
140813** This function is called from within the xFilter method. It initializes
140814** the full-text query currently stored in pCsr->pExpr. To iterate through
140815** the results of a query, the caller does:
140816**
140817**    fts3EvalStart(pCsr);
140818**    while( 1 ){
140819**      fts3EvalNext(pCsr);
140820**      if( pCsr->bEof ) break;
140821**      ... return row pCsr->iPrevId to the caller ...
140822**    }
140823*/
140824static int fts3EvalStart(Fts3Cursor *pCsr){
140825  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
140826  int rc = SQLITE_OK;
140827  int nToken = 0;
140828  int nOr = 0;
140829
140830  /* Allocate a MultiSegReader for each token in the expression. */
140831  fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
140832
140833  /* Determine which, if any, tokens in the expression should be deferred. */
140834#ifndef SQLITE_DISABLE_FTS4_DEFERRED
140835  if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
140836    Fts3TokenAndCost *aTC;
140837    Fts3Expr **apOr;
140838    aTC = (Fts3TokenAndCost *)sqlite3_malloc(
140839        sizeof(Fts3TokenAndCost) * nToken
140840      + sizeof(Fts3Expr *) * nOr * 2
140841    );
140842    apOr = (Fts3Expr **)&aTC[nToken];
140843
140844    if( !aTC ){
140845      rc = SQLITE_NOMEM;
140846    }else{
140847      int ii;
140848      Fts3TokenAndCost *pTC = aTC;
140849      Fts3Expr **ppOr = apOr;
140850
140851      fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
140852      nToken = (int)(pTC-aTC);
140853      nOr = (int)(ppOr-apOr);
140854
140855      if( rc==SQLITE_OK ){
140856        rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
140857        for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
140858          rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
140859        }
140860      }
140861
140862      sqlite3_free(aTC);
140863    }
140864  }
140865#endif
140866
140867  fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
140868  return rc;
140869}
140870
140871/*
140872** Invalidate the current position list for phrase pPhrase.
140873*/
140874static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
140875  if( pPhrase->doclist.bFreeList ){
140876    sqlite3_free(pPhrase->doclist.pList);
140877  }
140878  pPhrase->doclist.pList = 0;
140879  pPhrase->doclist.nList = 0;
140880  pPhrase->doclist.bFreeList = 0;
140881}
140882
140883/*
140884** This function is called to edit the position list associated with
140885** the phrase object passed as the fifth argument according to a NEAR
140886** condition. For example:
140887**
140888**     abc NEAR/5 "def ghi"
140889**
140890** Parameter nNear is passed the NEAR distance of the expression (5 in
140891** the example above). When this function is called, *paPoslist points to
140892** the position list, and *pnToken is the number of phrase tokens in, the
140893** phrase on the other side of the NEAR operator to pPhrase. For example,
140894** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
140895** the position list associated with phrase "abc".
140896**
140897** All positions in the pPhrase position list that are not sufficiently
140898** close to a position in the *paPoslist position list are removed. If this
140899** leaves 0 positions, zero is returned. Otherwise, non-zero.
140900**
140901** Before returning, *paPoslist is set to point to the position lsit
140902** associated with pPhrase. And *pnToken is set to the number of tokens in
140903** pPhrase.
140904*/
140905static int fts3EvalNearTrim(
140906  int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
140907  char *aTmp,                     /* Temporary space to use */
140908  char **paPoslist,               /* IN/OUT: Position list */
140909  int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
140910  Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
140911){
140912  int nParam1 = nNear + pPhrase->nToken;
140913  int nParam2 = nNear + *pnToken;
140914  int nNew;
140915  char *p2;
140916  char *pOut;
140917  int res;
140918
140919  assert( pPhrase->doclist.pList );
140920
140921  p2 = pOut = pPhrase->doclist.pList;
140922  res = fts3PoslistNearMerge(
140923    &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
140924  );
140925  if( res ){
140926    nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
140927    assert( pPhrase->doclist.pList[nNew]=='\0' );
140928    assert( nNew<=pPhrase->doclist.nList && nNew>0 );
140929    memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
140930    pPhrase->doclist.nList = nNew;
140931    *paPoslist = pPhrase->doclist.pList;
140932    *pnToken = pPhrase->nToken;
140933  }
140934
140935  return res;
140936}
140937
140938/*
140939** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
140940** Otherwise, it advances the expression passed as the second argument to
140941** point to the next matching row in the database. Expressions iterate through
140942** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
140943** or descending if it is non-zero.
140944**
140945** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
140946** successful, the following variables in pExpr are set:
140947**
140948**   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
140949**   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
140950**
140951** If the expression is of type FTSQUERY_PHRASE, and the expression is not
140952** at EOF, then the following variables are populated with the position list
140953** for the phrase for the visited row:
140954**
140955**   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
140956**   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
140957**
140958** It says above that this function advances the expression to the next
140959** matching row. This is usually true, but there are the following exceptions:
140960**
140961**   1. Deferred tokens are not taken into account. If a phrase consists
140962**      entirely of deferred tokens, it is assumed to match every row in
140963**      the db. In this case the position-list is not populated at all.
140964**
140965**      Or, if a phrase contains one or more deferred tokens and one or
140966**      more non-deferred tokens, then the expression is advanced to the
140967**      next possible match, considering only non-deferred tokens. In other
140968**      words, if the phrase is "A B C", and "B" is deferred, the expression
140969**      is advanced to the next row that contains an instance of "A * C",
140970**      where "*" may match any single token. The position list in this case
140971**      is populated as for "A * C" before returning.
140972**
140973**   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
140974**      advanced to point to the next row that matches "x AND y".
140975**
140976** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
140977** really a match, taking into account deferred tokens and NEAR operators.
140978*/
140979static void fts3EvalNextRow(
140980  Fts3Cursor *pCsr,               /* FTS Cursor handle */
140981  Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
140982  int *pRc                        /* IN/OUT: Error code */
140983){
140984  if( *pRc==SQLITE_OK ){
140985    int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
140986    assert( pExpr->bEof==0 );
140987    pExpr->bStart = 1;
140988
140989    switch( pExpr->eType ){
140990      case FTSQUERY_NEAR:
140991      case FTSQUERY_AND: {
140992        Fts3Expr *pLeft = pExpr->pLeft;
140993        Fts3Expr *pRight = pExpr->pRight;
140994        assert( !pLeft->bDeferred || !pRight->bDeferred );
140995
140996        if( pLeft->bDeferred ){
140997          /* LHS is entirely deferred. So we assume it matches every row.
140998          ** Advance the RHS iterator to find the next row visited. */
140999          fts3EvalNextRow(pCsr, pRight, pRc);
141000          pExpr->iDocid = pRight->iDocid;
141001          pExpr->bEof = pRight->bEof;
141002        }else if( pRight->bDeferred ){
141003          /* RHS is entirely deferred. So we assume it matches every row.
141004          ** Advance the LHS iterator to find the next row visited. */
141005          fts3EvalNextRow(pCsr, pLeft, pRc);
141006          pExpr->iDocid = pLeft->iDocid;
141007          pExpr->bEof = pLeft->bEof;
141008        }else{
141009          /* Neither the RHS or LHS are deferred. */
141010          fts3EvalNextRow(pCsr, pLeft, pRc);
141011          fts3EvalNextRow(pCsr, pRight, pRc);
141012          while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
141013            sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
141014            if( iDiff==0 ) break;
141015            if( iDiff<0 ){
141016              fts3EvalNextRow(pCsr, pLeft, pRc);
141017            }else{
141018              fts3EvalNextRow(pCsr, pRight, pRc);
141019            }
141020          }
141021          pExpr->iDocid = pLeft->iDocid;
141022          pExpr->bEof = (pLeft->bEof || pRight->bEof);
141023          if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
141024            if( pRight->pPhrase && pRight->pPhrase->doclist.aAll ){
141025              Fts3Doclist *pDl = &pRight->pPhrase->doclist;
141026              while( *pRc==SQLITE_OK && pRight->bEof==0 ){
141027                memset(pDl->pList, 0, pDl->nList);
141028                fts3EvalNextRow(pCsr, pRight, pRc);
141029              }
141030            }
141031            if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
141032              Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
141033              while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
141034                memset(pDl->pList, 0, pDl->nList);
141035                fts3EvalNextRow(pCsr, pLeft, pRc);
141036              }
141037            }
141038          }
141039        }
141040        break;
141041      }
141042
141043      case FTSQUERY_OR: {
141044        Fts3Expr *pLeft = pExpr->pLeft;
141045        Fts3Expr *pRight = pExpr->pRight;
141046        sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
141047
141048        assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
141049        assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
141050
141051        if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
141052          fts3EvalNextRow(pCsr, pLeft, pRc);
141053        }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
141054          fts3EvalNextRow(pCsr, pRight, pRc);
141055        }else{
141056          fts3EvalNextRow(pCsr, pLeft, pRc);
141057          fts3EvalNextRow(pCsr, pRight, pRc);
141058        }
141059
141060        pExpr->bEof = (pLeft->bEof && pRight->bEof);
141061        iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
141062        if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
141063          pExpr->iDocid = pLeft->iDocid;
141064        }else{
141065          pExpr->iDocid = pRight->iDocid;
141066        }
141067
141068        break;
141069      }
141070
141071      case FTSQUERY_NOT: {
141072        Fts3Expr *pLeft = pExpr->pLeft;
141073        Fts3Expr *pRight = pExpr->pRight;
141074
141075        if( pRight->bStart==0 ){
141076          fts3EvalNextRow(pCsr, pRight, pRc);
141077          assert( *pRc!=SQLITE_OK || pRight->bStart );
141078        }
141079
141080        fts3EvalNextRow(pCsr, pLeft, pRc);
141081        if( pLeft->bEof==0 ){
141082          while( !*pRc
141083              && !pRight->bEof
141084              && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
141085          ){
141086            fts3EvalNextRow(pCsr, pRight, pRc);
141087          }
141088        }
141089        pExpr->iDocid = pLeft->iDocid;
141090        pExpr->bEof = pLeft->bEof;
141091        break;
141092      }
141093
141094      default: {
141095        Fts3Phrase *pPhrase = pExpr->pPhrase;
141096        fts3EvalInvalidatePoslist(pPhrase);
141097        *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
141098        pExpr->iDocid = pPhrase->doclist.iDocid;
141099        break;
141100      }
141101    }
141102  }
141103}
141104
141105/*
141106** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
141107** cluster, then this function returns 1 immediately.
141108**
141109** Otherwise, it checks if the current row really does match the NEAR
141110** expression, using the data currently stored in the position lists
141111** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
141112**
141113** If the current row is a match, the position list associated with each
141114** phrase in the NEAR expression is edited in place to contain only those
141115** phrase instances sufficiently close to their peers to satisfy all NEAR
141116** constraints. In this case it returns 1. If the NEAR expression does not
141117** match the current row, 0 is returned. The position lists may or may not
141118** be edited if 0 is returned.
141119*/
141120static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
141121  int res = 1;
141122
141123  /* The following block runs if pExpr is the root of a NEAR query.
141124  ** For example, the query:
141125  **
141126  **         "w" NEAR "x" NEAR "y" NEAR "z"
141127  **
141128  ** which is represented in tree form as:
141129  **
141130  **                               |
141131  **                          +--NEAR--+      <-- root of NEAR query
141132  **                          |        |
141133  **                     +--NEAR--+   "z"
141134  **                     |        |
141135  **                +--NEAR--+   "y"
141136  **                |        |
141137  **               "w"      "x"
141138  **
141139  ** The right-hand child of a NEAR node is always a phrase. The
141140  ** left-hand child may be either a phrase or a NEAR node. There are
141141  ** no exceptions to this - it's the way the parser in fts3_expr.c works.
141142  */
141143  if( *pRc==SQLITE_OK
141144   && pExpr->eType==FTSQUERY_NEAR
141145   && pExpr->bEof==0
141146   && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
141147  ){
141148    Fts3Expr *p;
141149    int nTmp = 0;                 /* Bytes of temp space */
141150    char *aTmp;                   /* Temp space for PoslistNearMerge() */
141151
141152    /* Allocate temporary working space. */
141153    for(p=pExpr; p->pLeft; p=p->pLeft){
141154      nTmp += p->pRight->pPhrase->doclist.nList;
141155    }
141156    nTmp += p->pPhrase->doclist.nList;
141157    if( nTmp==0 ){
141158      res = 0;
141159    }else{
141160      aTmp = sqlite3_malloc(nTmp*2);
141161      if( !aTmp ){
141162        *pRc = SQLITE_NOMEM;
141163        res = 0;
141164      }else{
141165        char *aPoslist = p->pPhrase->doclist.pList;
141166        int nToken = p->pPhrase->nToken;
141167
141168        for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
141169          Fts3Phrase *pPhrase = p->pRight->pPhrase;
141170          int nNear = p->nNear;
141171          res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
141172        }
141173
141174        aPoslist = pExpr->pRight->pPhrase->doclist.pList;
141175        nToken = pExpr->pRight->pPhrase->nToken;
141176        for(p=pExpr->pLeft; p && res; p=p->pLeft){
141177          int nNear;
141178          Fts3Phrase *pPhrase;
141179          assert( p->pParent && p->pParent->pLeft==p );
141180          nNear = p->pParent->nNear;
141181          pPhrase = (
141182              p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
141183              );
141184          res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
141185        }
141186      }
141187
141188      sqlite3_free(aTmp);
141189    }
141190  }
141191
141192  return res;
141193}
141194
141195/*
141196** This function is a helper function for sqlite3Fts3EvalTestDeferred().
141197** Assuming no error occurs or has occurred, It returns non-zero if the
141198** expression passed as the second argument matches the row that pCsr
141199** currently points to, or zero if it does not.
141200**
141201** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
141202** If an error occurs during execution of this function, *pRc is set to
141203** the appropriate SQLite error code. In this case the returned value is
141204** undefined.
141205*/
141206static int fts3EvalTestExpr(
141207  Fts3Cursor *pCsr,               /* FTS cursor handle */
141208  Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
141209  int *pRc                        /* IN/OUT: Error code */
141210){
141211  int bHit = 1;                   /* Return value */
141212  if( *pRc==SQLITE_OK ){
141213    switch( pExpr->eType ){
141214      case FTSQUERY_NEAR:
141215      case FTSQUERY_AND:
141216        bHit = (
141217            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
141218         && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
141219         && fts3EvalNearTest(pExpr, pRc)
141220        );
141221
141222        /* If the NEAR expression does not match any rows, zero the doclist for
141223        ** all phrases involved in the NEAR. This is because the snippet(),
141224        ** offsets() and matchinfo() functions are not supposed to recognize
141225        ** any instances of phrases that are part of unmatched NEAR queries.
141226        ** For example if this expression:
141227        **
141228        **    ... MATCH 'a OR (b NEAR c)'
141229        **
141230        ** is matched against a row containing:
141231        **
141232        **        'a b d e'
141233        **
141234        ** then any snippet() should ony highlight the "a" term, not the "b"
141235        ** (as "b" is part of a non-matching NEAR clause).
141236        */
141237        if( bHit==0
141238         && pExpr->eType==FTSQUERY_NEAR
141239         && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
141240        ){
141241          Fts3Expr *p;
141242          for(p=pExpr; p->pPhrase==0; p=p->pLeft){
141243            if( p->pRight->iDocid==pCsr->iPrevId ){
141244              fts3EvalInvalidatePoslist(p->pRight->pPhrase);
141245            }
141246          }
141247          if( p->iDocid==pCsr->iPrevId ){
141248            fts3EvalInvalidatePoslist(p->pPhrase);
141249          }
141250        }
141251
141252        break;
141253
141254      case FTSQUERY_OR: {
141255        int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
141256        int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
141257        bHit = bHit1 || bHit2;
141258        break;
141259      }
141260
141261      case FTSQUERY_NOT:
141262        bHit = (
141263            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
141264         && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
141265        );
141266        break;
141267
141268      default: {
141269#ifndef SQLITE_DISABLE_FTS4_DEFERRED
141270        if( pCsr->pDeferred
141271         && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
141272        ){
141273          Fts3Phrase *pPhrase = pExpr->pPhrase;
141274          assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
141275          if( pExpr->bDeferred ){
141276            fts3EvalInvalidatePoslist(pPhrase);
141277          }
141278          *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
141279          bHit = (pPhrase->doclist.pList!=0);
141280          pExpr->iDocid = pCsr->iPrevId;
141281        }else
141282#endif
141283        {
141284          bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
141285        }
141286        break;
141287      }
141288    }
141289  }
141290  return bHit;
141291}
141292
141293/*
141294** This function is called as the second part of each xNext operation when
141295** iterating through the results of a full-text query. At this point the
141296** cursor points to a row that matches the query expression, with the
141297** following caveats:
141298**
141299**   * Up until this point, "NEAR" operators in the expression have been
141300**     treated as "AND".
141301**
141302**   * Deferred tokens have not yet been considered.
141303**
141304** If *pRc is not SQLITE_OK when this function is called, it immediately
141305** returns 0. Otherwise, it tests whether or not after considering NEAR
141306** operators and deferred tokens the current row is still a match for the
141307** expression. It returns 1 if both of the following are true:
141308**
141309**   1. *pRc is SQLITE_OK when this function returns, and
141310**
141311**   2. After scanning the current FTS table row for the deferred tokens,
141312**      it is determined that the row does *not* match the query.
141313**
141314** Or, if no error occurs and it seems the current row does match the FTS
141315** query, return 0.
141316*/
141317SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
141318  int rc = *pRc;
141319  int bMiss = 0;
141320  if( rc==SQLITE_OK ){
141321
141322    /* If there are one or more deferred tokens, load the current row into
141323    ** memory and scan it to determine the position list for each deferred
141324    ** token. Then, see if this row is really a match, considering deferred
141325    ** tokens and NEAR operators (neither of which were taken into account
141326    ** earlier, by fts3EvalNextRow()).
141327    */
141328    if( pCsr->pDeferred ){
141329      rc = fts3CursorSeek(0, pCsr);
141330      if( rc==SQLITE_OK ){
141331        rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
141332      }
141333    }
141334    bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
141335
141336    /* Free the position-lists accumulated for each deferred token above. */
141337    sqlite3Fts3FreeDeferredDoclists(pCsr);
141338    *pRc = rc;
141339  }
141340  return (rc==SQLITE_OK && bMiss);
141341}
141342
141343/*
141344** Advance to the next document that matches the FTS expression in
141345** Fts3Cursor.pExpr.
141346*/
141347static int fts3EvalNext(Fts3Cursor *pCsr){
141348  int rc = SQLITE_OK;             /* Return Code */
141349  Fts3Expr *pExpr = pCsr->pExpr;
141350  assert( pCsr->isEof==0 );
141351  if( pExpr==0 ){
141352    pCsr->isEof = 1;
141353  }else{
141354    do {
141355      if( pCsr->isRequireSeek==0 ){
141356        sqlite3_reset(pCsr->pStmt);
141357      }
141358      assert( sqlite3_data_count(pCsr->pStmt)==0 );
141359      fts3EvalNextRow(pCsr, pExpr, &rc);
141360      pCsr->isEof = pExpr->bEof;
141361      pCsr->isRequireSeek = 1;
141362      pCsr->isMatchinfoNeeded = 1;
141363      pCsr->iPrevId = pExpr->iDocid;
141364    }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
141365  }
141366
141367  /* Check if the cursor is past the end of the docid range specified
141368  ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag.  */
141369  if( rc==SQLITE_OK && (
141370        (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
141371     || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
141372  )){
141373    pCsr->isEof = 1;
141374  }
141375
141376  return rc;
141377}
141378
141379/*
141380** Restart interation for expression pExpr so that the next call to
141381** fts3EvalNext() visits the first row. Do not allow incremental
141382** loading or merging of phrase doclists for this iteration.
141383**
141384** If *pRc is other than SQLITE_OK when this function is called, it is
141385** a no-op. If an error occurs within this function, *pRc is set to an
141386** SQLite error code before returning.
141387*/
141388static void fts3EvalRestart(
141389  Fts3Cursor *pCsr,
141390  Fts3Expr *pExpr,
141391  int *pRc
141392){
141393  if( pExpr && *pRc==SQLITE_OK ){
141394    Fts3Phrase *pPhrase = pExpr->pPhrase;
141395
141396    if( pPhrase ){
141397      fts3EvalInvalidatePoslist(pPhrase);
141398      if( pPhrase->bIncr ){
141399        int i;
141400        for(i=0; i<pPhrase->nToken; i++){
141401          Fts3PhraseToken *pToken = &pPhrase->aToken[i];
141402          assert( pToken->pDeferred==0 );
141403          if( pToken->pSegcsr ){
141404            sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
141405          }
141406        }
141407        *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
141408      }
141409      pPhrase->doclist.pNextDocid = 0;
141410      pPhrase->doclist.iDocid = 0;
141411      pPhrase->pOrPoslist = 0;
141412    }
141413
141414    pExpr->iDocid = 0;
141415    pExpr->bEof = 0;
141416    pExpr->bStart = 0;
141417
141418    fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
141419    fts3EvalRestart(pCsr, pExpr->pRight, pRc);
141420  }
141421}
141422
141423/*
141424** After allocating the Fts3Expr.aMI[] array for each phrase in the
141425** expression rooted at pExpr, the cursor iterates through all rows matched
141426** by pExpr, calling this function for each row. This function increments
141427** the values in Fts3Expr.aMI[] according to the position-list currently
141428** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
141429** expression nodes.
141430*/
141431static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
141432  if( pExpr ){
141433    Fts3Phrase *pPhrase = pExpr->pPhrase;
141434    if( pPhrase && pPhrase->doclist.pList ){
141435      int iCol = 0;
141436      char *p = pPhrase->doclist.pList;
141437
141438      assert( *p );
141439      while( 1 ){
141440        u8 c = 0;
141441        int iCnt = 0;
141442        while( 0xFE & (*p | c) ){
141443          if( (c&0x80)==0 ) iCnt++;
141444          c = *p++ & 0x80;
141445        }
141446
141447        /* aMI[iCol*3 + 1] = Number of occurrences
141448        ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
141449        */
141450        pExpr->aMI[iCol*3 + 1] += iCnt;
141451        pExpr->aMI[iCol*3 + 2] += (iCnt>0);
141452        if( *p==0x00 ) break;
141453        p++;
141454        p += fts3GetVarint32(p, &iCol);
141455      }
141456    }
141457
141458    fts3EvalUpdateCounts(pExpr->pLeft);
141459    fts3EvalUpdateCounts(pExpr->pRight);
141460  }
141461}
141462
141463/*
141464** Expression pExpr must be of type FTSQUERY_PHRASE.
141465**
141466** If it is not already allocated and populated, this function allocates and
141467** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
141468** of a NEAR expression, then it also allocates and populates the same array
141469** for all other phrases that are part of the NEAR expression.
141470**
141471** SQLITE_OK is returned if the aMI[] array is successfully allocated and
141472** populated. Otherwise, if an error occurs, an SQLite error code is returned.
141473*/
141474static int fts3EvalGatherStats(
141475  Fts3Cursor *pCsr,               /* Cursor object */
141476  Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
141477){
141478  int rc = SQLITE_OK;             /* Return code */
141479
141480  assert( pExpr->eType==FTSQUERY_PHRASE );
141481  if( pExpr->aMI==0 ){
141482    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
141483    Fts3Expr *pRoot;                /* Root of NEAR expression */
141484    Fts3Expr *p;                    /* Iterator used for several purposes */
141485
141486    sqlite3_int64 iPrevId = pCsr->iPrevId;
141487    sqlite3_int64 iDocid;
141488    u8 bEof;
141489
141490    /* Find the root of the NEAR expression */
141491    pRoot = pExpr;
141492    while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
141493      pRoot = pRoot->pParent;
141494    }
141495    iDocid = pRoot->iDocid;
141496    bEof = pRoot->bEof;
141497    assert( pRoot->bStart );
141498
141499    /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
141500    for(p=pRoot; p; p=p->pLeft){
141501      Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
141502      assert( pE->aMI==0 );
141503      pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
141504      if( !pE->aMI ) return SQLITE_NOMEM;
141505      memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
141506    }
141507
141508    fts3EvalRestart(pCsr, pRoot, &rc);
141509
141510    while( pCsr->isEof==0 && rc==SQLITE_OK ){
141511
141512      do {
141513        /* Ensure the %_content statement is reset. */
141514        if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
141515        assert( sqlite3_data_count(pCsr->pStmt)==0 );
141516
141517        /* Advance to the next document */
141518        fts3EvalNextRow(pCsr, pRoot, &rc);
141519        pCsr->isEof = pRoot->bEof;
141520        pCsr->isRequireSeek = 1;
141521        pCsr->isMatchinfoNeeded = 1;
141522        pCsr->iPrevId = pRoot->iDocid;
141523      }while( pCsr->isEof==0
141524           && pRoot->eType==FTSQUERY_NEAR
141525           && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
141526      );
141527
141528      if( rc==SQLITE_OK && pCsr->isEof==0 ){
141529        fts3EvalUpdateCounts(pRoot);
141530      }
141531    }
141532
141533    pCsr->isEof = 0;
141534    pCsr->iPrevId = iPrevId;
141535
141536    if( bEof ){
141537      pRoot->bEof = bEof;
141538    }else{
141539      /* Caution: pRoot may iterate through docids in ascending or descending
141540      ** order. For this reason, even though it seems more defensive, the
141541      ** do loop can not be written:
141542      **
141543      **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
141544      */
141545      fts3EvalRestart(pCsr, pRoot, &rc);
141546      do {
141547        fts3EvalNextRow(pCsr, pRoot, &rc);
141548        assert( pRoot->bEof==0 );
141549      }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
141550    }
141551  }
141552  return rc;
141553}
141554
141555/*
141556** This function is used by the matchinfo() module to query a phrase
141557** expression node for the following information:
141558**
141559**   1. The total number of occurrences of the phrase in each column of
141560**      the FTS table (considering all rows), and
141561**
141562**   2. For each column, the number of rows in the table for which the
141563**      column contains at least one instance of the phrase.
141564**
141565** If no error occurs, SQLITE_OK is returned and the values for each column
141566** written into the array aiOut as follows:
141567**
141568**   aiOut[iCol*3 + 1] = Number of occurrences
141569**   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
141570**
141571** Caveats:
141572**
141573**   * If a phrase consists entirely of deferred tokens, then all output
141574**     values are set to the number of documents in the table. In other
141575**     words we assume that very common tokens occur exactly once in each
141576**     column of each row of the table.
141577**
141578**   * If a phrase contains some deferred tokens (and some non-deferred
141579**     tokens), count the potential occurrence identified by considering
141580**     the non-deferred tokens instead of actual phrase occurrences.
141581**
141582**   * If the phrase is part of a NEAR expression, then only phrase instances
141583**     that meet the NEAR constraint are included in the counts.
141584*/
141585SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
141586  Fts3Cursor *pCsr,               /* FTS cursor handle */
141587  Fts3Expr *pExpr,                /* Phrase expression */
141588  u32 *aiOut                      /* Array to write results into (see above) */
141589){
141590  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
141591  int rc = SQLITE_OK;
141592  int iCol;
141593
141594  if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
141595    assert( pCsr->nDoc>0 );
141596    for(iCol=0; iCol<pTab->nColumn; iCol++){
141597      aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
141598      aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
141599    }
141600  }else{
141601    rc = fts3EvalGatherStats(pCsr, pExpr);
141602    if( rc==SQLITE_OK ){
141603      assert( pExpr->aMI );
141604      for(iCol=0; iCol<pTab->nColumn; iCol++){
141605        aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
141606        aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
141607      }
141608    }
141609  }
141610
141611  return rc;
141612}
141613
141614/*
141615** The expression pExpr passed as the second argument to this function
141616** must be of type FTSQUERY_PHRASE.
141617**
141618** The returned value is either NULL or a pointer to a buffer containing
141619** a position-list indicating the occurrences of the phrase in column iCol
141620** of the current row.
141621**
141622** More specifically, the returned buffer contains 1 varint for each
141623** occurrence of the phrase in the column, stored using the normal (delta+2)
141624** compression and is terminated by either an 0x01 or 0x00 byte. For example,
141625** if the requested column contains "a b X c d X X" and the position-list
141626** for 'X' is requested, the buffer returned may contain:
141627**
141628**     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
141629**
141630** This function works regardless of whether or not the phrase is deferred,
141631** incremental, or neither.
141632*/
141633SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
141634  Fts3Cursor *pCsr,               /* FTS3 cursor object */
141635  Fts3Expr *pExpr,                /* Phrase to return doclist for */
141636  int iCol,                       /* Column to return position list for */
141637  char **ppOut                    /* OUT: Pointer to position list */
141638){
141639  Fts3Phrase *pPhrase = pExpr->pPhrase;
141640  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
141641  char *pIter;
141642  int iThis;
141643  sqlite3_int64 iDocid;
141644
141645  /* If this phrase is applies specifically to some column other than
141646  ** column iCol, return a NULL pointer.  */
141647  *ppOut = 0;
141648  assert( iCol>=0 && iCol<pTab->nColumn );
141649  if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
141650    return SQLITE_OK;
141651  }
141652
141653  iDocid = pExpr->iDocid;
141654  pIter = pPhrase->doclist.pList;
141655  if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
141656    int rc = SQLITE_OK;
141657    int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
141658    int bOr = 0;
141659    u8 bTreeEof = 0;
141660    Fts3Expr *p;                  /* Used to iterate from pExpr to root */
141661    Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */
141662    int bMatch;
141663
141664    /* Check if this phrase descends from an OR expression node. If not,
141665    ** return NULL. Otherwise, the entry that corresponds to docid
141666    ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
141667    ** tree that the node is part of has been marked as EOF, but the node
141668    ** itself is not EOF, then it may point to an earlier entry. */
141669    pNear = pExpr;
141670    for(p=pExpr->pParent; p; p=p->pParent){
141671      if( p->eType==FTSQUERY_OR ) bOr = 1;
141672      if( p->eType==FTSQUERY_NEAR ) pNear = p;
141673      if( p->bEof ) bTreeEof = 1;
141674    }
141675    if( bOr==0 ) return SQLITE_OK;
141676
141677    /* This is the descendent of an OR node. In this case we cannot use
141678    ** an incremental phrase. Load the entire doclist for the phrase
141679    ** into memory in this case.  */
141680    if( pPhrase->bIncr ){
141681      int bEofSave = pNear->bEof;
141682      fts3EvalRestart(pCsr, pNear, &rc);
141683      while( rc==SQLITE_OK && !pNear->bEof ){
141684        fts3EvalNextRow(pCsr, pNear, &rc);
141685        if( bEofSave==0 && pNear->iDocid==iDocid ) break;
141686      }
141687      assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
141688    }
141689    if( bTreeEof ){
141690      while( rc==SQLITE_OK && !pNear->bEof ){
141691        fts3EvalNextRow(pCsr, pNear, &rc);
141692      }
141693    }
141694    if( rc!=SQLITE_OK ) return rc;
141695
141696    bMatch = 1;
141697    for(p=pNear; p; p=p->pLeft){
141698      u8 bEof = 0;
141699      Fts3Expr *pTest = p;
141700      Fts3Phrase *pPh;
141701      assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
141702      if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
141703      assert( pTest->eType==FTSQUERY_PHRASE );
141704      pPh = pTest->pPhrase;
141705
141706      pIter = pPh->pOrPoslist;
141707      iDocid = pPh->iOrDocid;
141708      if( pCsr->bDesc==bDescDoclist ){
141709        bEof = !pPh->doclist.nAll ||
141710          (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
141711        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
141712          sqlite3Fts3DoclistNext(
141713              bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
141714              &pIter, &iDocid, &bEof
141715          );
141716        }
141717      }else{
141718        bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
141719        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
141720          int dummy;
141721          sqlite3Fts3DoclistPrev(
141722              bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
141723              &pIter, &iDocid, &dummy, &bEof
141724              );
141725        }
141726      }
141727      pPh->pOrPoslist = pIter;
141728      pPh->iOrDocid = iDocid;
141729      if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
141730    }
141731
141732    if( bMatch ){
141733      pIter = pPhrase->pOrPoslist;
141734    }else{
141735      pIter = 0;
141736    }
141737  }
141738  if( pIter==0 ) return SQLITE_OK;
141739
141740  if( *pIter==0x01 ){
141741    pIter++;
141742    pIter += fts3GetVarint32(pIter, &iThis);
141743  }else{
141744    iThis = 0;
141745  }
141746  while( iThis<iCol ){
141747    fts3ColumnlistCopy(0, &pIter);
141748    if( *pIter==0x00 ) return SQLITE_OK;
141749    pIter++;
141750    pIter += fts3GetVarint32(pIter, &iThis);
141751  }
141752  if( *pIter==0x00 ){
141753    pIter = 0;
141754  }
141755
141756  *ppOut = ((iCol==iThis)?pIter:0);
141757  return SQLITE_OK;
141758}
141759
141760/*
141761** Free all components of the Fts3Phrase structure that were allocated by
141762** the eval module. Specifically, this means to free:
141763**
141764**   * the contents of pPhrase->doclist, and
141765**   * any Fts3MultiSegReader objects held by phrase tokens.
141766*/
141767SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
141768  if( pPhrase ){
141769    int i;
141770    sqlite3_free(pPhrase->doclist.aAll);
141771    fts3EvalInvalidatePoslist(pPhrase);
141772    memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
141773    for(i=0; i<pPhrase->nToken; i++){
141774      fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
141775      pPhrase->aToken[i].pSegcsr = 0;
141776    }
141777  }
141778}
141779
141780
141781/*
141782** Return SQLITE_CORRUPT_VTAB.
141783*/
141784#ifdef SQLITE_DEBUG
141785SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
141786  return SQLITE_CORRUPT_VTAB;
141787}
141788#endif
141789
141790#if !SQLITE_CORE
141791/*
141792** Initialize API pointer table, if required.
141793*/
141794#ifdef _WIN32
141795__declspec(dllexport)
141796#endif
141797SQLITE_API int SQLITE_STDCALL sqlite3_fts3_init(
141798  sqlite3 *db,
141799  char **pzErrMsg,
141800  const sqlite3_api_routines *pApi
141801){
141802  SQLITE_EXTENSION_INIT2(pApi)
141803  return sqlite3Fts3Init(db);
141804}
141805#endif
141806
141807#endif
141808
141809/************** End of fts3.c ************************************************/
141810/************** Begin file fts3_aux.c ****************************************/
141811/*
141812** 2011 Jan 27
141813**
141814** The author disclaims copyright to this source code.  In place of
141815** a legal notice, here is a blessing:
141816**
141817**    May you do good and not evil.
141818**    May you find forgiveness for yourself and forgive others.
141819**    May you share freely, never taking more than you give.
141820**
141821******************************************************************************
141822**
141823*/
141824/* #include "fts3Int.h" */
141825#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
141826
141827/* #include <string.h> */
141828/* #include <assert.h> */
141829
141830typedef struct Fts3auxTable Fts3auxTable;
141831typedef struct Fts3auxCursor Fts3auxCursor;
141832
141833struct Fts3auxTable {
141834  sqlite3_vtab base;              /* Base class used by SQLite core */
141835  Fts3Table *pFts3Tab;
141836};
141837
141838struct Fts3auxCursor {
141839  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
141840  Fts3MultiSegReader csr;        /* Must be right after "base" */
141841  Fts3SegFilter filter;
141842  char *zStop;
141843  int nStop;                      /* Byte-length of string zStop */
141844  int iLangid;                    /* Language id to query */
141845  int isEof;                      /* True if cursor is at EOF */
141846  sqlite3_int64 iRowid;           /* Current rowid */
141847
141848  int iCol;                       /* Current value of 'col' column */
141849  int nStat;                      /* Size of aStat[] array */
141850  struct Fts3auxColstats {
141851    sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
141852    sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
141853  } *aStat;
141854};
141855
141856/*
141857** Schema of the terms table.
141858*/
141859#define FTS3_AUX_SCHEMA \
141860  "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
141861
141862/*
141863** This function does all the work for both the xConnect and xCreate methods.
141864** These tables have no persistent representation of their own, so xConnect
141865** and xCreate are identical operations.
141866*/
141867static int fts3auxConnectMethod(
141868  sqlite3 *db,                    /* Database connection */
141869  void *pUnused,                  /* Unused */
141870  int argc,                       /* Number of elements in argv array */
141871  const char * const *argv,       /* xCreate/xConnect argument array */
141872  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
141873  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
141874){
141875  char const *zDb;                /* Name of database (e.g. "main") */
141876  char const *zFts3;              /* Name of fts3 table */
141877  int nDb;                        /* Result of strlen(zDb) */
141878  int nFts3;                      /* Result of strlen(zFts3) */
141879  int nByte;                      /* Bytes of space to allocate here */
141880  int rc;                         /* value returned by declare_vtab() */
141881  Fts3auxTable *p;                /* Virtual table object to return */
141882
141883  UNUSED_PARAMETER(pUnused);
141884
141885  /* The user should invoke this in one of two forms:
141886  **
141887  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
141888  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
141889  */
141890  if( argc!=4 && argc!=5 ) goto bad_args;
141891
141892  zDb = argv[1];
141893  nDb = (int)strlen(zDb);
141894  if( argc==5 ){
141895    if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
141896      zDb = argv[3];
141897      nDb = (int)strlen(zDb);
141898      zFts3 = argv[4];
141899    }else{
141900      goto bad_args;
141901    }
141902  }else{
141903    zFts3 = argv[3];
141904  }
141905  nFts3 = (int)strlen(zFts3);
141906
141907  rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
141908  if( rc!=SQLITE_OK ) return rc;
141909
141910  nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
141911  p = (Fts3auxTable *)sqlite3_malloc(nByte);
141912  if( !p ) return SQLITE_NOMEM;
141913  memset(p, 0, nByte);
141914
141915  p->pFts3Tab = (Fts3Table *)&p[1];
141916  p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
141917  p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
141918  p->pFts3Tab->db = db;
141919  p->pFts3Tab->nIndex = 1;
141920
141921  memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
141922  memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
141923  sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
141924
141925  *ppVtab = (sqlite3_vtab *)p;
141926  return SQLITE_OK;
141927
141928 bad_args:
141929  sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
141930  return SQLITE_ERROR;
141931}
141932
141933/*
141934** This function does the work for both the xDisconnect and xDestroy methods.
141935** These tables have no persistent representation of their own, so xDisconnect
141936** and xDestroy are identical operations.
141937*/
141938static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
141939  Fts3auxTable *p = (Fts3auxTable *)pVtab;
141940  Fts3Table *pFts3 = p->pFts3Tab;
141941  int i;
141942
141943  /* Free any prepared statements held */
141944  for(i=0; i<SizeofArray(pFts3->aStmt); i++){
141945    sqlite3_finalize(pFts3->aStmt[i]);
141946  }
141947  sqlite3_free(pFts3->zSegmentsTbl);
141948  sqlite3_free(p);
141949  return SQLITE_OK;
141950}
141951
141952#define FTS4AUX_EQ_CONSTRAINT 1
141953#define FTS4AUX_GE_CONSTRAINT 2
141954#define FTS4AUX_LE_CONSTRAINT 4
141955
141956/*
141957** xBestIndex - Analyze a WHERE and ORDER BY clause.
141958*/
141959static int fts3auxBestIndexMethod(
141960  sqlite3_vtab *pVTab,
141961  sqlite3_index_info *pInfo
141962){
141963  int i;
141964  int iEq = -1;
141965  int iGe = -1;
141966  int iLe = -1;
141967  int iLangid = -1;
141968  int iNext = 1;                  /* Next free argvIndex value */
141969
141970  UNUSED_PARAMETER(pVTab);
141971
141972  /* This vtab delivers always results in "ORDER BY term ASC" order. */
141973  if( pInfo->nOrderBy==1
141974   && pInfo->aOrderBy[0].iColumn==0
141975   && pInfo->aOrderBy[0].desc==0
141976  ){
141977    pInfo->orderByConsumed = 1;
141978  }
141979
141980  /* Search for equality and range constraints on the "term" column.
141981  ** And equality constraints on the hidden "languageid" column. */
141982  for(i=0; i<pInfo->nConstraint; i++){
141983    if( pInfo->aConstraint[i].usable ){
141984      int op = pInfo->aConstraint[i].op;
141985      int iCol = pInfo->aConstraint[i].iColumn;
141986
141987      if( iCol==0 ){
141988        if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
141989        if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
141990        if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
141991        if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
141992        if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
141993      }
141994      if( iCol==4 ){
141995        if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
141996      }
141997    }
141998  }
141999
142000  if( iEq>=0 ){
142001    pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
142002    pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
142003    pInfo->estimatedCost = 5;
142004  }else{
142005    pInfo->idxNum = 0;
142006    pInfo->estimatedCost = 20000;
142007    if( iGe>=0 ){
142008      pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
142009      pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
142010      pInfo->estimatedCost /= 2;
142011    }
142012    if( iLe>=0 ){
142013      pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
142014      pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
142015      pInfo->estimatedCost /= 2;
142016    }
142017  }
142018  if( iLangid>=0 ){
142019    pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
142020    pInfo->estimatedCost--;
142021  }
142022
142023  return SQLITE_OK;
142024}
142025
142026/*
142027** xOpen - Open a cursor.
142028*/
142029static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
142030  Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
142031
142032  UNUSED_PARAMETER(pVTab);
142033
142034  pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
142035  if( !pCsr ) return SQLITE_NOMEM;
142036  memset(pCsr, 0, sizeof(Fts3auxCursor));
142037
142038  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
142039  return SQLITE_OK;
142040}
142041
142042/*
142043** xClose - Close a cursor.
142044*/
142045static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
142046  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
142047  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
142048
142049  sqlite3Fts3SegmentsClose(pFts3);
142050  sqlite3Fts3SegReaderFinish(&pCsr->csr);
142051  sqlite3_free((void *)pCsr->filter.zTerm);
142052  sqlite3_free(pCsr->zStop);
142053  sqlite3_free(pCsr->aStat);
142054  sqlite3_free(pCsr);
142055  return SQLITE_OK;
142056}
142057
142058static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
142059  if( nSize>pCsr->nStat ){
142060    struct Fts3auxColstats *aNew;
142061    aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
142062        sizeof(struct Fts3auxColstats) * nSize
142063    );
142064    if( aNew==0 ) return SQLITE_NOMEM;
142065    memset(&aNew[pCsr->nStat], 0,
142066        sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
142067    );
142068    pCsr->aStat = aNew;
142069    pCsr->nStat = nSize;
142070  }
142071  return SQLITE_OK;
142072}
142073
142074/*
142075** xNext - Advance the cursor to the next row, if any.
142076*/
142077static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
142078  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
142079  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
142080  int rc;
142081
142082  /* Increment our pretend rowid value. */
142083  pCsr->iRowid++;
142084
142085  for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
142086    if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
142087  }
142088
142089  rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
142090  if( rc==SQLITE_ROW ){
142091    int i = 0;
142092    int nDoclist = pCsr->csr.nDoclist;
142093    char *aDoclist = pCsr->csr.aDoclist;
142094    int iCol;
142095
142096    int eState = 0;
142097
142098    if( pCsr->zStop ){
142099      int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
142100      int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
142101      if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
142102        pCsr->isEof = 1;
142103        return SQLITE_OK;
142104      }
142105    }
142106
142107    if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
142108    memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
142109    iCol = 0;
142110
142111    while( i<nDoclist ){
142112      sqlite3_int64 v = 0;
142113
142114      i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
142115      switch( eState ){
142116        /* State 0. In this state the integer just read was a docid. */
142117        case 0:
142118          pCsr->aStat[0].nDoc++;
142119          eState = 1;
142120          iCol = 0;
142121          break;
142122
142123        /* State 1. In this state we are expecting either a 1, indicating
142124        ** that the following integer will be a column number, or the
142125        ** start of a position list for column 0.
142126        **
142127        ** The only difference between state 1 and state 2 is that if the
142128        ** integer encountered in state 1 is not 0 or 1, then we need to
142129        ** increment the column 0 "nDoc" count for this term.
142130        */
142131        case 1:
142132          assert( iCol==0 );
142133          if( v>1 ){
142134            pCsr->aStat[1].nDoc++;
142135          }
142136          eState = 2;
142137          /* fall through */
142138
142139        case 2:
142140          if( v==0 ){       /* 0x00. Next integer will be a docid. */
142141            eState = 0;
142142          }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
142143            eState = 3;
142144          }else{            /* 2 or greater. A position. */
142145            pCsr->aStat[iCol+1].nOcc++;
142146            pCsr->aStat[0].nOcc++;
142147          }
142148          break;
142149
142150        /* State 3. The integer just read is a column number. */
142151        default: assert( eState==3 );
142152          iCol = (int)v;
142153          if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
142154          pCsr->aStat[iCol+1].nDoc++;
142155          eState = 2;
142156          break;
142157      }
142158    }
142159
142160    pCsr->iCol = 0;
142161    rc = SQLITE_OK;
142162  }else{
142163    pCsr->isEof = 1;
142164  }
142165  return rc;
142166}
142167
142168/*
142169** xFilter - Initialize a cursor to point at the start of its data.
142170*/
142171static int fts3auxFilterMethod(
142172  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
142173  int idxNum,                     /* Strategy index */
142174  const char *idxStr,             /* Unused */
142175  int nVal,                       /* Number of elements in apVal */
142176  sqlite3_value **apVal           /* Arguments for the indexing scheme */
142177){
142178  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
142179  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
142180  int rc;
142181  int isScan = 0;
142182  int iLangVal = 0;               /* Language id to query */
142183
142184  int iEq = -1;                   /* Index of term=? value in apVal */
142185  int iGe = -1;                   /* Index of term>=? value in apVal */
142186  int iLe = -1;                   /* Index of term<=? value in apVal */
142187  int iLangid = -1;               /* Index of languageid=? value in apVal */
142188  int iNext = 0;
142189
142190  UNUSED_PARAMETER(nVal);
142191  UNUSED_PARAMETER(idxStr);
142192
142193  assert( idxStr==0 );
142194  assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
142195       || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
142196       || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
142197  );
142198
142199  if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
142200    iEq = iNext++;
142201  }else{
142202    isScan = 1;
142203    if( idxNum & FTS4AUX_GE_CONSTRAINT ){
142204      iGe = iNext++;
142205    }
142206    if( idxNum & FTS4AUX_LE_CONSTRAINT ){
142207      iLe = iNext++;
142208    }
142209  }
142210  if( iNext<nVal ){
142211    iLangid = iNext++;
142212  }
142213
142214  /* In case this cursor is being reused, close and zero it. */
142215  testcase(pCsr->filter.zTerm);
142216  sqlite3Fts3SegReaderFinish(&pCsr->csr);
142217  sqlite3_free((void *)pCsr->filter.zTerm);
142218  sqlite3_free(pCsr->aStat);
142219  memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
142220
142221  pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
142222  if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
142223
142224  if( iEq>=0 || iGe>=0 ){
142225    const unsigned char *zStr = sqlite3_value_text(apVal[0]);
142226    assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
142227    if( zStr ){
142228      pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
142229      pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
142230      if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
142231    }
142232  }
142233
142234  if( iLe>=0 ){
142235    pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
142236    pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
142237    if( pCsr->zStop==0 ) return SQLITE_NOMEM;
142238  }
142239
142240  if( iLangid>=0 ){
142241    iLangVal = sqlite3_value_int(apVal[iLangid]);
142242
142243    /* If the user specified a negative value for the languageid, use zero
142244    ** instead. This works, as the "languageid=?" constraint will also
142245    ** be tested by the VDBE layer. The test will always be false (since
142246    ** this module will not return a row with a negative languageid), and
142247    ** so the overall query will return zero rows.  */
142248    if( iLangVal<0 ) iLangVal = 0;
142249  }
142250  pCsr->iLangid = iLangVal;
142251
142252  rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
142253      pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
142254  );
142255  if( rc==SQLITE_OK ){
142256    rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
142257  }
142258
142259  if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
142260  return rc;
142261}
142262
142263/*
142264** xEof - Return true if the cursor is at EOF, or false otherwise.
142265*/
142266static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
142267  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
142268  return pCsr->isEof;
142269}
142270
142271/*
142272** xColumn - Return a column value.
142273*/
142274static int fts3auxColumnMethod(
142275  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
142276  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
142277  int iCol                        /* Index of column to read value from */
142278){
142279  Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
142280
142281  assert( p->isEof==0 );
142282  switch( iCol ){
142283    case 0: /* term */
142284      sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
142285      break;
142286
142287    case 1: /* col */
142288      if( p->iCol ){
142289        sqlite3_result_int(pCtx, p->iCol-1);
142290      }else{
142291        sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
142292      }
142293      break;
142294
142295    case 2: /* documents */
142296      sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
142297      break;
142298
142299    case 3: /* occurrences */
142300      sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
142301      break;
142302
142303    default: /* languageid */
142304      assert( iCol==4 );
142305      sqlite3_result_int(pCtx, p->iLangid);
142306      break;
142307  }
142308
142309  return SQLITE_OK;
142310}
142311
142312/*
142313** xRowid - Return the current rowid for the cursor.
142314*/
142315static int fts3auxRowidMethod(
142316  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
142317  sqlite_int64 *pRowid            /* OUT: Rowid value */
142318){
142319  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
142320  *pRowid = pCsr->iRowid;
142321  return SQLITE_OK;
142322}
142323
142324/*
142325** Register the fts3aux module with database connection db. Return SQLITE_OK
142326** if successful or an error code if sqlite3_create_module() fails.
142327*/
142328SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
142329  static const sqlite3_module fts3aux_module = {
142330     0,                           /* iVersion      */
142331     fts3auxConnectMethod,        /* xCreate       */
142332     fts3auxConnectMethod,        /* xConnect      */
142333     fts3auxBestIndexMethod,      /* xBestIndex    */
142334     fts3auxDisconnectMethod,     /* xDisconnect   */
142335     fts3auxDisconnectMethod,     /* xDestroy      */
142336     fts3auxOpenMethod,           /* xOpen         */
142337     fts3auxCloseMethod,          /* xClose        */
142338     fts3auxFilterMethod,         /* xFilter       */
142339     fts3auxNextMethod,           /* xNext         */
142340     fts3auxEofMethod,            /* xEof          */
142341     fts3auxColumnMethod,         /* xColumn       */
142342     fts3auxRowidMethod,          /* xRowid        */
142343     0,                           /* xUpdate       */
142344     0,                           /* xBegin        */
142345     0,                           /* xSync         */
142346     0,                           /* xCommit       */
142347     0,                           /* xRollback     */
142348     0,                           /* xFindFunction */
142349     0,                           /* xRename       */
142350     0,                           /* xSavepoint    */
142351     0,                           /* xRelease      */
142352     0                            /* xRollbackTo   */
142353  };
142354  int rc;                         /* Return code */
142355
142356  rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
142357  return rc;
142358}
142359
142360#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
142361
142362/************** End of fts3_aux.c ********************************************/
142363/************** Begin file fts3_expr.c ***************************************/
142364/*
142365** 2008 Nov 28
142366**
142367** The author disclaims copyright to this source code.  In place of
142368** a legal notice, here is a blessing:
142369**
142370**    May you do good and not evil.
142371**    May you find forgiveness for yourself and forgive others.
142372**    May you share freely, never taking more than you give.
142373**
142374******************************************************************************
142375**
142376** This module contains code that implements a parser for fts3 query strings
142377** (the right-hand argument to the MATCH operator). Because the supported
142378** syntax is relatively simple, the whole tokenizer/parser system is
142379** hand-coded.
142380*/
142381/* #include "fts3Int.h" */
142382#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
142383
142384/*
142385** By default, this module parses the legacy syntax that has been
142386** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
142387** is defined, then it uses the new syntax. The differences between
142388** the new and the old syntaxes are:
142389**
142390**  a) The new syntax supports parenthesis. The old does not.
142391**
142392**  b) The new syntax supports the AND and NOT operators. The old does not.
142393**
142394**  c) The old syntax supports the "-" token qualifier. This is not
142395**     supported by the new syntax (it is replaced by the NOT operator).
142396**
142397**  d) When using the old syntax, the OR operator has a greater precedence
142398**     than an implicit AND. When using the new, both implicity and explicit
142399**     AND operators have a higher precedence than OR.
142400**
142401** If compiled with SQLITE_TEST defined, then this module exports the
142402** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
142403** to zero causes the module to use the old syntax. If it is set to
142404** non-zero the new syntax is activated. This is so both syntaxes can
142405** be tested using a single build of testfixture.
142406**
142407** The following describes the syntax supported by the fts3 MATCH
142408** operator in a similar format to that used by the lemon parser
142409** generator. This module does not use actually lemon, it uses a
142410** custom parser.
142411**
142412**   query ::= andexpr (OR andexpr)*.
142413**
142414**   andexpr ::= notexpr (AND? notexpr)*.
142415**
142416**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
142417**   notexpr ::= LP query RP.
142418**
142419**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
142420**
142421**   distance_opt ::= .
142422**   distance_opt ::= / INTEGER.
142423**
142424**   phrase ::= TOKEN.
142425**   phrase ::= COLUMN:TOKEN.
142426**   phrase ::= "TOKEN TOKEN TOKEN...".
142427*/
142428
142429#ifdef SQLITE_TEST
142430SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
142431#else
142432# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
142433#  define sqlite3_fts3_enable_parentheses 1
142434# else
142435#  define sqlite3_fts3_enable_parentheses 0
142436# endif
142437#endif
142438
142439/*
142440** Default span for NEAR operators.
142441*/
142442#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
142443
142444/* #include <string.h> */
142445/* #include <assert.h> */
142446
142447/*
142448** isNot:
142449**   This variable is used by function getNextNode(). When getNextNode() is
142450**   called, it sets ParseContext.isNot to true if the 'next node' is a
142451**   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
142452**   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
142453**   zero.
142454*/
142455typedef struct ParseContext ParseContext;
142456struct ParseContext {
142457  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
142458  int iLangid;                        /* Language id used with tokenizer */
142459  const char **azCol;                 /* Array of column names for fts3 table */
142460  int bFts4;                          /* True to allow FTS4-only syntax */
142461  int nCol;                           /* Number of entries in azCol[] */
142462  int iDefaultCol;                    /* Default column to query */
142463  int isNot;                          /* True if getNextNode() sees a unary - */
142464  sqlite3_context *pCtx;              /* Write error message here */
142465  int nNest;                          /* Number of nested brackets */
142466};
142467
142468/*
142469** This function is equivalent to the standard isspace() function.
142470**
142471** The standard isspace() can be awkward to use safely, because although it
142472** is defined to accept an argument of type int, its behavior when passed
142473** an integer that falls outside of the range of the unsigned char type
142474** is undefined (and sometimes, "undefined" means segfault). This wrapper
142475** is defined to accept an argument of type char, and always returns 0 for
142476** any values that fall outside of the range of the unsigned char type (i.e.
142477** negative values).
142478*/
142479static int fts3isspace(char c){
142480  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
142481}
142482
142483/*
142484** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
142485** zero the memory before returning a pointer to it. If unsuccessful,
142486** return NULL.
142487*/
142488static void *fts3MallocZero(int nByte){
142489  void *pRet = sqlite3_malloc(nByte);
142490  if( pRet ) memset(pRet, 0, nByte);
142491  return pRet;
142492}
142493
142494SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
142495  sqlite3_tokenizer *pTokenizer,
142496  int iLangid,
142497  const char *z,
142498  int n,
142499  sqlite3_tokenizer_cursor **ppCsr
142500){
142501  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
142502  sqlite3_tokenizer_cursor *pCsr = 0;
142503  int rc;
142504
142505  rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
142506  assert( rc==SQLITE_OK || pCsr==0 );
142507  if( rc==SQLITE_OK ){
142508    pCsr->pTokenizer = pTokenizer;
142509    if( pModule->iVersion>=1 ){
142510      rc = pModule->xLanguageid(pCsr, iLangid);
142511      if( rc!=SQLITE_OK ){
142512        pModule->xClose(pCsr);
142513        pCsr = 0;
142514      }
142515    }
142516  }
142517  *ppCsr = pCsr;
142518  return rc;
142519}
142520
142521/*
142522** Function getNextNode(), which is called by fts3ExprParse(), may itself
142523** call fts3ExprParse(). So this forward declaration is required.
142524*/
142525static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
142526
142527/*
142528** Extract the next token from buffer z (length n) using the tokenizer
142529** and other information (column names etc.) in pParse. Create an Fts3Expr
142530** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
142531** single token and set *ppExpr to point to it. If the end of the buffer is
142532** reached before a token is found, set *ppExpr to zero. It is the
142533** responsibility of the caller to eventually deallocate the allocated
142534** Fts3Expr structure (if any) by passing it to sqlite3_free().
142535**
142536** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
142537** fails.
142538*/
142539static int getNextToken(
142540  ParseContext *pParse,                   /* fts3 query parse context */
142541  int iCol,                               /* Value for Fts3Phrase.iColumn */
142542  const char *z, int n,                   /* Input string */
142543  Fts3Expr **ppExpr,                      /* OUT: expression */
142544  int *pnConsumed                         /* OUT: Number of bytes consumed */
142545){
142546  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
142547  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
142548  int rc;
142549  sqlite3_tokenizer_cursor *pCursor;
142550  Fts3Expr *pRet = 0;
142551  int i = 0;
142552
142553  /* Set variable i to the maximum number of bytes of input to tokenize. */
142554  for(i=0; i<n; i++){
142555    if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
142556    if( z[i]=='"' ) break;
142557  }
142558
142559  *pnConsumed = i;
142560  rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
142561  if( rc==SQLITE_OK ){
142562    const char *zToken;
142563    int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
142564    int nByte;                               /* total space to allocate */
142565
142566    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
142567    if( rc==SQLITE_OK ){
142568      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
142569      pRet = (Fts3Expr *)fts3MallocZero(nByte);
142570      if( !pRet ){
142571        rc = SQLITE_NOMEM;
142572      }else{
142573        pRet->eType = FTSQUERY_PHRASE;
142574        pRet->pPhrase = (Fts3Phrase *)&pRet[1];
142575        pRet->pPhrase->nToken = 1;
142576        pRet->pPhrase->iColumn = iCol;
142577        pRet->pPhrase->aToken[0].n = nToken;
142578        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
142579        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
142580
142581        if( iEnd<n && z[iEnd]=='*' ){
142582          pRet->pPhrase->aToken[0].isPrefix = 1;
142583          iEnd++;
142584        }
142585
142586        while( 1 ){
142587          if( !sqlite3_fts3_enable_parentheses
142588           && iStart>0 && z[iStart-1]=='-'
142589          ){
142590            pParse->isNot = 1;
142591            iStart--;
142592          }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
142593            pRet->pPhrase->aToken[0].bFirst = 1;
142594            iStart--;
142595          }else{
142596            break;
142597          }
142598        }
142599
142600      }
142601      *pnConsumed = iEnd;
142602    }else if( i && rc==SQLITE_DONE ){
142603      rc = SQLITE_OK;
142604    }
142605
142606    pModule->xClose(pCursor);
142607  }
142608
142609  *ppExpr = pRet;
142610  return rc;
142611}
142612
142613
142614/*
142615** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
142616** then free the old allocation.
142617*/
142618static void *fts3ReallocOrFree(void *pOrig, int nNew){
142619  void *pRet = sqlite3_realloc(pOrig, nNew);
142620  if( !pRet ){
142621    sqlite3_free(pOrig);
142622  }
142623  return pRet;
142624}
142625
142626/*
142627** Buffer zInput, length nInput, contains the contents of a quoted string
142628** that appeared as part of an fts3 query expression. Neither quote character
142629** is included in the buffer. This function attempts to tokenize the entire
142630** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
142631** containing the results.
142632**
142633** If successful, SQLITE_OK is returned and *ppExpr set to point at the
142634** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
142635** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
142636** to 0.
142637*/
142638static int getNextString(
142639  ParseContext *pParse,                   /* fts3 query parse context */
142640  const char *zInput, int nInput,         /* Input string */
142641  Fts3Expr **ppExpr                       /* OUT: expression */
142642){
142643  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
142644  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
142645  int rc;
142646  Fts3Expr *p = 0;
142647  sqlite3_tokenizer_cursor *pCursor = 0;
142648  char *zTemp = 0;
142649  int nTemp = 0;
142650
142651  const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
142652  int nToken = 0;
142653
142654  /* The final Fts3Expr data structure, including the Fts3Phrase,
142655  ** Fts3PhraseToken structures token buffers are all stored as a single
142656  ** allocation so that the expression can be freed with a single call to
142657  ** sqlite3_free(). Setting this up requires a two pass approach.
142658  **
142659  ** The first pass, in the block below, uses a tokenizer cursor to iterate
142660  ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
142661  ** to assemble data in two dynamic buffers:
142662  **
142663  **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
142664  **             structure, followed by the array of Fts3PhraseToken
142665  **             structures. This pass only populates the Fts3PhraseToken array.
142666  **
142667  **   Buffer zTemp: Contains copies of all tokens.
142668  **
142669  ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
142670  ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
142671  ** structures.
142672  */
142673  rc = sqlite3Fts3OpenTokenizer(
142674      pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
142675  if( rc==SQLITE_OK ){
142676    int ii;
142677    for(ii=0; rc==SQLITE_OK; ii++){
142678      const char *zByte;
142679      int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
142680      rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
142681      if( rc==SQLITE_OK ){
142682        Fts3PhraseToken *pToken;
142683
142684        p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
142685        if( !p ) goto no_mem;
142686
142687        zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
142688        if( !zTemp ) goto no_mem;
142689
142690        assert( nToken==ii );
142691        pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
142692        memset(pToken, 0, sizeof(Fts3PhraseToken));
142693
142694        memcpy(&zTemp[nTemp], zByte, nByte);
142695        nTemp += nByte;
142696
142697        pToken->n = nByte;
142698        pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
142699        pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
142700        nToken = ii+1;
142701      }
142702    }
142703
142704    pModule->xClose(pCursor);
142705    pCursor = 0;
142706  }
142707
142708  if( rc==SQLITE_DONE ){
142709    int jj;
142710    char *zBuf = 0;
142711
142712    p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
142713    if( !p ) goto no_mem;
142714    memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
142715    p->eType = FTSQUERY_PHRASE;
142716    p->pPhrase = (Fts3Phrase *)&p[1];
142717    p->pPhrase->iColumn = pParse->iDefaultCol;
142718    p->pPhrase->nToken = nToken;
142719
142720    zBuf = (char *)&p->pPhrase->aToken[nToken];
142721    if( zTemp ){
142722      memcpy(zBuf, zTemp, nTemp);
142723      sqlite3_free(zTemp);
142724    }else{
142725      assert( nTemp==0 );
142726    }
142727
142728    for(jj=0; jj<p->pPhrase->nToken; jj++){
142729      p->pPhrase->aToken[jj].z = zBuf;
142730      zBuf += p->pPhrase->aToken[jj].n;
142731    }
142732    rc = SQLITE_OK;
142733  }
142734
142735  *ppExpr = p;
142736  return rc;
142737no_mem:
142738
142739  if( pCursor ){
142740    pModule->xClose(pCursor);
142741  }
142742  sqlite3_free(zTemp);
142743  sqlite3_free(p);
142744  *ppExpr = 0;
142745  return SQLITE_NOMEM;
142746}
142747
142748/*
142749** The output variable *ppExpr is populated with an allocated Fts3Expr
142750** structure, or set to 0 if the end of the input buffer is reached.
142751**
142752** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
142753** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
142754** If SQLITE_ERROR is returned, pContext is populated with an error message.
142755*/
142756static int getNextNode(
142757  ParseContext *pParse,                   /* fts3 query parse context */
142758  const char *z, int n,                   /* Input string */
142759  Fts3Expr **ppExpr,                      /* OUT: expression */
142760  int *pnConsumed                         /* OUT: Number of bytes consumed */
142761){
142762  static const struct Fts3Keyword {
142763    char *z;                              /* Keyword text */
142764    unsigned char n;                      /* Length of the keyword */
142765    unsigned char parenOnly;              /* Only valid in paren mode */
142766    unsigned char eType;                  /* Keyword code */
142767  } aKeyword[] = {
142768    { "OR" ,  2, 0, FTSQUERY_OR   },
142769    { "AND",  3, 1, FTSQUERY_AND  },
142770    { "NOT",  3, 1, FTSQUERY_NOT  },
142771    { "NEAR", 4, 0, FTSQUERY_NEAR }
142772  };
142773  int ii;
142774  int iCol;
142775  int iColLen;
142776  int rc;
142777  Fts3Expr *pRet = 0;
142778
142779  const char *zInput = z;
142780  int nInput = n;
142781
142782  pParse->isNot = 0;
142783
142784  /* Skip over any whitespace before checking for a keyword, an open or
142785  ** close bracket, or a quoted string.
142786  */
142787  while( nInput>0 && fts3isspace(*zInput) ){
142788    nInput--;
142789    zInput++;
142790  }
142791  if( nInput==0 ){
142792    return SQLITE_DONE;
142793  }
142794
142795  /* See if we are dealing with a keyword. */
142796  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
142797    const struct Fts3Keyword *pKey = &aKeyword[ii];
142798
142799    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
142800      continue;
142801    }
142802
142803    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
142804      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
142805      int nKey = pKey->n;
142806      char cNext;
142807
142808      /* If this is a "NEAR" keyword, check for an explicit nearness. */
142809      if( pKey->eType==FTSQUERY_NEAR ){
142810        assert( nKey==4 );
142811        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
142812          nNear = 0;
142813          for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
142814            nNear = nNear * 10 + (zInput[nKey] - '0');
142815          }
142816        }
142817      }
142818
142819      /* At this point this is probably a keyword. But for that to be true,
142820      ** the next byte must contain either whitespace, an open or close
142821      ** parenthesis, a quote character, or EOF.
142822      */
142823      cNext = zInput[nKey];
142824      if( fts3isspace(cNext)
142825       || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
142826      ){
142827        pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
142828        if( !pRet ){
142829          return SQLITE_NOMEM;
142830        }
142831        pRet->eType = pKey->eType;
142832        pRet->nNear = nNear;
142833        *ppExpr = pRet;
142834        *pnConsumed = (int)((zInput - z) + nKey);
142835        return SQLITE_OK;
142836      }
142837
142838      /* Turns out that wasn't a keyword after all. This happens if the
142839      ** user has supplied a token such as "ORacle". Continue.
142840      */
142841    }
142842  }
142843
142844  /* See if we are dealing with a quoted phrase. If this is the case, then
142845  ** search for the closing quote and pass the whole string to getNextString()
142846  ** for processing. This is easy to do, as fts3 has no syntax for escaping
142847  ** a quote character embedded in a string.
142848  */
142849  if( *zInput=='"' ){
142850    for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
142851    *pnConsumed = (int)((zInput - z) + ii + 1);
142852    if( ii==nInput ){
142853      return SQLITE_ERROR;
142854    }
142855    return getNextString(pParse, &zInput[1], ii-1, ppExpr);
142856  }
142857
142858  if( sqlite3_fts3_enable_parentheses ){
142859    if( *zInput=='(' ){
142860      int nConsumed = 0;
142861      pParse->nNest++;
142862      rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
142863      if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
142864      *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
142865      return rc;
142866    }else if( *zInput==')' ){
142867      pParse->nNest--;
142868      *pnConsumed = (int)((zInput - z) + 1);
142869      *ppExpr = 0;
142870      return SQLITE_DONE;
142871    }
142872  }
142873
142874  /* If control flows to this point, this must be a regular token, or
142875  ** the end of the input. Read a regular token using the sqlite3_tokenizer
142876  ** interface. Before doing so, figure out if there is an explicit
142877  ** column specifier for the token.
142878  **
142879  ** TODO: Strangely, it is not possible to associate a column specifier
142880  ** with a quoted phrase, only with a single token. Not sure if this was
142881  ** an implementation artifact or an intentional decision when fts3 was
142882  ** first implemented. Whichever it was, this module duplicates the
142883  ** limitation.
142884  */
142885  iCol = pParse->iDefaultCol;
142886  iColLen = 0;
142887  for(ii=0; ii<pParse->nCol; ii++){
142888    const char *zStr = pParse->azCol[ii];
142889    int nStr = (int)strlen(zStr);
142890    if( nInput>nStr && zInput[nStr]==':'
142891     && sqlite3_strnicmp(zStr, zInput, nStr)==0
142892    ){
142893      iCol = ii;
142894      iColLen = (int)((zInput - z) + nStr + 1);
142895      break;
142896    }
142897  }
142898  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
142899  *pnConsumed += iColLen;
142900  return rc;
142901}
142902
142903/*
142904** The argument is an Fts3Expr structure for a binary operator (any type
142905** except an FTSQUERY_PHRASE). Return an integer value representing the
142906** precedence of the operator. Lower values have a higher precedence (i.e.
142907** group more tightly). For example, in the C language, the == operator
142908** groups more tightly than ||, and would therefore have a higher precedence.
142909**
142910** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
142911** is defined), the order of the operators in precedence from highest to
142912** lowest is:
142913**
142914**   NEAR
142915**   NOT
142916**   AND (including implicit ANDs)
142917**   OR
142918**
142919** Note that when using the old query syntax, the OR operator has a higher
142920** precedence than the AND operator.
142921*/
142922static int opPrecedence(Fts3Expr *p){
142923  assert( p->eType!=FTSQUERY_PHRASE );
142924  if( sqlite3_fts3_enable_parentheses ){
142925    return p->eType;
142926  }else if( p->eType==FTSQUERY_NEAR ){
142927    return 1;
142928  }else if( p->eType==FTSQUERY_OR ){
142929    return 2;
142930  }
142931  assert( p->eType==FTSQUERY_AND );
142932  return 3;
142933}
142934
142935/*
142936** Argument ppHead contains a pointer to the current head of a query
142937** expression tree being parsed. pPrev is the expression node most recently
142938** inserted into the tree. This function adds pNew, which is always a binary
142939** operator node, into the expression tree based on the relative precedence
142940** of pNew and the existing nodes of the tree. This may result in the head
142941** of the tree changing, in which case *ppHead is set to the new root node.
142942*/
142943static void insertBinaryOperator(
142944  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
142945  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
142946  Fts3Expr *pNew           /* New binary node to insert into expression tree */
142947){
142948  Fts3Expr *pSplit = pPrev;
142949  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
142950    pSplit = pSplit->pParent;
142951  }
142952
142953  if( pSplit->pParent ){
142954    assert( pSplit->pParent->pRight==pSplit );
142955    pSplit->pParent->pRight = pNew;
142956    pNew->pParent = pSplit->pParent;
142957  }else{
142958    *ppHead = pNew;
142959  }
142960  pNew->pLeft = pSplit;
142961  pSplit->pParent = pNew;
142962}
142963
142964/*
142965** Parse the fts3 query expression found in buffer z, length n. This function
142966** returns either when the end of the buffer is reached or an unmatched
142967** closing bracket - ')' - is encountered.
142968**
142969** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
142970** parsed form of the expression and *pnConsumed is set to the number of
142971** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
142972** (out of memory error) or SQLITE_ERROR (parse error) is returned.
142973*/
142974static int fts3ExprParse(
142975  ParseContext *pParse,                   /* fts3 query parse context */
142976  const char *z, int n,                   /* Text of MATCH query */
142977  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
142978  int *pnConsumed                         /* OUT: Number of bytes consumed */
142979){
142980  Fts3Expr *pRet = 0;
142981  Fts3Expr *pPrev = 0;
142982  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
142983  int nIn = n;
142984  const char *zIn = z;
142985  int rc = SQLITE_OK;
142986  int isRequirePhrase = 1;
142987
142988  while( rc==SQLITE_OK ){
142989    Fts3Expr *p = 0;
142990    int nByte = 0;
142991
142992    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
142993    assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
142994    if( rc==SQLITE_OK ){
142995      if( p ){
142996        int isPhrase;
142997
142998        if( !sqlite3_fts3_enable_parentheses
142999            && p->eType==FTSQUERY_PHRASE && pParse->isNot
143000        ){
143001          /* Create an implicit NOT operator. */
143002          Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
143003          if( !pNot ){
143004            sqlite3Fts3ExprFree(p);
143005            rc = SQLITE_NOMEM;
143006            goto exprparse_out;
143007          }
143008          pNot->eType = FTSQUERY_NOT;
143009          pNot->pRight = p;
143010          p->pParent = pNot;
143011          if( pNotBranch ){
143012            pNot->pLeft = pNotBranch;
143013            pNotBranch->pParent = pNot;
143014          }
143015          pNotBranch = pNot;
143016          p = pPrev;
143017        }else{
143018          int eType = p->eType;
143019          isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
143020
143021          /* The isRequirePhrase variable is set to true if a phrase or
143022          ** an expression contained in parenthesis is required. If a
143023          ** binary operator (AND, OR, NOT or NEAR) is encounted when
143024          ** isRequirePhrase is set, this is a syntax error.
143025          */
143026          if( !isPhrase && isRequirePhrase ){
143027            sqlite3Fts3ExprFree(p);
143028            rc = SQLITE_ERROR;
143029            goto exprparse_out;
143030          }
143031
143032          if( isPhrase && !isRequirePhrase ){
143033            /* Insert an implicit AND operator. */
143034            Fts3Expr *pAnd;
143035            assert( pRet && pPrev );
143036            pAnd = fts3MallocZero(sizeof(Fts3Expr));
143037            if( !pAnd ){
143038              sqlite3Fts3ExprFree(p);
143039              rc = SQLITE_NOMEM;
143040              goto exprparse_out;
143041            }
143042            pAnd->eType = FTSQUERY_AND;
143043            insertBinaryOperator(&pRet, pPrev, pAnd);
143044            pPrev = pAnd;
143045          }
143046
143047          /* This test catches attempts to make either operand of a NEAR
143048           ** operator something other than a phrase. For example, either of
143049           ** the following:
143050           **
143051           **    (bracketed expression) NEAR phrase
143052           **    phrase NEAR (bracketed expression)
143053           **
143054           ** Return an error in either case.
143055           */
143056          if( pPrev && (
143057            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
143058         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
143059          )){
143060            sqlite3Fts3ExprFree(p);
143061            rc = SQLITE_ERROR;
143062            goto exprparse_out;
143063          }
143064
143065          if( isPhrase ){
143066            if( pRet ){
143067              assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
143068              pPrev->pRight = p;
143069              p->pParent = pPrev;
143070            }else{
143071              pRet = p;
143072            }
143073          }else{
143074            insertBinaryOperator(&pRet, pPrev, p);
143075          }
143076          isRequirePhrase = !isPhrase;
143077        }
143078        pPrev = p;
143079      }
143080      assert( nByte>0 );
143081    }
143082    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
143083    nIn -= nByte;
143084    zIn += nByte;
143085  }
143086
143087  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
143088    rc = SQLITE_ERROR;
143089  }
143090
143091  if( rc==SQLITE_DONE ){
143092    rc = SQLITE_OK;
143093    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
143094      if( !pRet ){
143095        rc = SQLITE_ERROR;
143096      }else{
143097        Fts3Expr *pIter = pNotBranch;
143098        while( pIter->pLeft ){
143099          pIter = pIter->pLeft;
143100        }
143101        pIter->pLeft = pRet;
143102        pRet->pParent = pIter;
143103        pRet = pNotBranch;
143104      }
143105    }
143106  }
143107  *pnConsumed = n - nIn;
143108
143109exprparse_out:
143110  if( rc!=SQLITE_OK ){
143111    sqlite3Fts3ExprFree(pRet);
143112    sqlite3Fts3ExprFree(pNotBranch);
143113    pRet = 0;
143114  }
143115  *ppExpr = pRet;
143116  return rc;
143117}
143118
143119/*
143120** Return SQLITE_ERROR if the maximum depth of the expression tree passed
143121** as the only argument is more than nMaxDepth.
143122*/
143123static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
143124  int rc = SQLITE_OK;
143125  if( p ){
143126    if( nMaxDepth<0 ){
143127      rc = SQLITE_TOOBIG;
143128    }else{
143129      rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
143130      if( rc==SQLITE_OK ){
143131        rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
143132      }
143133    }
143134  }
143135  return rc;
143136}
143137
143138/*
143139** This function attempts to transform the expression tree at (*pp) to
143140** an equivalent but more balanced form. The tree is modified in place.
143141** If successful, SQLITE_OK is returned and (*pp) set to point to the
143142** new root expression node.
143143**
143144** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
143145**
143146** Otherwise, if an error occurs, an SQLite error code is returned and
143147** expression (*pp) freed.
143148*/
143149static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
143150  int rc = SQLITE_OK;             /* Return code */
143151  Fts3Expr *pRoot = *pp;          /* Initial root node */
143152  Fts3Expr *pFree = 0;            /* List of free nodes. Linked by pParent. */
143153  int eType = pRoot->eType;       /* Type of node in this tree */
143154
143155  if( nMaxDepth==0 ){
143156    rc = SQLITE_ERROR;
143157  }
143158
143159  if( rc==SQLITE_OK ){
143160    if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
143161      Fts3Expr **apLeaf;
143162      apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
143163      if( 0==apLeaf ){
143164        rc = SQLITE_NOMEM;
143165      }else{
143166        memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
143167      }
143168
143169      if( rc==SQLITE_OK ){
143170        int i;
143171        Fts3Expr *p;
143172
143173        /* Set $p to point to the left-most leaf in the tree of eType nodes. */
143174        for(p=pRoot; p->eType==eType; p=p->pLeft){
143175          assert( p->pParent==0 || p->pParent->pLeft==p );
143176          assert( p->pLeft && p->pRight );
143177        }
143178
143179        /* This loop runs once for each leaf in the tree of eType nodes. */
143180        while( 1 ){
143181          int iLvl;
143182          Fts3Expr *pParent = p->pParent;     /* Current parent of p */
143183
143184          assert( pParent==0 || pParent->pLeft==p );
143185          p->pParent = 0;
143186          if( pParent ){
143187            pParent->pLeft = 0;
143188          }else{
143189            pRoot = 0;
143190          }
143191          rc = fts3ExprBalance(&p, nMaxDepth-1);
143192          if( rc!=SQLITE_OK ) break;
143193
143194          for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
143195            if( apLeaf[iLvl]==0 ){
143196              apLeaf[iLvl] = p;
143197              p = 0;
143198            }else{
143199              assert( pFree );
143200              pFree->pLeft = apLeaf[iLvl];
143201              pFree->pRight = p;
143202              pFree->pLeft->pParent = pFree;
143203              pFree->pRight->pParent = pFree;
143204
143205              p = pFree;
143206              pFree = pFree->pParent;
143207              p->pParent = 0;
143208              apLeaf[iLvl] = 0;
143209            }
143210          }
143211          if( p ){
143212            sqlite3Fts3ExprFree(p);
143213            rc = SQLITE_TOOBIG;
143214            break;
143215          }
143216
143217          /* If that was the last leaf node, break out of the loop */
143218          if( pParent==0 ) break;
143219
143220          /* Set $p to point to the next leaf in the tree of eType nodes */
143221          for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
143222
143223          /* Remove pParent from the original tree. */
143224          assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
143225          pParent->pRight->pParent = pParent->pParent;
143226          if( pParent->pParent ){
143227            pParent->pParent->pLeft = pParent->pRight;
143228          }else{
143229            assert( pParent==pRoot );
143230            pRoot = pParent->pRight;
143231          }
143232
143233          /* Link pParent into the free node list. It will be used as an
143234          ** internal node of the new tree.  */
143235          pParent->pParent = pFree;
143236          pFree = pParent;
143237        }
143238
143239        if( rc==SQLITE_OK ){
143240          p = 0;
143241          for(i=0; i<nMaxDepth; i++){
143242            if( apLeaf[i] ){
143243              if( p==0 ){
143244                p = apLeaf[i];
143245                p->pParent = 0;
143246              }else{
143247                assert( pFree!=0 );
143248                pFree->pRight = p;
143249                pFree->pLeft = apLeaf[i];
143250                pFree->pLeft->pParent = pFree;
143251                pFree->pRight->pParent = pFree;
143252
143253                p = pFree;
143254                pFree = pFree->pParent;
143255                p->pParent = 0;
143256              }
143257            }
143258          }
143259          pRoot = p;
143260        }else{
143261          /* An error occurred. Delete the contents of the apLeaf[] array
143262          ** and pFree list. Everything else is cleaned up by the call to
143263          ** sqlite3Fts3ExprFree(pRoot) below.  */
143264          Fts3Expr *pDel;
143265          for(i=0; i<nMaxDepth; i++){
143266            sqlite3Fts3ExprFree(apLeaf[i]);
143267          }
143268          while( (pDel=pFree)!=0 ){
143269            pFree = pDel->pParent;
143270            sqlite3_free(pDel);
143271          }
143272        }
143273
143274        assert( pFree==0 );
143275        sqlite3_free( apLeaf );
143276      }
143277    }else if( eType==FTSQUERY_NOT ){
143278      Fts3Expr *pLeft = pRoot->pLeft;
143279      Fts3Expr *pRight = pRoot->pRight;
143280
143281      pRoot->pLeft = 0;
143282      pRoot->pRight = 0;
143283      pLeft->pParent = 0;
143284      pRight->pParent = 0;
143285
143286      rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
143287      if( rc==SQLITE_OK ){
143288        rc = fts3ExprBalance(&pRight, nMaxDepth-1);
143289      }
143290
143291      if( rc!=SQLITE_OK ){
143292        sqlite3Fts3ExprFree(pRight);
143293        sqlite3Fts3ExprFree(pLeft);
143294      }else{
143295        assert( pLeft && pRight );
143296        pRoot->pLeft = pLeft;
143297        pLeft->pParent = pRoot;
143298        pRoot->pRight = pRight;
143299        pRight->pParent = pRoot;
143300      }
143301    }
143302  }
143303
143304  if( rc!=SQLITE_OK ){
143305    sqlite3Fts3ExprFree(pRoot);
143306    pRoot = 0;
143307  }
143308  *pp = pRoot;
143309  return rc;
143310}
143311
143312/*
143313** This function is similar to sqlite3Fts3ExprParse(), with the following
143314** differences:
143315**
143316**   1. It does not do expression rebalancing.
143317**   2. It does not check that the expression does not exceed the
143318**      maximum allowable depth.
143319**   3. Even if it fails, *ppExpr may still be set to point to an
143320**      expression tree. It should be deleted using sqlite3Fts3ExprFree()
143321**      in this case.
143322*/
143323static int fts3ExprParseUnbalanced(
143324  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
143325  int iLangid,                        /* Language id for tokenizer */
143326  char **azCol,                       /* Array of column names for fts3 table */
143327  int bFts4,                          /* True to allow FTS4-only syntax */
143328  int nCol,                           /* Number of entries in azCol[] */
143329  int iDefaultCol,                    /* Default column to query */
143330  const char *z, int n,               /* Text of MATCH query */
143331  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
143332){
143333  int nParsed;
143334  int rc;
143335  ParseContext sParse;
143336
143337  memset(&sParse, 0, sizeof(ParseContext));
143338  sParse.pTokenizer = pTokenizer;
143339  sParse.iLangid = iLangid;
143340  sParse.azCol = (const char **)azCol;
143341  sParse.nCol = nCol;
143342  sParse.iDefaultCol = iDefaultCol;
143343  sParse.bFts4 = bFts4;
143344  if( z==0 ){
143345    *ppExpr = 0;
143346    return SQLITE_OK;
143347  }
143348  if( n<0 ){
143349    n = (int)strlen(z);
143350  }
143351  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
143352  assert( rc==SQLITE_OK || *ppExpr==0 );
143353
143354  /* Check for mismatched parenthesis */
143355  if( rc==SQLITE_OK && sParse.nNest ){
143356    rc = SQLITE_ERROR;
143357  }
143358
143359  return rc;
143360}
143361
143362/*
143363** Parameters z and n contain a pointer to and length of a buffer containing
143364** an fts3 query expression, respectively. This function attempts to parse the
143365** query expression and create a tree of Fts3Expr structures representing the
143366** parsed expression. If successful, *ppExpr is set to point to the head
143367** of the parsed expression tree and SQLITE_OK is returned. If an error
143368** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
143369** error) is returned and *ppExpr is set to 0.
143370**
143371** If parameter n is a negative number, then z is assumed to point to a
143372** nul-terminated string and the length is determined using strlen().
143373**
143374** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
143375** use to normalize query tokens while parsing the expression. The azCol[]
143376** array, which is assumed to contain nCol entries, should contain the names
143377** of each column in the target fts3 table, in order from left to right.
143378** Column names must be nul-terminated strings.
143379**
143380** The iDefaultCol parameter should be passed the index of the table column
143381** that appears on the left-hand-side of the MATCH operator (the default
143382** column to match against for tokens for which a column name is not explicitly
143383** specified as part of the query string), or -1 if tokens may by default
143384** match any table column.
143385*/
143386SQLITE_PRIVATE int sqlite3Fts3ExprParse(
143387  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
143388  int iLangid,                        /* Language id for tokenizer */
143389  char **azCol,                       /* Array of column names for fts3 table */
143390  int bFts4,                          /* True to allow FTS4-only syntax */
143391  int nCol,                           /* Number of entries in azCol[] */
143392  int iDefaultCol,                    /* Default column to query */
143393  const char *z, int n,               /* Text of MATCH query */
143394  Fts3Expr **ppExpr,                  /* OUT: Parsed query structure */
143395  char **pzErr                        /* OUT: Error message (sqlite3_malloc) */
143396){
143397  int rc = fts3ExprParseUnbalanced(
143398      pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
143399  );
143400
143401  /* Rebalance the expression. And check that its depth does not exceed
143402  ** SQLITE_FTS3_MAX_EXPR_DEPTH.  */
143403  if( rc==SQLITE_OK && *ppExpr ){
143404    rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
143405    if( rc==SQLITE_OK ){
143406      rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
143407    }
143408  }
143409
143410  if( rc!=SQLITE_OK ){
143411    sqlite3Fts3ExprFree(*ppExpr);
143412    *ppExpr = 0;
143413    if( rc==SQLITE_TOOBIG ){
143414      sqlite3Fts3ErrMsg(pzErr,
143415          "FTS expression tree is too large (maximum depth %d)",
143416          SQLITE_FTS3_MAX_EXPR_DEPTH
143417      );
143418      rc = SQLITE_ERROR;
143419    }else if( rc==SQLITE_ERROR ){
143420      sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
143421    }
143422  }
143423
143424  return rc;
143425}
143426
143427/*
143428** Free a single node of an expression tree.
143429*/
143430static void fts3FreeExprNode(Fts3Expr *p){
143431  assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
143432  sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
143433  sqlite3_free(p->aMI);
143434  sqlite3_free(p);
143435}
143436
143437/*
143438** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
143439**
143440** This function would be simpler if it recursively called itself. But
143441** that would mean passing a sufficiently large expression to ExprParse()
143442** could cause a stack overflow.
143443*/
143444SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
143445  Fts3Expr *p;
143446  assert( pDel==0 || pDel->pParent==0 );
143447  for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
143448    assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
143449  }
143450  while( p ){
143451    Fts3Expr *pParent = p->pParent;
143452    fts3FreeExprNode(p);
143453    if( pParent && p==pParent->pLeft && pParent->pRight ){
143454      p = pParent->pRight;
143455      while( p && (p->pLeft || p->pRight) ){
143456        assert( p==p->pParent->pRight || p==p->pParent->pLeft );
143457        p = (p->pLeft ? p->pLeft : p->pRight);
143458      }
143459    }else{
143460      p = pParent;
143461    }
143462  }
143463}
143464
143465/****************************************************************************
143466*****************************************************************************
143467** Everything after this point is just test code.
143468*/
143469
143470#ifdef SQLITE_TEST
143471
143472/* #include <stdio.h> */
143473
143474/*
143475** Function to query the hash-table of tokenizers (see README.tokenizers).
143476*/
143477static int queryTestTokenizer(
143478  sqlite3 *db,
143479  const char *zName,
143480  const sqlite3_tokenizer_module **pp
143481){
143482  int rc;
143483  sqlite3_stmt *pStmt;
143484  const char zSql[] = "SELECT fts3_tokenizer(?)";
143485
143486  *pp = 0;
143487  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
143488  if( rc!=SQLITE_OK ){
143489    return rc;
143490  }
143491
143492  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
143493  if( SQLITE_ROW==sqlite3_step(pStmt) ){
143494    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
143495      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
143496    }
143497  }
143498
143499  return sqlite3_finalize(pStmt);
143500}
143501
143502/*
143503** Return a pointer to a buffer containing a text representation of the
143504** expression passed as the first argument. The buffer is obtained from
143505** sqlite3_malloc(). It is the responsibility of the caller to use
143506** sqlite3_free() to release the memory. If an OOM condition is encountered,
143507** NULL is returned.
143508**
143509** If the second argument is not NULL, then its contents are prepended to
143510** the returned expression text and then freed using sqlite3_free().
143511*/
143512static char *exprToString(Fts3Expr *pExpr, char *zBuf){
143513  if( pExpr==0 ){
143514    return sqlite3_mprintf("");
143515  }
143516  switch( pExpr->eType ){
143517    case FTSQUERY_PHRASE: {
143518      Fts3Phrase *pPhrase = pExpr->pPhrase;
143519      int i;
143520      zBuf = sqlite3_mprintf(
143521          "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
143522      for(i=0; zBuf && i<pPhrase->nToken; i++){
143523        zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
143524            pPhrase->aToken[i].n, pPhrase->aToken[i].z,
143525            (pPhrase->aToken[i].isPrefix?"+":"")
143526        );
143527      }
143528      return zBuf;
143529    }
143530
143531    case FTSQUERY_NEAR:
143532      zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
143533      break;
143534    case FTSQUERY_NOT:
143535      zBuf = sqlite3_mprintf("%zNOT ", zBuf);
143536      break;
143537    case FTSQUERY_AND:
143538      zBuf = sqlite3_mprintf("%zAND ", zBuf);
143539      break;
143540    case FTSQUERY_OR:
143541      zBuf = sqlite3_mprintf("%zOR ", zBuf);
143542      break;
143543  }
143544
143545  if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
143546  if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
143547  if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
143548
143549  if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
143550  if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
143551
143552  return zBuf;
143553}
143554
143555/*
143556** This is the implementation of a scalar SQL function used to test the
143557** expression parser. It should be called as follows:
143558**
143559**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
143560**
143561** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
143562** to parse the query expression (see README.tokenizers). The second argument
143563** is the query expression to parse. Each subsequent argument is the name
143564** of a column of the fts3 table that the query expression may refer to.
143565** For example:
143566**
143567**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
143568*/
143569static void fts3ExprTest(
143570  sqlite3_context *context,
143571  int argc,
143572  sqlite3_value **argv
143573){
143574  sqlite3_tokenizer_module const *pModule = 0;
143575  sqlite3_tokenizer *pTokenizer = 0;
143576  int rc;
143577  char **azCol = 0;
143578  const char *zExpr;
143579  int nExpr;
143580  int nCol;
143581  int ii;
143582  Fts3Expr *pExpr;
143583  char *zBuf = 0;
143584  sqlite3 *db = sqlite3_context_db_handle(context);
143585
143586  if( argc<3 ){
143587    sqlite3_result_error(context,
143588        "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
143589    );
143590    return;
143591  }
143592
143593  rc = queryTestTokenizer(db,
143594                          (const char *)sqlite3_value_text(argv[0]), &pModule);
143595  if( rc==SQLITE_NOMEM ){
143596    sqlite3_result_error_nomem(context);
143597    goto exprtest_out;
143598  }else if( !pModule ){
143599    sqlite3_result_error(context, "No such tokenizer module", -1);
143600    goto exprtest_out;
143601  }
143602
143603  rc = pModule->xCreate(0, 0, &pTokenizer);
143604  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
143605  if( rc==SQLITE_NOMEM ){
143606    sqlite3_result_error_nomem(context);
143607    goto exprtest_out;
143608  }
143609  pTokenizer->pModule = pModule;
143610
143611  zExpr = (const char *)sqlite3_value_text(argv[1]);
143612  nExpr = sqlite3_value_bytes(argv[1]);
143613  nCol = argc-2;
143614  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
143615  if( !azCol ){
143616    sqlite3_result_error_nomem(context);
143617    goto exprtest_out;
143618  }
143619  for(ii=0; ii<nCol; ii++){
143620    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
143621  }
143622
143623  if( sqlite3_user_data(context) ){
143624    char *zDummy = 0;
143625    rc = sqlite3Fts3ExprParse(
143626        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
143627    );
143628    assert( rc==SQLITE_OK || pExpr==0 );
143629    sqlite3_free(zDummy);
143630  }else{
143631    rc = fts3ExprParseUnbalanced(
143632        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
143633    );
143634  }
143635
143636  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
143637    sqlite3Fts3ExprFree(pExpr);
143638    sqlite3_result_error(context, "Error parsing expression", -1);
143639  }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
143640    sqlite3_result_error_nomem(context);
143641  }else{
143642    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
143643    sqlite3_free(zBuf);
143644  }
143645
143646  sqlite3Fts3ExprFree(pExpr);
143647
143648exprtest_out:
143649  if( pModule && pTokenizer ){
143650    rc = pModule->xDestroy(pTokenizer);
143651  }
143652  sqlite3_free(azCol);
143653}
143654
143655/*
143656** Register the query expression parser test function fts3_exprtest()
143657** with database connection db.
143658*/
143659SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
143660  int rc = sqlite3_create_function(
143661      db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
143662  );
143663  if( rc==SQLITE_OK ){
143664    rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
143665        -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
143666    );
143667  }
143668  return rc;
143669}
143670
143671#endif
143672#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
143673
143674/************** End of fts3_expr.c *******************************************/
143675/************** Begin file fts3_hash.c ***************************************/
143676/*
143677** 2001 September 22
143678**
143679** The author disclaims copyright to this source code.  In place of
143680** a legal notice, here is a blessing:
143681**
143682**    May you do good and not evil.
143683**    May you find forgiveness for yourself and forgive others.
143684**    May you share freely, never taking more than you give.
143685**
143686*************************************************************************
143687** This is the implementation of generic hash-tables used in SQLite.
143688** We've modified it slightly to serve as a standalone hash table
143689** implementation for the full-text indexing module.
143690*/
143691
143692/*
143693** The code in this file is only compiled if:
143694**
143695**     * The FTS3 module is being built as an extension
143696**       (in which case SQLITE_CORE is not defined), or
143697**
143698**     * The FTS3 module is being built into the core of
143699**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
143700*/
143701/* #include "fts3Int.h" */
143702#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
143703
143704/* #include <assert.h> */
143705/* #include <stdlib.h> */
143706/* #include <string.h> */
143707
143708/* #include "fts3_hash.h" */
143709
143710/*
143711** Malloc and Free functions
143712*/
143713static void *fts3HashMalloc(int n){
143714  void *p = sqlite3_malloc(n);
143715  if( p ){
143716    memset(p, 0, n);
143717  }
143718  return p;
143719}
143720static void fts3HashFree(void *p){
143721  sqlite3_free(p);
143722}
143723
143724/* Turn bulk memory into a hash table object by initializing the
143725** fields of the Hash structure.
143726**
143727** "pNew" is a pointer to the hash table that is to be initialized.
143728** keyClass is one of the constants
143729** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
143730** determines what kind of key the hash table will use.  "copyKey" is
143731** true if the hash table should make its own private copy of keys and
143732** false if it should just use the supplied pointer.
143733*/
143734SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
143735  assert( pNew!=0 );
143736  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
143737  pNew->keyClass = keyClass;
143738  pNew->copyKey = copyKey;
143739  pNew->first = 0;
143740  pNew->count = 0;
143741  pNew->htsize = 0;
143742  pNew->ht = 0;
143743}
143744
143745/* Remove all entries from a hash table.  Reclaim all memory.
143746** Call this routine to delete a hash table or to reset a hash table
143747** to the empty state.
143748*/
143749SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
143750  Fts3HashElem *elem;         /* For looping over all elements of the table */
143751
143752  assert( pH!=0 );
143753  elem = pH->first;
143754  pH->first = 0;
143755  fts3HashFree(pH->ht);
143756  pH->ht = 0;
143757  pH->htsize = 0;
143758  while( elem ){
143759    Fts3HashElem *next_elem = elem->next;
143760    if( pH->copyKey && elem->pKey ){
143761      fts3HashFree(elem->pKey);
143762    }
143763    fts3HashFree(elem);
143764    elem = next_elem;
143765  }
143766  pH->count = 0;
143767}
143768
143769/*
143770** Hash and comparison functions when the mode is FTS3_HASH_STRING
143771*/
143772static int fts3StrHash(const void *pKey, int nKey){
143773  const char *z = (const char *)pKey;
143774  unsigned h = 0;
143775  if( nKey<=0 ) nKey = (int) strlen(z);
143776  while( nKey > 0  ){
143777    h = (h<<3) ^ h ^ *z++;
143778    nKey--;
143779  }
143780  return (int)(h & 0x7fffffff);
143781}
143782static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
143783  if( n1!=n2 ) return 1;
143784  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
143785}
143786
143787/*
143788** Hash and comparison functions when the mode is FTS3_HASH_BINARY
143789*/
143790static int fts3BinHash(const void *pKey, int nKey){
143791  int h = 0;
143792  const char *z = (const char *)pKey;
143793  while( nKey-- > 0 ){
143794    h = (h<<3) ^ h ^ *(z++);
143795  }
143796  return h & 0x7fffffff;
143797}
143798static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
143799  if( n1!=n2 ) return 1;
143800  return memcmp(pKey1,pKey2,n1);
143801}
143802
143803/*
143804** Return a pointer to the appropriate hash function given the key class.
143805**
143806** The C syntax in this function definition may be unfamilar to some
143807** programmers, so we provide the following additional explanation:
143808**
143809** The name of the function is "ftsHashFunction".  The function takes a
143810** single parameter "keyClass".  The return value of ftsHashFunction()
143811** is a pointer to another function.  Specifically, the return value
143812** of ftsHashFunction() is a pointer to a function that takes two parameters
143813** with types "const void*" and "int" and returns an "int".
143814*/
143815static int (*ftsHashFunction(int keyClass))(const void*,int){
143816  if( keyClass==FTS3_HASH_STRING ){
143817    return &fts3StrHash;
143818  }else{
143819    assert( keyClass==FTS3_HASH_BINARY );
143820    return &fts3BinHash;
143821  }
143822}
143823
143824/*
143825** Return a pointer to the appropriate hash function given the key class.
143826**
143827** For help in interpreted the obscure C code in the function definition,
143828** see the header comment on the previous function.
143829*/
143830static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
143831  if( keyClass==FTS3_HASH_STRING ){
143832    return &fts3StrCompare;
143833  }else{
143834    assert( keyClass==FTS3_HASH_BINARY );
143835    return &fts3BinCompare;
143836  }
143837}
143838
143839/* Link an element into the hash table
143840*/
143841static void fts3HashInsertElement(
143842  Fts3Hash *pH,            /* The complete hash table */
143843  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
143844  Fts3HashElem *pNew       /* The element to be inserted */
143845){
143846  Fts3HashElem *pHead;     /* First element already in pEntry */
143847  pHead = pEntry->chain;
143848  if( pHead ){
143849    pNew->next = pHead;
143850    pNew->prev = pHead->prev;
143851    if( pHead->prev ){ pHead->prev->next = pNew; }
143852    else             { pH->first = pNew; }
143853    pHead->prev = pNew;
143854  }else{
143855    pNew->next = pH->first;
143856    if( pH->first ){ pH->first->prev = pNew; }
143857    pNew->prev = 0;
143858    pH->first = pNew;
143859  }
143860  pEntry->count++;
143861  pEntry->chain = pNew;
143862}
143863
143864
143865/* Resize the hash table so that it cantains "new_size" buckets.
143866** "new_size" must be a power of 2.  The hash table might fail
143867** to resize if sqliteMalloc() fails.
143868**
143869** Return non-zero if a memory allocation error occurs.
143870*/
143871static int fts3Rehash(Fts3Hash *pH, int new_size){
143872  struct _fts3ht *new_ht;          /* The new hash table */
143873  Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
143874  int (*xHash)(const void*,int);   /* The hash function */
143875
143876  assert( (new_size & (new_size-1))==0 );
143877  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
143878  if( new_ht==0 ) return 1;
143879  fts3HashFree(pH->ht);
143880  pH->ht = new_ht;
143881  pH->htsize = new_size;
143882  xHash = ftsHashFunction(pH->keyClass);
143883  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
143884    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
143885    next_elem = elem->next;
143886    fts3HashInsertElement(pH, &new_ht[h], elem);
143887  }
143888  return 0;
143889}
143890
143891/* This function (for internal use only) locates an element in an
143892** hash table that matches the given key.  The hash for this key has
143893** already been computed and is passed as the 4th parameter.
143894*/
143895static Fts3HashElem *fts3FindElementByHash(
143896  const Fts3Hash *pH, /* The pH to be searched */
143897  const void *pKey,   /* The key we are searching for */
143898  int nKey,
143899  int h               /* The hash for this key. */
143900){
143901  Fts3HashElem *elem;            /* Used to loop thru the element list */
143902  int count;                     /* Number of elements left to test */
143903  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
143904
143905  if( pH->ht ){
143906    struct _fts3ht *pEntry = &pH->ht[h];
143907    elem = pEntry->chain;
143908    count = pEntry->count;
143909    xCompare = ftsCompareFunction(pH->keyClass);
143910    while( count-- && elem ){
143911      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
143912        return elem;
143913      }
143914      elem = elem->next;
143915    }
143916  }
143917  return 0;
143918}
143919
143920/* Remove a single entry from the hash table given a pointer to that
143921** element and a hash on the element's key.
143922*/
143923static void fts3RemoveElementByHash(
143924  Fts3Hash *pH,         /* The pH containing "elem" */
143925  Fts3HashElem* elem,   /* The element to be removed from the pH */
143926  int h                 /* Hash value for the element */
143927){
143928  struct _fts3ht *pEntry;
143929  if( elem->prev ){
143930    elem->prev->next = elem->next;
143931  }else{
143932    pH->first = elem->next;
143933  }
143934  if( elem->next ){
143935    elem->next->prev = elem->prev;
143936  }
143937  pEntry = &pH->ht[h];
143938  if( pEntry->chain==elem ){
143939    pEntry->chain = elem->next;
143940  }
143941  pEntry->count--;
143942  if( pEntry->count<=0 ){
143943    pEntry->chain = 0;
143944  }
143945  if( pH->copyKey && elem->pKey ){
143946    fts3HashFree(elem->pKey);
143947  }
143948  fts3HashFree( elem );
143949  pH->count--;
143950  if( pH->count<=0 ){
143951    assert( pH->first==0 );
143952    assert( pH->count==0 );
143953    fts3HashClear(pH);
143954  }
143955}
143956
143957SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
143958  const Fts3Hash *pH,
143959  const void *pKey,
143960  int nKey
143961){
143962  int h;                          /* A hash on key */
143963  int (*xHash)(const void*,int);  /* The hash function */
143964
143965  if( pH==0 || pH->ht==0 ) return 0;
143966  xHash = ftsHashFunction(pH->keyClass);
143967  assert( xHash!=0 );
143968  h = (*xHash)(pKey,nKey);
143969  assert( (pH->htsize & (pH->htsize-1))==0 );
143970  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
143971}
143972
143973/*
143974** Attempt to locate an element of the hash table pH with a key
143975** that matches pKey,nKey.  Return the data for this element if it is
143976** found, or NULL if there is no match.
143977*/
143978SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
143979  Fts3HashElem *pElem;            /* The element that matches key (if any) */
143980
143981  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
143982  return pElem ? pElem->data : 0;
143983}
143984
143985/* Insert an element into the hash table pH.  The key is pKey,nKey
143986** and the data is "data".
143987**
143988** If no element exists with a matching key, then a new
143989** element is created.  A copy of the key is made if the copyKey
143990** flag is set.  NULL is returned.
143991**
143992** If another element already exists with the same key, then the
143993** new data replaces the old data and the old data is returned.
143994** The key is not copied in this instance.  If a malloc fails, then
143995** the new data is returned and the hash table is unchanged.
143996**
143997** If the "data" parameter to this function is NULL, then the
143998** element corresponding to "key" is removed from the hash table.
143999*/
144000SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
144001  Fts3Hash *pH,        /* The hash table to insert into */
144002  const void *pKey,    /* The key */
144003  int nKey,            /* Number of bytes in the key */
144004  void *data           /* The data */
144005){
144006  int hraw;                 /* Raw hash value of the key */
144007  int h;                    /* the hash of the key modulo hash table size */
144008  Fts3HashElem *elem;       /* Used to loop thru the element list */
144009  Fts3HashElem *new_elem;   /* New element added to the pH */
144010  int (*xHash)(const void*,int);  /* The hash function */
144011
144012  assert( pH!=0 );
144013  xHash = ftsHashFunction(pH->keyClass);
144014  assert( xHash!=0 );
144015  hraw = (*xHash)(pKey, nKey);
144016  assert( (pH->htsize & (pH->htsize-1))==0 );
144017  h = hraw & (pH->htsize-1);
144018  elem = fts3FindElementByHash(pH,pKey,nKey,h);
144019  if( elem ){
144020    void *old_data = elem->data;
144021    if( data==0 ){
144022      fts3RemoveElementByHash(pH,elem,h);
144023    }else{
144024      elem->data = data;
144025    }
144026    return old_data;
144027  }
144028  if( data==0 ) return 0;
144029  if( (pH->htsize==0 && fts3Rehash(pH,8))
144030   || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
144031  ){
144032    pH->count = 0;
144033    return data;
144034  }
144035  assert( pH->htsize>0 );
144036  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
144037  if( new_elem==0 ) return data;
144038  if( pH->copyKey && pKey!=0 ){
144039    new_elem->pKey = fts3HashMalloc( nKey );
144040    if( new_elem->pKey==0 ){
144041      fts3HashFree(new_elem);
144042      return data;
144043    }
144044    memcpy((void*)new_elem->pKey, pKey, nKey);
144045  }else{
144046    new_elem->pKey = (void*)pKey;
144047  }
144048  new_elem->nKey = nKey;
144049  pH->count++;
144050  assert( pH->htsize>0 );
144051  assert( (pH->htsize & (pH->htsize-1))==0 );
144052  h = hraw & (pH->htsize-1);
144053  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
144054  new_elem->data = data;
144055  return 0;
144056}
144057
144058#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
144059
144060/************** End of fts3_hash.c *******************************************/
144061/************** Begin file fts3_porter.c *************************************/
144062/*
144063** 2006 September 30
144064**
144065** The author disclaims copyright to this source code.  In place of
144066** a legal notice, here is a blessing:
144067**
144068**    May you do good and not evil.
144069**    May you find forgiveness for yourself and forgive others.
144070**    May you share freely, never taking more than you give.
144071**
144072*************************************************************************
144073** Implementation of the full-text-search tokenizer that implements
144074** a Porter stemmer.
144075*/
144076
144077/*
144078** The code in this file is only compiled if:
144079**
144080**     * The FTS3 module is being built as an extension
144081**       (in which case SQLITE_CORE is not defined), or
144082**
144083**     * The FTS3 module is being built into the core of
144084**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
144085*/
144086/* #include "fts3Int.h" */
144087#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
144088
144089/* #include <assert.h> */
144090/* #include <stdlib.h> */
144091/* #include <stdio.h> */
144092/* #include <string.h> */
144093
144094/* #include "fts3_tokenizer.h" */
144095
144096/*
144097** Class derived from sqlite3_tokenizer
144098*/
144099typedef struct porter_tokenizer {
144100  sqlite3_tokenizer base;      /* Base class */
144101} porter_tokenizer;
144102
144103/*
144104** Class derived from sqlite3_tokenizer_cursor
144105*/
144106typedef struct porter_tokenizer_cursor {
144107  sqlite3_tokenizer_cursor base;
144108  const char *zInput;          /* input we are tokenizing */
144109  int nInput;                  /* size of the input */
144110  int iOffset;                 /* current position in zInput */
144111  int iToken;                  /* index of next token to be returned */
144112  char *zToken;                /* storage for current token */
144113  int nAllocated;              /* space allocated to zToken buffer */
144114} porter_tokenizer_cursor;
144115
144116
144117/*
144118** Create a new tokenizer instance.
144119*/
144120static int porterCreate(
144121  int argc, const char * const *argv,
144122  sqlite3_tokenizer **ppTokenizer
144123){
144124  porter_tokenizer *t;
144125
144126  UNUSED_PARAMETER(argc);
144127  UNUSED_PARAMETER(argv);
144128
144129  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
144130  if( t==NULL ) return SQLITE_NOMEM;
144131  memset(t, 0, sizeof(*t));
144132  *ppTokenizer = &t->base;
144133  return SQLITE_OK;
144134}
144135
144136/*
144137** Destroy a tokenizer
144138*/
144139static int porterDestroy(sqlite3_tokenizer *pTokenizer){
144140  sqlite3_free(pTokenizer);
144141  return SQLITE_OK;
144142}
144143
144144/*
144145** Prepare to begin tokenizing a particular string.  The input
144146** string to be tokenized is zInput[0..nInput-1].  A cursor
144147** used to incrementally tokenize this string is returned in
144148** *ppCursor.
144149*/
144150static int porterOpen(
144151  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
144152  const char *zInput, int nInput,        /* String to be tokenized */
144153  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
144154){
144155  porter_tokenizer_cursor *c;
144156
144157  UNUSED_PARAMETER(pTokenizer);
144158
144159  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
144160  if( c==NULL ) return SQLITE_NOMEM;
144161
144162  c->zInput = zInput;
144163  if( zInput==0 ){
144164    c->nInput = 0;
144165  }else if( nInput<0 ){
144166    c->nInput = (int)strlen(zInput);
144167  }else{
144168    c->nInput = nInput;
144169  }
144170  c->iOffset = 0;                 /* start tokenizing at the beginning */
144171  c->iToken = 0;
144172  c->zToken = NULL;               /* no space allocated, yet. */
144173  c->nAllocated = 0;
144174
144175  *ppCursor = &c->base;
144176  return SQLITE_OK;
144177}
144178
144179/*
144180** Close a tokenization cursor previously opened by a call to
144181** porterOpen() above.
144182*/
144183static int porterClose(sqlite3_tokenizer_cursor *pCursor){
144184  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
144185  sqlite3_free(c->zToken);
144186  sqlite3_free(c);
144187  return SQLITE_OK;
144188}
144189/*
144190** Vowel or consonant
144191*/
144192static const char cType[] = {
144193   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
144194   1, 1, 1, 2, 1
144195};
144196
144197/*
144198** isConsonant() and isVowel() determine if their first character in
144199** the string they point to is a consonant or a vowel, according
144200** to Porter ruls.
144201**
144202** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
144203** 'Y' is a consonant unless it follows another consonant,
144204** in which case it is a vowel.
144205**
144206** In these routine, the letters are in reverse order.  So the 'y' rule
144207** is that 'y' is a consonant unless it is followed by another
144208** consonent.
144209*/
144210static int isVowel(const char*);
144211static int isConsonant(const char *z){
144212  int j;
144213  char x = *z;
144214  if( x==0 ) return 0;
144215  assert( x>='a' && x<='z' );
144216  j = cType[x-'a'];
144217  if( j<2 ) return j;
144218  return z[1]==0 || isVowel(z + 1);
144219}
144220static int isVowel(const char *z){
144221  int j;
144222  char x = *z;
144223  if( x==0 ) return 0;
144224  assert( x>='a' && x<='z' );
144225  j = cType[x-'a'];
144226  if( j<2 ) return 1-j;
144227  return isConsonant(z + 1);
144228}
144229
144230/*
144231** Let any sequence of one or more vowels be represented by V and let
144232** C be sequence of one or more consonants.  Then every word can be
144233** represented as:
144234**
144235**           [C] (VC){m} [V]
144236**
144237** In prose:  A word is an optional consonant followed by zero or
144238** vowel-consonant pairs followed by an optional vowel.  "m" is the
144239** number of vowel consonant pairs.  This routine computes the value
144240** of m for the first i bytes of a word.
144241**
144242** Return true if the m-value for z is 1 or more.  In other words,
144243** return true if z contains at least one vowel that is followed
144244** by a consonant.
144245**
144246** In this routine z[] is in reverse order.  So we are really looking
144247** for an instance of a consonant followed by a vowel.
144248*/
144249static int m_gt_0(const char *z){
144250  while( isVowel(z) ){ z++; }
144251  if( *z==0 ) return 0;
144252  while( isConsonant(z) ){ z++; }
144253  return *z!=0;
144254}
144255
144256/* Like mgt0 above except we are looking for a value of m which is
144257** exactly 1
144258*/
144259static int m_eq_1(const char *z){
144260  while( isVowel(z) ){ z++; }
144261  if( *z==0 ) return 0;
144262  while( isConsonant(z) ){ z++; }
144263  if( *z==0 ) return 0;
144264  while( isVowel(z) ){ z++; }
144265  if( *z==0 ) return 1;
144266  while( isConsonant(z) ){ z++; }
144267  return *z==0;
144268}
144269
144270/* Like mgt0 above except we are looking for a value of m>1 instead
144271** or m>0
144272*/
144273static int m_gt_1(const char *z){
144274  while( isVowel(z) ){ z++; }
144275  if( *z==0 ) return 0;
144276  while( isConsonant(z) ){ z++; }
144277  if( *z==0 ) return 0;
144278  while( isVowel(z) ){ z++; }
144279  if( *z==0 ) return 0;
144280  while( isConsonant(z) ){ z++; }
144281  return *z!=0;
144282}
144283
144284/*
144285** Return TRUE if there is a vowel anywhere within z[0..n-1]
144286*/
144287static int hasVowel(const char *z){
144288  while( isConsonant(z) ){ z++; }
144289  return *z!=0;
144290}
144291
144292/*
144293** Return TRUE if the word ends in a double consonant.
144294**
144295** The text is reversed here. So we are really looking at
144296** the first two characters of z[].
144297*/
144298static int doubleConsonant(const char *z){
144299  return isConsonant(z) && z[0]==z[1];
144300}
144301
144302/*
144303** Return TRUE if the word ends with three letters which
144304** are consonant-vowel-consonent and where the final consonant
144305** is not 'w', 'x', or 'y'.
144306**
144307** The word is reversed here.  So we are really checking the
144308** first three letters and the first one cannot be in [wxy].
144309*/
144310static int star_oh(const char *z){
144311  return
144312    isConsonant(z) &&
144313    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
144314    isVowel(z+1) &&
144315    isConsonant(z+2);
144316}
144317
144318/*
144319** If the word ends with zFrom and xCond() is true for the stem
144320** of the word that preceeds the zFrom ending, then change the
144321** ending to zTo.
144322**
144323** The input word *pz and zFrom are both in reverse order.  zTo
144324** is in normal order.
144325**
144326** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
144327** match.  Not that TRUE is returned even if xCond() fails and
144328** no substitution occurs.
144329*/
144330static int stem(
144331  char **pz,             /* The word being stemmed (Reversed) */
144332  const char *zFrom,     /* If the ending matches this... (Reversed) */
144333  const char *zTo,       /* ... change the ending to this (not reversed) */
144334  int (*xCond)(const char*)   /* Condition that must be true */
144335){
144336  char *z = *pz;
144337  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
144338  if( *zFrom!=0 ) return 0;
144339  if( xCond && !xCond(z) ) return 1;
144340  while( *zTo ){
144341    *(--z) = *(zTo++);
144342  }
144343  *pz = z;
144344  return 1;
144345}
144346
144347/*
144348** This is the fallback stemmer used when the porter stemmer is
144349** inappropriate.  The input word is copied into the output with
144350** US-ASCII case folding.  If the input word is too long (more
144351** than 20 bytes if it contains no digits or more than 6 bytes if
144352** it contains digits) then word is truncated to 20 or 6 bytes
144353** by taking 10 or 3 bytes from the beginning and end.
144354*/
144355static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
144356  int i, mx, j;
144357  int hasDigit = 0;
144358  for(i=0; i<nIn; i++){
144359    char c = zIn[i];
144360    if( c>='A' && c<='Z' ){
144361      zOut[i] = c - 'A' + 'a';
144362    }else{
144363      if( c>='0' && c<='9' ) hasDigit = 1;
144364      zOut[i] = c;
144365    }
144366  }
144367  mx = hasDigit ? 3 : 10;
144368  if( nIn>mx*2 ){
144369    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
144370      zOut[j] = zOut[i];
144371    }
144372    i = j;
144373  }
144374  zOut[i] = 0;
144375  *pnOut = i;
144376}
144377
144378
144379/*
144380** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
144381** zOut is at least big enough to hold nIn bytes.  Write the actual
144382** size of the output word (exclusive of the '\0' terminator) into *pnOut.
144383**
144384** Any upper-case characters in the US-ASCII character set ([A-Z])
144385** are converted to lower case.  Upper-case UTF characters are
144386** unchanged.
144387**
144388** Words that are longer than about 20 bytes are stemmed by retaining
144389** a few bytes from the beginning and the end of the word.  If the
144390** word contains digits, 3 bytes are taken from the beginning and
144391** 3 bytes from the end.  For long words without digits, 10 bytes
144392** are taken from each end.  US-ASCII case folding still applies.
144393**
144394** If the input word contains not digits but does characters not
144395** in [a-zA-Z] then no stemming is attempted and this routine just
144396** copies the input into the input into the output with US-ASCII
144397** case folding.
144398**
144399** Stemming never increases the length of the word.  So there is
144400** no chance of overflowing the zOut buffer.
144401*/
144402static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
144403  int i, j;
144404  char zReverse[28];
144405  char *z, *z2;
144406  if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
144407    /* The word is too big or too small for the porter stemmer.
144408    ** Fallback to the copy stemmer */
144409    copy_stemmer(zIn, nIn, zOut, pnOut);
144410    return;
144411  }
144412  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
144413    char c = zIn[i];
144414    if( c>='A' && c<='Z' ){
144415      zReverse[j] = c + 'a' - 'A';
144416    }else if( c>='a' && c<='z' ){
144417      zReverse[j] = c;
144418    }else{
144419      /* The use of a character not in [a-zA-Z] means that we fallback
144420      ** to the copy stemmer */
144421      copy_stemmer(zIn, nIn, zOut, pnOut);
144422      return;
144423    }
144424  }
144425  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
144426  z = &zReverse[j+1];
144427
144428
144429  /* Step 1a */
144430  if( z[0]=='s' ){
144431    if(
144432     !stem(&z, "sess", "ss", 0) &&
144433     !stem(&z, "sei", "i", 0)  &&
144434     !stem(&z, "ss", "ss", 0)
144435    ){
144436      z++;
144437    }
144438  }
144439
144440  /* Step 1b */
144441  z2 = z;
144442  if( stem(&z, "dee", "ee", m_gt_0) ){
144443    /* Do nothing.  The work was all in the test */
144444  }else if(
144445     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
144446      && z!=z2
144447  ){
144448     if( stem(&z, "ta", "ate", 0) ||
144449         stem(&z, "lb", "ble", 0) ||
144450         stem(&z, "zi", "ize", 0) ){
144451       /* Do nothing.  The work was all in the test */
144452     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
144453       z++;
144454     }else if( m_eq_1(z) && star_oh(z) ){
144455       *(--z) = 'e';
144456     }
144457  }
144458
144459  /* Step 1c */
144460  if( z[0]=='y' && hasVowel(z+1) ){
144461    z[0] = 'i';
144462  }
144463
144464  /* Step 2 */
144465  switch( z[1] ){
144466   case 'a':
144467     if( !stem(&z, "lanoita", "ate", m_gt_0) ){
144468       stem(&z, "lanoit", "tion", m_gt_0);
144469     }
144470     break;
144471   case 'c':
144472     if( !stem(&z, "icne", "ence", m_gt_0) ){
144473       stem(&z, "icna", "ance", m_gt_0);
144474     }
144475     break;
144476   case 'e':
144477     stem(&z, "rezi", "ize", m_gt_0);
144478     break;
144479   case 'g':
144480     stem(&z, "igol", "log", m_gt_0);
144481     break;
144482   case 'l':
144483     if( !stem(&z, "ilb", "ble", m_gt_0)
144484      && !stem(&z, "illa", "al", m_gt_0)
144485      && !stem(&z, "iltne", "ent", m_gt_0)
144486      && !stem(&z, "ile", "e", m_gt_0)
144487     ){
144488       stem(&z, "ilsuo", "ous", m_gt_0);
144489     }
144490     break;
144491   case 'o':
144492     if( !stem(&z, "noitazi", "ize", m_gt_0)
144493      && !stem(&z, "noita", "ate", m_gt_0)
144494     ){
144495       stem(&z, "rota", "ate", m_gt_0);
144496     }
144497     break;
144498   case 's':
144499     if( !stem(&z, "msila", "al", m_gt_0)
144500      && !stem(&z, "ssenevi", "ive", m_gt_0)
144501      && !stem(&z, "ssenluf", "ful", m_gt_0)
144502     ){
144503       stem(&z, "ssensuo", "ous", m_gt_0);
144504     }
144505     break;
144506   case 't':
144507     if( !stem(&z, "itila", "al", m_gt_0)
144508      && !stem(&z, "itivi", "ive", m_gt_0)
144509     ){
144510       stem(&z, "itilib", "ble", m_gt_0);
144511     }
144512     break;
144513  }
144514
144515  /* Step 3 */
144516  switch( z[0] ){
144517   case 'e':
144518     if( !stem(&z, "etaci", "ic", m_gt_0)
144519      && !stem(&z, "evita", "", m_gt_0)
144520     ){
144521       stem(&z, "ezila", "al", m_gt_0);
144522     }
144523     break;
144524   case 'i':
144525     stem(&z, "itici", "ic", m_gt_0);
144526     break;
144527   case 'l':
144528     if( !stem(&z, "laci", "ic", m_gt_0) ){
144529       stem(&z, "luf", "", m_gt_0);
144530     }
144531     break;
144532   case 's':
144533     stem(&z, "ssen", "", m_gt_0);
144534     break;
144535  }
144536
144537  /* Step 4 */
144538  switch( z[1] ){
144539   case 'a':
144540     if( z[0]=='l' && m_gt_1(z+2) ){
144541       z += 2;
144542     }
144543     break;
144544   case 'c':
144545     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
144546       z += 4;
144547     }
144548     break;
144549   case 'e':
144550     if( z[0]=='r' && m_gt_1(z+2) ){
144551       z += 2;
144552     }
144553     break;
144554   case 'i':
144555     if( z[0]=='c' && m_gt_1(z+2) ){
144556       z += 2;
144557     }
144558     break;
144559   case 'l':
144560     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
144561       z += 4;
144562     }
144563     break;
144564   case 'n':
144565     if( z[0]=='t' ){
144566       if( z[2]=='a' ){
144567         if( m_gt_1(z+3) ){
144568           z += 3;
144569         }
144570       }else if( z[2]=='e' ){
144571         if( !stem(&z, "tneme", "", m_gt_1)
144572          && !stem(&z, "tnem", "", m_gt_1)
144573         ){
144574           stem(&z, "tne", "", m_gt_1);
144575         }
144576       }
144577     }
144578     break;
144579   case 'o':
144580     if( z[0]=='u' ){
144581       if( m_gt_1(z+2) ){
144582         z += 2;
144583       }
144584     }else if( z[3]=='s' || z[3]=='t' ){
144585       stem(&z, "noi", "", m_gt_1);
144586     }
144587     break;
144588   case 's':
144589     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
144590       z += 3;
144591     }
144592     break;
144593   case 't':
144594     if( !stem(&z, "eta", "", m_gt_1) ){
144595       stem(&z, "iti", "", m_gt_1);
144596     }
144597     break;
144598   case 'u':
144599     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
144600       z += 3;
144601     }
144602     break;
144603   case 'v':
144604   case 'z':
144605     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
144606       z += 3;
144607     }
144608     break;
144609  }
144610
144611  /* Step 5a */
144612  if( z[0]=='e' ){
144613    if( m_gt_1(z+1) ){
144614      z++;
144615    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
144616      z++;
144617    }
144618  }
144619
144620  /* Step 5b */
144621  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
144622    z++;
144623  }
144624
144625  /* z[] is now the stemmed word in reverse order.  Flip it back
144626  ** around into forward order and return.
144627  */
144628  *pnOut = i = (int)strlen(z);
144629  zOut[i] = 0;
144630  while( *z ){
144631    zOut[--i] = *(z++);
144632  }
144633}
144634
144635/*
144636** Characters that can be part of a token.  We assume any character
144637** whose value is greater than 0x80 (any UTF character) can be
144638** part of a token.  In other words, delimiters all must have
144639** values of 0x7f or lower.
144640*/
144641static const char porterIdChar[] = {
144642/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
144643    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
144644    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
144645    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
144646    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
144647    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
144648};
144649#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
144650
144651/*
144652** Extract the next token from a tokenization cursor.  The cursor must
144653** have been opened by a prior call to porterOpen().
144654*/
144655static int porterNext(
144656  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
144657  const char **pzToken,               /* OUT: *pzToken is the token text */
144658  int *pnBytes,                       /* OUT: Number of bytes in token */
144659  int *piStartOffset,                 /* OUT: Starting offset of token */
144660  int *piEndOffset,                   /* OUT: Ending offset of token */
144661  int *piPosition                     /* OUT: Position integer of token */
144662){
144663  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
144664  const char *z = c->zInput;
144665
144666  while( c->iOffset<c->nInput ){
144667    int iStartOffset, ch;
144668
144669    /* Scan past delimiter characters */
144670    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
144671      c->iOffset++;
144672    }
144673
144674    /* Count non-delimiter characters. */
144675    iStartOffset = c->iOffset;
144676    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
144677      c->iOffset++;
144678    }
144679
144680    if( c->iOffset>iStartOffset ){
144681      int n = c->iOffset-iStartOffset;
144682      if( n>c->nAllocated ){
144683        char *pNew;
144684        c->nAllocated = n+20;
144685        pNew = sqlite3_realloc(c->zToken, c->nAllocated);
144686        if( !pNew ) return SQLITE_NOMEM;
144687        c->zToken = pNew;
144688      }
144689      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
144690      *pzToken = c->zToken;
144691      *piStartOffset = iStartOffset;
144692      *piEndOffset = c->iOffset;
144693      *piPosition = c->iToken++;
144694      return SQLITE_OK;
144695    }
144696  }
144697  return SQLITE_DONE;
144698}
144699
144700/*
144701** The set of routines that implement the porter-stemmer tokenizer
144702*/
144703static const sqlite3_tokenizer_module porterTokenizerModule = {
144704  0,
144705  porterCreate,
144706  porterDestroy,
144707  porterOpen,
144708  porterClose,
144709  porterNext,
144710  0
144711};
144712
144713/*
144714** Allocate a new porter tokenizer.  Return a pointer to the new
144715** tokenizer in *ppModule
144716*/
144717SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
144718  sqlite3_tokenizer_module const**ppModule
144719){
144720  *ppModule = &porterTokenizerModule;
144721}
144722
144723#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
144724
144725/************** End of fts3_porter.c *****************************************/
144726/************** Begin file fts3_tokenizer.c **********************************/
144727/*
144728** 2007 June 22
144729**
144730** The author disclaims copyright to this source code.  In place of
144731** a legal notice, here is a blessing:
144732**
144733**    May you do good and not evil.
144734**    May you find forgiveness for yourself and forgive others.
144735**    May you share freely, never taking more than you give.
144736**
144737******************************************************************************
144738**
144739** This is part of an SQLite module implementing full-text search.
144740** This particular file implements the generic tokenizer interface.
144741*/
144742
144743/*
144744** The code in this file is only compiled if:
144745**
144746**     * The FTS3 module is being built as an extension
144747**       (in which case SQLITE_CORE is not defined), or
144748**
144749**     * The FTS3 module is being built into the core of
144750**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
144751*/
144752/* #include "fts3Int.h" */
144753#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
144754
144755/* #include <assert.h> */
144756/* #include <string.h> */
144757
144758/*
144759** Implementation of the SQL scalar function for accessing the underlying
144760** hash table. This function may be called as follows:
144761**
144762**   SELECT <function-name>(<key-name>);
144763**   SELECT <function-name>(<key-name>, <pointer>);
144764**
144765** where <function-name> is the name passed as the second argument
144766** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
144767**
144768** If the <pointer> argument is specified, it must be a blob value
144769** containing a pointer to be stored as the hash data corresponding
144770** to the string <key-name>. If <pointer> is not specified, then
144771** the string <key-name> must already exist in the has table. Otherwise,
144772** an error is returned.
144773**
144774** Whether or not the <pointer> argument is specified, the value returned
144775** is a blob containing the pointer stored as the hash data corresponding
144776** to string <key-name> (after the hash-table is updated, if applicable).
144777*/
144778static void scalarFunc(
144779  sqlite3_context *context,
144780  int argc,
144781  sqlite3_value **argv
144782){
144783  Fts3Hash *pHash;
144784  void *pPtr = 0;
144785  const unsigned char *zName;
144786  int nName;
144787
144788  assert( argc==1 || argc==2 );
144789
144790  pHash = (Fts3Hash *)sqlite3_user_data(context);
144791
144792  zName = sqlite3_value_text(argv[0]);
144793  nName = sqlite3_value_bytes(argv[0])+1;
144794
144795  if( argc==2 ){
144796    void *pOld;
144797    int n = sqlite3_value_bytes(argv[1]);
144798    if( zName==0 || n!=sizeof(pPtr) ){
144799      sqlite3_result_error(context, "argument type mismatch", -1);
144800      return;
144801    }
144802    pPtr = *(void **)sqlite3_value_blob(argv[1]);
144803    pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
144804    if( pOld==pPtr ){
144805      sqlite3_result_error(context, "out of memory", -1);
144806      return;
144807    }
144808  }else{
144809    if( zName ){
144810      pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
144811    }
144812    if( !pPtr ){
144813      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
144814      sqlite3_result_error(context, zErr, -1);
144815      sqlite3_free(zErr);
144816      return;
144817    }
144818  }
144819
144820  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
144821}
144822
144823SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
144824  static const char isFtsIdChar[] = {
144825      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
144826      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
144827      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
144828      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
144829      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
144830      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
144831      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
144832      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
144833  };
144834  return (c&0x80 || isFtsIdChar[(int)(c)]);
144835}
144836
144837SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
144838  const char *z1;
144839  const char *z2 = 0;
144840
144841  /* Find the start of the next token. */
144842  z1 = zStr;
144843  while( z2==0 ){
144844    char c = *z1;
144845    switch( c ){
144846      case '\0': return 0;        /* No more tokens here */
144847      case '\'':
144848      case '"':
144849      case '`': {
144850        z2 = z1;
144851        while( *++z2 && (*z2!=c || *++z2==c) );
144852        break;
144853      }
144854      case '[':
144855        z2 = &z1[1];
144856        while( *z2 && z2[0]!=']' ) z2++;
144857        if( *z2 ) z2++;
144858        break;
144859
144860      default:
144861        if( sqlite3Fts3IsIdChar(*z1) ){
144862          z2 = &z1[1];
144863          while( sqlite3Fts3IsIdChar(*z2) ) z2++;
144864        }else{
144865          z1++;
144866        }
144867    }
144868  }
144869
144870  *pn = (int)(z2-z1);
144871  return z1;
144872}
144873
144874SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
144875  Fts3Hash *pHash,                /* Tokenizer hash table */
144876  const char *zArg,               /* Tokenizer name */
144877  sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
144878  char **pzErr                    /* OUT: Set to malloced error message */
144879){
144880  int rc;
144881  char *z = (char *)zArg;
144882  int n = 0;
144883  char *zCopy;
144884  char *zEnd;                     /* Pointer to nul-term of zCopy */
144885  sqlite3_tokenizer_module *m;
144886
144887  zCopy = sqlite3_mprintf("%s", zArg);
144888  if( !zCopy ) return SQLITE_NOMEM;
144889  zEnd = &zCopy[strlen(zCopy)];
144890
144891  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
144892  if( z==0 ){
144893    assert( n==0 );
144894    z = zCopy;
144895  }
144896  z[n] = '\0';
144897  sqlite3Fts3Dequote(z);
144898
144899  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
144900  if( !m ){
144901    sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
144902    rc = SQLITE_ERROR;
144903  }else{
144904    char const **aArg = 0;
144905    int iArg = 0;
144906    z = &z[n+1];
144907    while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
144908      int nNew = sizeof(char *)*(iArg+1);
144909      char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
144910      if( !aNew ){
144911        sqlite3_free(zCopy);
144912        sqlite3_free((void *)aArg);
144913        return SQLITE_NOMEM;
144914      }
144915      aArg = aNew;
144916      aArg[iArg++] = z;
144917      z[n] = '\0';
144918      sqlite3Fts3Dequote(z);
144919      z = &z[n+1];
144920    }
144921    rc = m->xCreate(iArg, aArg, ppTok);
144922    assert( rc!=SQLITE_OK || *ppTok );
144923    if( rc!=SQLITE_OK ){
144924      sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
144925    }else{
144926      (*ppTok)->pModule = m;
144927    }
144928    sqlite3_free((void *)aArg);
144929  }
144930
144931  sqlite3_free(zCopy);
144932  return rc;
144933}
144934
144935
144936#ifdef SQLITE_TEST
144937
144938#include <tcl.h>
144939/* #include <string.h> */
144940
144941/*
144942** Implementation of a special SQL scalar function for testing tokenizers
144943** designed to be used in concert with the Tcl testing framework. This
144944** function must be called with two or more arguments:
144945**
144946**   SELECT <function-name>(<key-name>, ..., <input-string>);
144947**
144948** where <function-name> is the name passed as the second argument
144949** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
144950** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
144951**
144952** The return value is a string that may be interpreted as a Tcl
144953** list. For each token in the <input-string>, three elements are
144954** added to the returned list. The first is the token position, the
144955** second is the token text (folded, stemmed, etc.) and the third is the
144956** substring of <input-string> associated with the token. For example,
144957** using the built-in "simple" tokenizer:
144958**
144959**   SELECT fts_tokenizer_test('simple', 'I don't see how');
144960**
144961** will return the string:
144962**
144963**   "{0 i I 1 dont don't 2 see see 3 how how}"
144964**
144965*/
144966static void testFunc(
144967  sqlite3_context *context,
144968  int argc,
144969  sqlite3_value **argv
144970){
144971  Fts3Hash *pHash;
144972  sqlite3_tokenizer_module *p;
144973  sqlite3_tokenizer *pTokenizer = 0;
144974  sqlite3_tokenizer_cursor *pCsr = 0;
144975
144976  const char *zErr = 0;
144977
144978  const char *zName;
144979  int nName;
144980  const char *zInput;
144981  int nInput;
144982
144983  const char *azArg[64];
144984
144985  const char *zToken;
144986  int nToken = 0;
144987  int iStart = 0;
144988  int iEnd = 0;
144989  int iPos = 0;
144990  int i;
144991
144992  Tcl_Obj *pRet;
144993
144994  if( argc<2 ){
144995    sqlite3_result_error(context, "insufficient arguments", -1);
144996    return;
144997  }
144998
144999  nName = sqlite3_value_bytes(argv[0]);
145000  zName = (const char *)sqlite3_value_text(argv[0]);
145001  nInput = sqlite3_value_bytes(argv[argc-1]);
145002  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
145003
145004  pHash = (Fts3Hash *)sqlite3_user_data(context);
145005  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
145006
145007  if( !p ){
145008    char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
145009    sqlite3_result_error(context, zErr2, -1);
145010    sqlite3_free(zErr2);
145011    return;
145012  }
145013
145014  pRet = Tcl_NewObj();
145015  Tcl_IncrRefCount(pRet);
145016
145017  for(i=1; i<argc-1; i++){
145018    azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
145019  }
145020
145021  if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
145022    zErr = "error in xCreate()";
145023    goto finish;
145024  }
145025  pTokenizer->pModule = p;
145026  if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
145027    zErr = "error in xOpen()";
145028    goto finish;
145029  }
145030
145031  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
145032    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
145033    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
145034    zToken = &zInput[iStart];
145035    nToken = iEnd-iStart;
145036    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
145037  }
145038
145039  if( SQLITE_OK!=p->xClose(pCsr) ){
145040    zErr = "error in xClose()";
145041    goto finish;
145042  }
145043  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
145044    zErr = "error in xDestroy()";
145045    goto finish;
145046  }
145047
145048finish:
145049  if( zErr ){
145050    sqlite3_result_error(context, zErr, -1);
145051  }else{
145052    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
145053  }
145054  Tcl_DecrRefCount(pRet);
145055}
145056
145057static
145058int registerTokenizer(
145059  sqlite3 *db,
145060  char *zName,
145061  const sqlite3_tokenizer_module *p
145062){
145063  int rc;
145064  sqlite3_stmt *pStmt;
145065  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
145066
145067  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
145068  if( rc!=SQLITE_OK ){
145069    return rc;
145070  }
145071
145072  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
145073  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
145074  sqlite3_step(pStmt);
145075
145076  return sqlite3_finalize(pStmt);
145077}
145078
145079static
145080int queryTokenizer(
145081  sqlite3 *db,
145082  char *zName,
145083  const sqlite3_tokenizer_module **pp
145084){
145085  int rc;
145086  sqlite3_stmt *pStmt;
145087  const char zSql[] = "SELECT fts3_tokenizer(?)";
145088
145089  *pp = 0;
145090  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
145091  if( rc!=SQLITE_OK ){
145092    return rc;
145093  }
145094
145095  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
145096  if( SQLITE_ROW==sqlite3_step(pStmt) ){
145097    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
145098      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
145099    }
145100  }
145101
145102  return sqlite3_finalize(pStmt);
145103}
145104
145105SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
145106
145107/*
145108** Implementation of the scalar function fts3_tokenizer_internal_test().
145109** This function is used for testing only, it is not included in the
145110** build unless SQLITE_TEST is defined.
145111**
145112** The purpose of this is to test that the fts3_tokenizer() function
145113** can be used as designed by the C-code in the queryTokenizer and
145114** registerTokenizer() functions above. These two functions are repeated
145115** in the README.tokenizer file as an example, so it is important to
145116** test them.
145117**
145118** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
145119** function with no arguments. An assert() will fail if a problem is
145120** detected. i.e.:
145121**
145122**     SELECT fts3_tokenizer_internal_test();
145123**
145124*/
145125static void intTestFunc(
145126  sqlite3_context *context,
145127  int argc,
145128  sqlite3_value **argv
145129){
145130  int rc;
145131  const sqlite3_tokenizer_module *p1;
145132  const sqlite3_tokenizer_module *p2;
145133  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
145134
145135  UNUSED_PARAMETER(argc);
145136  UNUSED_PARAMETER(argv);
145137
145138  /* Test the query function */
145139  sqlite3Fts3SimpleTokenizerModule(&p1);
145140  rc = queryTokenizer(db, "simple", &p2);
145141  assert( rc==SQLITE_OK );
145142  assert( p1==p2 );
145143  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
145144  assert( rc==SQLITE_ERROR );
145145  assert( p2==0 );
145146  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
145147
145148  /* Test the storage function */
145149  rc = registerTokenizer(db, "nosuchtokenizer", p1);
145150  assert( rc==SQLITE_OK );
145151  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
145152  assert( rc==SQLITE_OK );
145153  assert( p2==p1 );
145154
145155  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
145156}
145157
145158#endif
145159
145160/*
145161** Set up SQL objects in database db used to access the contents of
145162** the hash table pointed to by argument pHash. The hash table must
145163** been initialized to use string keys, and to take a private copy
145164** of the key when a value is inserted. i.e. by a call similar to:
145165**
145166**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
145167**
145168** This function adds a scalar function (see header comment above
145169** scalarFunc() in this file for details) and, if ENABLE_TABLE is
145170** defined at compilation time, a temporary virtual table (see header
145171** comment above struct HashTableVtab) to the database schema. Both
145172** provide read/write access to the contents of *pHash.
145173**
145174** The third argument to this function, zName, is used as the name
145175** of both the scalar and, if created, the virtual table.
145176*/
145177SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
145178  sqlite3 *db,
145179  Fts3Hash *pHash,
145180  const char *zName
145181){
145182  int rc = SQLITE_OK;
145183  void *p = (void *)pHash;
145184  const int any = SQLITE_ANY;
145185
145186#ifdef SQLITE_TEST
145187  char *zTest = 0;
145188  char *zTest2 = 0;
145189  void *pdb = (void *)db;
145190  zTest = sqlite3_mprintf("%s_test", zName);
145191  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
145192  if( !zTest || !zTest2 ){
145193    rc = SQLITE_NOMEM;
145194  }
145195#endif
145196
145197  if( SQLITE_OK==rc ){
145198    rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
145199  }
145200  if( SQLITE_OK==rc ){
145201    rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
145202  }
145203#ifdef SQLITE_TEST
145204  if( SQLITE_OK==rc ){
145205    rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
145206  }
145207  if( SQLITE_OK==rc ){
145208    rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
145209  }
145210#endif
145211
145212#ifdef SQLITE_TEST
145213  sqlite3_free(zTest);
145214  sqlite3_free(zTest2);
145215#endif
145216
145217  return rc;
145218}
145219
145220#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
145221
145222/************** End of fts3_tokenizer.c **************************************/
145223/************** Begin file fts3_tokenizer1.c *********************************/
145224/*
145225** 2006 Oct 10
145226**
145227** The author disclaims copyright to this source code.  In place of
145228** a legal notice, here is a blessing:
145229**
145230**    May you do good and not evil.
145231**    May you find forgiveness for yourself and forgive others.
145232**    May you share freely, never taking more than you give.
145233**
145234******************************************************************************
145235**
145236** Implementation of the "simple" full-text-search tokenizer.
145237*/
145238
145239/*
145240** The code in this file is only compiled if:
145241**
145242**     * The FTS3 module is being built as an extension
145243**       (in which case SQLITE_CORE is not defined), or
145244**
145245**     * The FTS3 module is being built into the core of
145246**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
145247*/
145248/* #include "fts3Int.h" */
145249#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
145250
145251/* #include <assert.h> */
145252/* #include <stdlib.h> */
145253/* #include <stdio.h> */
145254/* #include <string.h> */
145255
145256/* #include "fts3_tokenizer.h" */
145257
145258typedef struct simple_tokenizer {
145259  sqlite3_tokenizer base;
145260  char delim[128];             /* flag ASCII delimiters */
145261} simple_tokenizer;
145262
145263typedef struct simple_tokenizer_cursor {
145264  sqlite3_tokenizer_cursor base;
145265  const char *pInput;          /* input we are tokenizing */
145266  int nBytes;                  /* size of the input */
145267  int iOffset;                 /* current position in pInput */
145268  int iToken;                  /* index of next token to be returned */
145269  char *pToken;                /* storage for current token */
145270  int nTokenAllocated;         /* space allocated to zToken buffer */
145271} simple_tokenizer_cursor;
145272
145273
145274static int simpleDelim(simple_tokenizer *t, unsigned char c){
145275  return c<0x80 && t->delim[c];
145276}
145277static int fts3_isalnum(int x){
145278  return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
145279}
145280
145281/*
145282** Create a new tokenizer instance.
145283*/
145284static int simpleCreate(
145285  int argc, const char * const *argv,
145286  sqlite3_tokenizer **ppTokenizer
145287){
145288  simple_tokenizer *t;
145289
145290  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
145291  if( t==NULL ) return SQLITE_NOMEM;
145292  memset(t, 0, sizeof(*t));
145293
145294  /* TODO(shess) Delimiters need to remain the same from run to run,
145295  ** else we need to reindex.  One solution would be a meta-table to
145296  ** track such information in the database, then we'd only want this
145297  ** information on the initial create.
145298  */
145299  if( argc>1 ){
145300    int i, n = (int)strlen(argv[1]);
145301    for(i=0; i<n; i++){
145302      unsigned char ch = argv[1][i];
145303      /* We explicitly don't support UTF-8 delimiters for now. */
145304      if( ch>=0x80 ){
145305        sqlite3_free(t);
145306        return SQLITE_ERROR;
145307      }
145308      t->delim[ch] = 1;
145309    }
145310  } else {
145311    /* Mark non-alphanumeric ASCII characters as delimiters */
145312    int i;
145313    for(i=1; i<0x80; i++){
145314      t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
145315    }
145316  }
145317
145318  *ppTokenizer = &t->base;
145319  return SQLITE_OK;
145320}
145321
145322/*
145323** Destroy a tokenizer
145324*/
145325static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
145326  sqlite3_free(pTokenizer);
145327  return SQLITE_OK;
145328}
145329
145330/*
145331** Prepare to begin tokenizing a particular string.  The input
145332** string to be tokenized is pInput[0..nBytes-1].  A cursor
145333** used to incrementally tokenize this string is returned in
145334** *ppCursor.
145335*/
145336static int simpleOpen(
145337  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
145338  const char *pInput, int nBytes,        /* String to be tokenized */
145339  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
145340){
145341  simple_tokenizer_cursor *c;
145342
145343  UNUSED_PARAMETER(pTokenizer);
145344
145345  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
145346  if( c==NULL ) return SQLITE_NOMEM;
145347
145348  c->pInput = pInput;
145349  if( pInput==0 ){
145350    c->nBytes = 0;
145351  }else if( nBytes<0 ){
145352    c->nBytes = (int)strlen(pInput);
145353  }else{
145354    c->nBytes = nBytes;
145355  }
145356  c->iOffset = 0;                 /* start tokenizing at the beginning */
145357  c->iToken = 0;
145358  c->pToken = NULL;               /* no space allocated, yet. */
145359  c->nTokenAllocated = 0;
145360
145361  *ppCursor = &c->base;
145362  return SQLITE_OK;
145363}
145364
145365/*
145366** Close a tokenization cursor previously opened by a call to
145367** simpleOpen() above.
145368*/
145369static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
145370  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
145371  sqlite3_free(c->pToken);
145372  sqlite3_free(c);
145373  return SQLITE_OK;
145374}
145375
145376/*
145377** Extract the next token from a tokenization cursor.  The cursor must
145378** have been opened by a prior call to simpleOpen().
145379*/
145380static int simpleNext(
145381  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
145382  const char **ppToken,               /* OUT: *ppToken is the token text */
145383  int *pnBytes,                       /* OUT: Number of bytes in token */
145384  int *piStartOffset,                 /* OUT: Starting offset of token */
145385  int *piEndOffset,                   /* OUT: Ending offset of token */
145386  int *piPosition                     /* OUT: Position integer of token */
145387){
145388  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
145389  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
145390  unsigned char *p = (unsigned char *)c->pInput;
145391
145392  while( c->iOffset<c->nBytes ){
145393    int iStartOffset;
145394
145395    /* Scan past delimiter characters */
145396    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
145397      c->iOffset++;
145398    }
145399
145400    /* Count non-delimiter characters. */
145401    iStartOffset = c->iOffset;
145402    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
145403      c->iOffset++;
145404    }
145405
145406    if( c->iOffset>iStartOffset ){
145407      int i, n = c->iOffset-iStartOffset;
145408      if( n>c->nTokenAllocated ){
145409        char *pNew;
145410        c->nTokenAllocated = n+20;
145411        pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
145412        if( !pNew ) return SQLITE_NOMEM;
145413        c->pToken = pNew;
145414      }
145415      for(i=0; i<n; i++){
145416        /* TODO(shess) This needs expansion to handle UTF-8
145417        ** case-insensitivity.
145418        */
145419        unsigned char ch = p[iStartOffset+i];
145420        c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
145421      }
145422      *ppToken = c->pToken;
145423      *pnBytes = n;
145424      *piStartOffset = iStartOffset;
145425      *piEndOffset = c->iOffset;
145426      *piPosition = c->iToken++;
145427
145428      return SQLITE_OK;
145429    }
145430  }
145431  return SQLITE_DONE;
145432}
145433
145434/*
145435** The set of routines that implement the simple tokenizer
145436*/
145437static const sqlite3_tokenizer_module simpleTokenizerModule = {
145438  0,
145439  simpleCreate,
145440  simpleDestroy,
145441  simpleOpen,
145442  simpleClose,
145443  simpleNext,
145444  0,
145445};
145446
145447/*
145448** Allocate a new simple tokenizer.  Return a pointer to the new
145449** tokenizer in *ppModule
145450*/
145451SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
145452  sqlite3_tokenizer_module const**ppModule
145453){
145454  *ppModule = &simpleTokenizerModule;
145455}
145456
145457#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
145458
145459/************** End of fts3_tokenizer1.c *************************************/
145460/************** Begin file fts3_tokenize_vtab.c ******************************/
145461/*
145462** 2013 Apr 22
145463**
145464** The author disclaims copyright to this source code.  In place of
145465** a legal notice, here is a blessing:
145466**
145467**    May you do good and not evil.
145468**    May you find forgiveness for yourself and forgive others.
145469**    May you share freely, never taking more than you give.
145470**
145471******************************************************************************
145472**
145473** This file contains code for the "fts3tokenize" virtual table module.
145474** An fts3tokenize virtual table is created as follows:
145475**
145476**   CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
145477**       <tokenizer-name>, <arg-1>, ...
145478**   );
145479**
145480** The table created has the following schema:
145481**
145482**   CREATE TABLE <tbl>(input, token, start, end, position)
145483**
145484** When queried, the query must include a WHERE clause of type:
145485**
145486**   input = <string>
145487**
145488** The virtual table module tokenizes this <string>, using the FTS3
145489** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
145490** statement and returns one row for each token in the result. With
145491** fields set as follows:
145492**
145493**   input:   Always set to a copy of <string>
145494**   token:   A token from the input.
145495**   start:   Byte offset of the token within the input <string>.
145496**   end:     Byte offset of the byte immediately following the end of the
145497**            token within the input string.
145498**   pos:     Token offset of token within input.
145499**
145500*/
145501/* #include "fts3Int.h" */
145502#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
145503
145504/* #include <string.h> */
145505/* #include <assert.h> */
145506
145507typedef struct Fts3tokTable Fts3tokTable;
145508typedef struct Fts3tokCursor Fts3tokCursor;
145509
145510/*
145511** Virtual table structure.
145512*/
145513struct Fts3tokTable {
145514  sqlite3_vtab base;              /* Base class used by SQLite core */
145515  const sqlite3_tokenizer_module *pMod;
145516  sqlite3_tokenizer *pTok;
145517};
145518
145519/*
145520** Virtual table cursor structure.
145521*/
145522struct Fts3tokCursor {
145523  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
145524  char *zInput;                   /* Input string */
145525  sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
145526  int iRowid;                     /* Current 'rowid' value */
145527  const char *zToken;             /* Current 'token' value */
145528  int nToken;                     /* Size of zToken in bytes */
145529  int iStart;                     /* Current 'start' value */
145530  int iEnd;                       /* Current 'end' value */
145531  int iPos;                       /* Current 'pos' value */
145532};
145533
145534/*
145535** Query FTS for the tokenizer implementation named zName.
145536*/
145537static int fts3tokQueryTokenizer(
145538  Fts3Hash *pHash,
145539  const char *zName,
145540  const sqlite3_tokenizer_module **pp,
145541  char **pzErr
145542){
145543  sqlite3_tokenizer_module *p;
145544  int nName = (int)strlen(zName);
145545
145546  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
145547  if( !p ){
145548    sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
145549    return SQLITE_ERROR;
145550  }
145551
145552  *pp = p;
145553  return SQLITE_OK;
145554}
145555
145556/*
145557** The second argument, argv[], is an array of pointers to nul-terminated
145558** strings. This function makes a copy of the array and strings into a
145559** single block of memory. It then dequotes any of the strings that appear
145560** to be quoted.
145561**
145562** If successful, output parameter *pazDequote is set to point at the
145563** array of dequoted strings and SQLITE_OK is returned. The caller is
145564** responsible for eventually calling sqlite3_free() to free the array
145565** in this case. Or, if an error occurs, an SQLite error code is returned.
145566** The final value of *pazDequote is undefined in this case.
145567*/
145568static int fts3tokDequoteArray(
145569  int argc,                       /* Number of elements in argv[] */
145570  const char * const *argv,       /* Input array */
145571  char ***pazDequote              /* Output array */
145572){
145573  int rc = SQLITE_OK;             /* Return code */
145574  if( argc==0 ){
145575    *pazDequote = 0;
145576  }else{
145577    int i;
145578    int nByte = 0;
145579    char **azDequote;
145580
145581    for(i=0; i<argc; i++){
145582      nByte += (int)(strlen(argv[i]) + 1);
145583    }
145584
145585    *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
145586    if( azDequote==0 ){
145587      rc = SQLITE_NOMEM;
145588    }else{
145589      char *pSpace = (char *)&azDequote[argc];
145590      for(i=0; i<argc; i++){
145591        int n = (int)strlen(argv[i]);
145592        azDequote[i] = pSpace;
145593        memcpy(pSpace, argv[i], n+1);
145594        sqlite3Fts3Dequote(pSpace);
145595        pSpace += (n+1);
145596      }
145597    }
145598  }
145599
145600  return rc;
145601}
145602
145603/*
145604** Schema of the tokenizer table.
145605*/
145606#define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
145607
145608/*
145609** This function does all the work for both the xConnect and xCreate methods.
145610** These tables have no persistent representation of their own, so xConnect
145611** and xCreate are identical operations.
145612**
145613**   argv[0]: module name
145614**   argv[1]: database name
145615**   argv[2]: table name
145616**   argv[3]: first argument (tokenizer name)
145617*/
145618static int fts3tokConnectMethod(
145619  sqlite3 *db,                    /* Database connection */
145620  void *pHash,                    /* Hash table of tokenizers */
145621  int argc,                       /* Number of elements in argv array */
145622  const char * const *argv,       /* xCreate/xConnect argument array */
145623  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
145624  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
145625){
145626  Fts3tokTable *pTab = 0;
145627  const sqlite3_tokenizer_module *pMod = 0;
145628  sqlite3_tokenizer *pTok = 0;
145629  int rc;
145630  char **azDequote = 0;
145631  int nDequote;
145632
145633  rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
145634  if( rc!=SQLITE_OK ) return rc;
145635
145636  nDequote = argc-3;
145637  rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
145638
145639  if( rc==SQLITE_OK ){
145640    const char *zModule;
145641    if( nDequote<1 ){
145642      zModule = "simple";
145643    }else{
145644      zModule = azDequote[0];
145645    }
145646    rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
145647  }
145648
145649  assert( (rc==SQLITE_OK)==(pMod!=0) );
145650  if( rc==SQLITE_OK ){
145651    const char * const *azArg = (const char * const *)&azDequote[1];
145652    rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
145653  }
145654
145655  if( rc==SQLITE_OK ){
145656    pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
145657    if( pTab==0 ){
145658      rc = SQLITE_NOMEM;
145659    }
145660  }
145661
145662  if( rc==SQLITE_OK ){
145663    memset(pTab, 0, sizeof(Fts3tokTable));
145664    pTab->pMod = pMod;
145665    pTab->pTok = pTok;
145666    *ppVtab = &pTab->base;
145667  }else{
145668    if( pTok ){
145669      pMod->xDestroy(pTok);
145670    }
145671  }
145672
145673  sqlite3_free(azDequote);
145674  return rc;
145675}
145676
145677/*
145678** This function does the work for both the xDisconnect and xDestroy methods.
145679** These tables have no persistent representation of their own, so xDisconnect
145680** and xDestroy are identical operations.
145681*/
145682static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
145683  Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
145684
145685  pTab->pMod->xDestroy(pTab->pTok);
145686  sqlite3_free(pTab);
145687  return SQLITE_OK;
145688}
145689
145690/*
145691** xBestIndex - Analyze a WHERE and ORDER BY clause.
145692*/
145693static int fts3tokBestIndexMethod(
145694  sqlite3_vtab *pVTab,
145695  sqlite3_index_info *pInfo
145696){
145697  int i;
145698  UNUSED_PARAMETER(pVTab);
145699
145700  for(i=0; i<pInfo->nConstraint; i++){
145701    if( pInfo->aConstraint[i].usable
145702     && pInfo->aConstraint[i].iColumn==0
145703     && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
145704    ){
145705      pInfo->idxNum = 1;
145706      pInfo->aConstraintUsage[i].argvIndex = 1;
145707      pInfo->aConstraintUsage[i].omit = 1;
145708      pInfo->estimatedCost = 1;
145709      return SQLITE_OK;
145710    }
145711  }
145712
145713  pInfo->idxNum = 0;
145714  assert( pInfo->estimatedCost>1000000.0 );
145715
145716  return SQLITE_OK;
145717}
145718
145719/*
145720** xOpen - Open a cursor.
145721*/
145722static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
145723  Fts3tokCursor *pCsr;
145724  UNUSED_PARAMETER(pVTab);
145725
145726  pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
145727  if( pCsr==0 ){
145728    return SQLITE_NOMEM;
145729  }
145730  memset(pCsr, 0, sizeof(Fts3tokCursor));
145731
145732  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
145733  return SQLITE_OK;
145734}
145735
145736/*
145737** Reset the tokenizer cursor passed as the only argument. As if it had
145738** just been returned by fts3tokOpenMethod().
145739*/
145740static void fts3tokResetCursor(Fts3tokCursor *pCsr){
145741  if( pCsr->pCsr ){
145742    Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
145743    pTab->pMod->xClose(pCsr->pCsr);
145744    pCsr->pCsr = 0;
145745  }
145746  sqlite3_free(pCsr->zInput);
145747  pCsr->zInput = 0;
145748  pCsr->zToken = 0;
145749  pCsr->nToken = 0;
145750  pCsr->iStart = 0;
145751  pCsr->iEnd = 0;
145752  pCsr->iPos = 0;
145753  pCsr->iRowid = 0;
145754}
145755
145756/*
145757** xClose - Close a cursor.
145758*/
145759static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
145760  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
145761
145762  fts3tokResetCursor(pCsr);
145763  sqlite3_free(pCsr);
145764  return SQLITE_OK;
145765}
145766
145767/*
145768** xNext - Advance the cursor to the next row, if any.
145769*/
145770static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
145771  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
145772  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
145773  int rc;                         /* Return code */
145774
145775  pCsr->iRowid++;
145776  rc = pTab->pMod->xNext(pCsr->pCsr,
145777      &pCsr->zToken, &pCsr->nToken,
145778      &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
145779  );
145780
145781  if( rc!=SQLITE_OK ){
145782    fts3tokResetCursor(pCsr);
145783    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
145784  }
145785
145786  return rc;
145787}
145788
145789/*
145790** xFilter - Initialize a cursor to point at the start of its data.
145791*/
145792static int fts3tokFilterMethod(
145793  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
145794  int idxNum,                     /* Strategy index */
145795  const char *idxStr,             /* Unused */
145796  int nVal,                       /* Number of elements in apVal */
145797  sqlite3_value **apVal           /* Arguments for the indexing scheme */
145798){
145799  int rc = SQLITE_ERROR;
145800  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
145801  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
145802  UNUSED_PARAMETER(idxStr);
145803  UNUSED_PARAMETER(nVal);
145804
145805  fts3tokResetCursor(pCsr);
145806  if( idxNum==1 ){
145807    const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
145808    int nByte = sqlite3_value_bytes(apVal[0]);
145809    pCsr->zInput = sqlite3_malloc(nByte+1);
145810    if( pCsr->zInput==0 ){
145811      rc = SQLITE_NOMEM;
145812    }else{
145813      memcpy(pCsr->zInput, zByte, nByte);
145814      pCsr->zInput[nByte] = 0;
145815      rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
145816      if( rc==SQLITE_OK ){
145817        pCsr->pCsr->pTokenizer = pTab->pTok;
145818      }
145819    }
145820  }
145821
145822  if( rc!=SQLITE_OK ) return rc;
145823  return fts3tokNextMethod(pCursor);
145824}
145825
145826/*
145827** xEof - Return true if the cursor is at EOF, or false otherwise.
145828*/
145829static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
145830  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
145831  return (pCsr->zToken==0);
145832}
145833
145834/*
145835** xColumn - Return a column value.
145836*/
145837static int fts3tokColumnMethod(
145838  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
145839  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
145840  int iCol                        /* Index of column to read value from */
145841){
145842  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
145843
145844  /* CREATE TABLE x(input, token, start, end, position) */
145845  switch( iCol ){
145846    case 0:
145847      sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
145848      break;
145849    case 1:
145850      sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
145851      break;
145852    case 2:
145853      sqlite3_result_int(pCtx, pCsr->iStart);
145854      break;
145855    case 3:
145856      sqlite3_result_int(pCtx, pCsr->iEnd);
145857      break;
145858    default:
145859      assert( iCol==4 );
145860      sqlite3_result_int(pCtx, pCsr->iPos);
145861      break;
145862  }
145863  return SQLITE_OK;
145864}
145865
145866/*
145867** xRowid - Return the current rowid for the cursor.
145868*/
145869static int fts3tokRowidMethod(
145870  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
145871  sqlite_int64 *pRowid            /* OUT: Rowid value */
145872){
145873  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
145874  *pRowid = (sqlite3_int64)pCsr->iRowid;
145875  return SQLITE_OK;
145876}
145877
145878/*
145879** Register the fts3tok module with database connection db. Return SQLITE_OK
145880** if successful or an error code if sqlite3_create_module() fails.
145881*/
145882SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
145883  static const sqlite3_module fts3tok_module = {
145884     0,                           /* iVersion      */
145885     fts3tokConnectMethod,        /* xCreate       */
145886     fts3tokConnectMethod,        /* xConnect      */
145887     fts3tokBestIndexMethod,      /* xBestIndex    */
145888     fts3tokDisconnectMethod,     /* xDisconnect   */
145889     fts3tokDisconnectMethod,     /* xDestroy      */
145890     fts3tokOpenMethod,           /* xOpen         */
145891     fts3tokCloseMethod,          /* xClose        */
145892     fts3tokFilterMethod,         /* xFilter       */
145893     fts3tokNextMethod,           /* xNext         */
145894     fts3tokEofMethod,            /* xEof          */
145895     fts3tokColumnMethod,         /* xColumn       */
145896     fts3tokRowidMethod,          /* xRowid        */
145897     0,                           /* xUpdate       */
145898     0,                           /* xBegin        */
145899     0,                           /* xSync         */
145900     0,                           /* xCommit       */
145901     0,                           /* xRollback     */
145902     0,                           /* xFindFunction */
145903     0,                           /* xRename       */
145904     0,                           /* xSavepoint    */
145905     0,                           /* xRelease      */
145906     0                            /* xRollbackTo   */
145907  };
145908  int rc;                         /* Return code */
145909
145910  rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
145911  return rc;
145912}
145913
145914#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
145915
145916/************** End of fts3_tokenize_vtab.c **********************************/
145917/************** Begin file fts3_write.c **************************************/
145918/*
145919** 2009 Oct 23
145920**
145921** The author disclaims copyright to this source code.  In place of
145922** a legal notice, here is a blessing:
145923**
145924**    May you do good and not evil.
145925**    May you find forgiveness for yourself and forgive others.
145926**    May you share freely, never taking more than you give.
145927**
145928******************************************************************************
145929**
145930** This file is part of the SQLite FTS3 extension module. Specifically,
145931** this file contains code to insert, update and delete rows from FTS3
145932** tables. It also contains code to merge FTS3 b-tree segments. Some
145933** of the sub-routines used to merge segments are also used by the query
145934** code in fts3.c.
145935*/
145936
145937/* #include "fts3Int.h" */
145938#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
145939
145940/* #include <string.h> */
145941/* #include <assert.h> */
145942/* #include <stdlib.h> */
145943
145944
145945#define FTS_MAX_APPENDABLE_HEIGHT 16
145946
145947/*
145948** When full-text index nodes are loaded from disk, the buffer that they
145949** are loaded into has the following number of bytes of padding at the end
145950** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
145951** of 920 bytes is allocated for it.
145952**
145953** This means that if we have a pointer into a buffer containing node data,
145954** it is always safe to read up to two varints from it without risking an
145955** overread, even if the node data is corrupted.
145956*/
145957#define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
145958
145959/*
145960** Under certain circumstances, b-tree nodes (doclists) can be loaded into
145961** memory incrementally instead of all at once. This can be a big performance
145962** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
145963** method before retrieving all query results (as may happen, for example,
145964** if a query has a LIMIT clause).
145965**
145966** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
145967** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
145968** The code is written so that the hard lower-limit for each of these values
145969** is 1. Clearly such small values would be inefficient, but can be useful
145970** for testing purposes.
145971**
145972** If this module is built with SQLITE_TEST defined, these constants may
145973** be overridden at runtime for testing purposes. File fts3_test.c contains
145974** a Tcl interface to read and write the values.
145975*/
145976#ifdef SQLITE_TEST
145977int test_fts3_node_chunksize = (4*1024);
145978int test_fts3_node_chunk_threshold = (4*1024)*4;
145979# define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
145980# define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
145981#else
145982# define FTS3_NODE_CHUNKSIZE (4*1024)
145983# define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
145984#endif
145985
145986/*
145987** The two values that may be meaningfully bound to the :1 parameter in
145988** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
145989*/
145990#define FTS_STAT_DOCTOTAL      0
145991#define FTS_STAT_INCRMERGEHINT 1
145992#define FTS_STAT_AUTOINCRMERGE 2
145993
145994/*
145995** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
145996** and incremental merge operation that takes place. This is used for
145997** debugging FTS only, it should not usually be turned on in production
145998** systems.
145999*/
146000#ifdef FTS3_LOG_MERGES
146001static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
146002  sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
146003}
146004#else
146005#define fts3LogMerge(x, y)
146006#endif
146007
146008
146009typedef struct PendingList PendingList;
146010typedef struct SegmentNode SegmentNode;
146011typedef struct SegmentWriter SegmentWriter;
146012
146013/*
146014** An instance of the following data structure is used to build doclists
146015** incrementally. See function fts3PendingListAppend() for details.
146016*/
146017struct PendingList {
146018  int nData;
146019  char *aData;
146020  int nSpace;
146021  sqlite3_int64 iLastDocid;
146022  sqlite3_int64 iLastCol;
146023  sqlite3_int64 iLastPos;
146024};
146025
146026
146027/*
146028** Each cursor has a (possibly empty) linked list of the following objects.
146029*/
146030struct Fts3DeferredToken {
146031  Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
146032  int iCol;                       /* Column token must occur in */
146033  Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
146034  PendingList *pList;             /* Doclist is assembled here */
146035};
146036
146037/*
146038** An instance of this structure is used to iterate through the terms on
146039** a contiguous set of segment b-tree leaf nodes. Although the details of
146040** this structure are only manipulated by code in this file, opaque handles
146041** of type Fts3SegReader* are also used by code in fts3.c to iterate through
146042** terms when querying the full-text index. See functions:
146043**
146044**   sqlite3Fts3SegReaderNew()
146045**   sqlite3Fts3SegReaderFree()
146046**   sqlite3Fts3SegReaderIterate()
146047**
146048** Methods used to manipulate Fts3SegReader structures:
146049**
146050**   fts3SegReaderNext()
146051**   fts3SegReaderFirstDocid()
146052**   fts3SegReaderNextDocid()
146053*/
146054struct Fts3SegReader {
146055  int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
146056  u8 bLookup;                     /* True for a lookup only */
146057  u8 rootOnly;                    /* True for a root-only reader */
146058
146059  sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
146060  sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
146061  sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
146062  sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
146063
146064  char *aNode;                    /* Pointer to node data (or NULL) */
146065  int nNode;                      /* Size of buffer at aNode (or 0) */
146066  int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
146067  sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
146068
146069  Fts3HashElem **ppNextElem;
146070
146071  /* Variables set by fts3SegReaderNext(). These may be read directly
146072  ** by the caller. They are valid from the time SegmentReaderNew() returns
146073  ** until SegmentReaderNext() returns something other than SQLITE_OK
146074  ** (i.e. SQLITE_DONE).
146075  */
146076  int nTerm;                      /* Number of bytes in current term */
146077  char *zTerm;                    /* Pointer to current term */
146078  int nTermAlloc;                 /* Allocated size of zTerm buffer */
146079  char *aDoclist;                 /* Pointer to doclist of current entry */
146080  int nDoclist;                   /* Size of doclist in current entry */
146081
146082  /* The following variables are used by fts3SegReaderNextDocid() to iterate
146083  ** through the current doclist (aDoclist/nDoclist).
146084  */
146085  char *pOffsetList;
146086  int nOffsetList;                /* For descending pending seg-readers only */
146087  sqlite3_int64 iDocid;
146088};
146089
146090#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
146091#define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
146092
146093/*
146094** An instance of this structure is used to create a segment b-tree in the
146095** database. The internal details of this type are only accessed by the
146096** following functions:
146097**
146098**   fts3SegWriterAdd()
146099**   fts3SegWriterFlush()
146100**   fts3SegWriterFree()
146101*/
146102struct SegmentWriter {
146103  SegmentNode *pTree;             /* Pointer to interior tree structure */
146104  sqlite3_int64 iFirst;           /* First slot in %_segments written */
146105  sqlite3_int64 iFree;            /* Next free slot in %_segments */
146106  char *zTerm;                    /* Pointer to previous term buffer */
146107  int nTerm;                      /* Number of bytes in zTerm */
146108  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
146109  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
146110  int nSize;                      /* Size of allocation at aData */
146111  int nData;                      /* Bytes of data in aData */
146112  char *aData;                    /* Pointer to block from malloc() */
146113  i64 nLeafData;                  /* Number of bytes of leaf data written */
146114};
146115
146116/*
146117** Type SegmentNode is used by the following three functions to create
146118** the interior part of the segment b+-tree structures (everything except
146119** the leaf nodes). These functions and type are only ever used by code
146120** within the fts3SegWriterXXX() family of functions described above.
146121**
146122**   fts3NodeAddTerm()
146123**   fts3NodeWrite()
146124**   fts3NodeFree()
146125**
146126** When a b+tree is written to the database (either as a result of a merge
146127** or the pending-terms table being flushed), leaves are written into the
146128** database file as soon as they are completely populated. The interior of
146129** the tree is assembled in memory and written out only once all leaves have
146130** been populated and stored. This is Ok, as the b+-tree fanout is usually
146131** very large, meaning that the interior of the tree consumes relatively
146132** little memory.
146133*/
146134struct SegmentNode {
146135  SegmentNode *pParent;           /* Parent node (or NULL for root node) */
146136  SegmentNode *pRight;            /* Pointer to right-sibling */
146137  SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
146138  int nEntry;                     /* Number of terms written to node so far */
146139  char *zTerm;                    /* Pointer to previous term buffer */
146140  int nTerm;                      /* Number of bytes in zTerm */
146141  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
146142  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
146143  int nData;                      /* Bytes of valid data so far */
146144  char *aData;                    /* Node data */
146145};
146146
146147/*
146148** Valid values for the second argument to fts3SqlStmt().
146149*/
146150#define SQL_DELETE_CONTENT             0
146151#define SQL_IS_EMPTY                   1
146152#define SQL_DELETE_ALL_CONTENT         2
146153#define SQL_DELETE_ALL_SEGMENTS        3
146154#define SQL_DELETE_ALL_SEGDIR          4
146155#define SQL_DELETE_ALL_DOCSIZE         5
146156#define SQL_DELETE_ALL_STAT            6
146157#define SQL_SELECT_CONTENT_BY_ROWID    7
146158#define SQL_NEXT_SEGMENT_INDEX         8
146159#define SQL_INSERT_SEGMENTS            9
146160#define SQL_NEXT_SEGMENTS_ID          10
146161#define SQL_INSERT_SEGDIR             11
146162#define SQL_SELECT_LEVEL              12
146163#define SQL_SELECT_LEVEL_RANGE        13
146164#define SQL_SELECT_LEVEL_COUNT        14
146165#define SQL_SELECT_SEGDIR_MAX_LEVEL   15
146166#define SQL_DELETE_SEGDIR_LEVEL       16
146167#define SQL_DELETE_SEGMENTS_RANGE     17
146168#define SQL_CONTENT_INSERT            18
146169#define SQL_DELETE_DOCSIZE            19
146170#define SQL_REPLACE_DOCSIZE           20
146171#define SQL_SELECT_DOCSIZE            21
146172#define SQL_SELECT_STAT               22
146173#define SQL_REPLACE_STAT              23
146174
146175#define SQL_SELECT_ALL_PREFIX_LEVEL   24
146176#define SQL_DELETE_ALL_TERMS_SEGDIR   25
146177#define SQL_DELETE_SEGDIR_RANGE       26
146178#define SQL_SELECT_ALL_LANGID         27
146179#define SQL_FIND_MERGE_LEVEL          28
146180#define SQL_MAX_LEAF_NODE_ESTIMATE    29
146181#define SQL_DELETE_SEGDIR_ENTRY       30
146182#define SQL_SHIFT_SEGDIR_ENTRY        31
146183#define SQL_SELECT_SEGDIR             32
146184#define SQL_CHOMP_SEGDIR              33
146185#define SQL_SEGMENT_IS_APPENDABLE     34
146186#define SQL_SELECT_INDEXES            35
146187#define SQL_SELECT_MXLEVEL            36
146188
146189#define SQL_SELECT_LEVEL_RANGE2       37
146190#define SQL_UPDATE_LEVEL_IDX          38
146191#define SQL_UPDATE_LEVEL              39
146192
146193/*
146194** This function is used to obtain an SQLite prepared statement handle
146195** for the statement identified by the second argument. If successful,
146196** *pp is set to the requested statement handle and SQLITE_OK returned.
146197** Otherwise, an SQLite error code is returned and *pp is set to 0.
146198**
146199** If argument apVal is not NULL, then it must point to an array with
146200** at least as many entries as the requested statement has bound
146201** parameters. The values are bound to the statements parameters before
146202** returning.
146203*/
146204static int fts3SqlStmt(
146205  Fts3Table *p,                   /* Virtual table handle */
146206  int eStmt,                      /* One of the SQL_XXX constants above */
146207  sqlite3_stmt **pp,              /* OUT: Statement handle */
146208  sqlite3_value **apVal           /* Values to bind to statement */
146209){
146210  const char *azSql[] = {
146211/* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
146212/* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
146213/* 2  */  "DELETE FROM %Q.'%q_content'",
146214/* 3  */  "DELETE FROM %Q.'%q_segments'",
146215/* 4  */  "DELETE FROM %Q.'%q_segdir'",
146216/* 5  */  "DELETE FROM %Q.'%q_docsize'",
146217/* 6  */  "DELETE FROM %Q.'%q_stat'",
146218/* 7  */  "SELECT %s WHERE rowid=?",
146219/* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
146220/* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
146221/* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
146222/* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
146223
146224          /* Return segments in order from oldest to newest.*/
146225/* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
146226            "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
146227/* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
146228            "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
146229            "ORDER BY level DESC, idx ASC",
146230
146231/* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
146232/* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
146233
146234/* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
146235/* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
146236/* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
146237/* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
146238/* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
146239/* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
146240/* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
146241/* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
146242/* 24 */  "",
146243/* 25 */  "",
146244
146245/* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
146246/* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
146247
146248/* This statement is used to determine which level to read the input from
146249** when performing an incremental merge. It returns the absolute level number
146250** of the oldest level in the db that contains at least ? segments. Or,
146251** if no level in the FTS index contains more than ? segments, the statement
146252** returns zero rows.  */
146253/* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
146254         "  ORDER BY (level %% 1024) ASC LIMIT 1",
146255
146256/* Estimate the upper limit on the number of leaf nodes in a new segment
146257** created by merging the oldest :2 segments from absolute level :1. See
146258** function sqlite3Fts3Incrmerge() for details.  */
146259/* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
146260         "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
146261
146262/* SQL_DELETE_SEGDIR_ENTRY
146263**   Delete the %_segdir entry on absolute level :1 with index :2.  */
146264/* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
146265
146266/* SQL_SHIFT_SEGDIR_ENTRY
146267**   Modify the idx value for the segment with idx=:3 on absolute level :2
146268**   to :1.  */
146269/* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
146270
146271/* SQL_SELECT_SEGDIR
146272**   Read a single entry from the %_segdir table. The entry from absolute
146273**   level :1 with index value :2.  */
146274/* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
146275            "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
146276
146277/* SQL_CHOMP_SEGDIR
146278**   Update the start_block (:1) and root (:2) fields of the %_segdir
146279**   entry located on absolute level :3 with index :4.  */
146280/* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
146281            "WHERE level = ? AND idx = ?",
146282
146283/* SQL_SEGMENT_IS_APPENDABLE
146284**   Return a single row if the segment with end_block=? is appendable. Or
146285**   no rows otherwise.  */
146286/* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
146287
146288/* SQL_SELECT_INDEXES
146289**   Return the list of valid segment indexes for absolute level ?  */
146290/* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
146291
146292/* SQL_SELECT_MXLEVEL
146293**   Return the largest relative level in the FTS index or indexes.  */
146294/* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
146295
146296          /* Return segments in order from oldest to newest.*/
146297/* 37 */  "SELECT level, idx, end_block "
146298            "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
146299            "ORDER BY level DESC, idx ASC",
146300
146301          /* Update statements used while promoting segments */
146302/* 38 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
146303            "WHERE level=? AND idx=?",
146304/* 39 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
146305
146306  };
146307  int rc = SQLITE_OK;
146308  sqlite3_stmt *pStmt;
146309
146310  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
146311  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
146312
146313  pStmt = p->aStmt[eStmt];
146314  if( !pStmt ){
146315    char *zSql;
146316    if( eStmt==SQL_CONTENT_INSERT ){
146317      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
146318    }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
146319      zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
146320    }else{
146321      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
146322    }
146323    if( !zSql ){
146324      rc = SQLITE_NOMEM;
146325    }else{
146326      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
146327      sqlite3_free(zSql);
146328      assert( rc==SQLITE_OK || pStmt==0 );
146329      p->aStmt[eStmt] = pStmt;
146330    }
146331  }
146332  if( apVal ){
146333    int i;
146334    int nParam = sqlite3_bind_parameter_count(pStmt);
146335    for(i=0; rc==SQLITE_OK && i<nParam; i++){
146336      rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
146337    }
146338  }
146339  *pp = pStmt;
146340  return rc;
146341}
146342
146343
146344static int fts3SelectDocsize(
146345  Fts3Table *pTab,                /* FTS3 table handle */
146346  sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
146347  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
146348){
146349  sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
146350  int rc;                         /* Return code */
146351
146352  rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
146353  if( rc==SQLITE_OK ){
146354    sqlite3_bind_int64(pStmt, 1, iDocid);
146355    rc = sqlite3_step(pStmt);
146356    if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
146357      rc = sqlite3_reset(pStmt);
146358      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
146359      pStmt = 0;
146360    }else{
146361      rc = SQLITE_OK;
146362    }
146363  }
146364
146365  *ppStmt = pStmt;
146366  return rc;
146367}
146368
146369SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
146370  Fts3Table *pTab,                /* Fts3 table handle */
146371  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
146372){
146373  sqlite3_stmt *pStmt = 0;
146374  int rc;
146375  rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
146376  if( rc==SQLITE_OK ){
146377    sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
146378    if( sqlite3_step(pStmt)!=SQLITE_ROW
146379     || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
146380    ){
146381      rc = sqlite3_reset(pStmt);
146382      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
146383      pStmt = 0;
146384    }
146385  }
146386  *ppStmt = pStmt;
146387  return rc;
146388}
146389
146390SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
146391  Fts3Table *pTab,                /* Fts3 table handle */
146392  sqlite3_int64 iDocid,           /* Docid to read size data for */
146393  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
146394){
146395  return fts3SelectDocsize(pTab, iDocid, ppStmt);
146396}
146397
146398/*
146399** Similar to fts3SqlStmt(). Except, after binding the parameters in
146400** array apVal[] to the SQL statement identified by eStmt, the statement
146401** is executed.
146402**
146403** Returns SQLITE_OK if the statement is successfully executed, or an
146404** SQLite error code otherwise.
146405*/
146406static void fts3SqlExec(
146407  int *pRC,                /* Result code */
146408  Fts3Table *p,            /* The FTS3 table */
146409  int eStmt,               /* Index of statement to evaluate */
146410  sqlite3_value **apVal    /* Parameters to bind */
146411){
146412  sqlite3_stmt *pStmt;
146413  int rc;
146414  if( *pRC ) return;
146415  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
146416  if( rc==SQLITE_OK ){
146417    sqlite3_step(pStmt);
146418    rc = sqlite3_reset(pStmt);
146419  }
146420  *pRC = rc;
146421}
146422
146423
146424/*
146425** This function ensures that the caller has obtained an exclusive
146426** shared-cache table-lock on the %_segdir table. This is required before
146427** writing data to the fts3 table. If this lock is not acquired first, then
146428** the caller may end up attempting to take this lock as part of committing
146429** a transaction, causing SQLite to return SQLITE_LOCKED or
146430** LOCKED_SHAREDCACHEto a COMMIT command.
146431**
146432** It is best to avoid this because if FTS3 returns any error when
146433** committing a transaction, the whole transaction will be rolled back.
146434** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
146435** It can still happen if the user locks the underlying tables directly
146436** instead of accessing them via FTS.
146437*/
146438static int fts3Writelock(Fts3Table *p){
146439  int rc = SQLITE_OK;
146440
146441  if( p->nPendingData==0 ){
146442    sqlite3_stmt *pStmt;
146443    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
146444    if( rc==SQLITE_OK ){
146445      sqlite3_bind_null(pStmt, 1);
146446      sqlite3_step(pStmt);
146447      rc = sqlite3_reset(pStmt);
146448    }
146449  }
146450
146451  return rc;
146452}
146453
146454/*
146455** FTS maintains a separate indexes for each language-id (a 32-bit integer).
146456** Within each language id, a separate index is maintained to store the
146457** document terms, and each configured prefix size (configured the FTS
146458** "prefix=" option). And each index consists of multiple levels ("relative
146459** levels").
146460**
146461** All three of these values (the language id, the specific index and the
146462** level within the index) are encoded in 64-bit integer values stored
146463** in the %_segdir table on disk. This function is used to convert three
146464** separate component values into the single 64-bit integer value that
146465** can be used to query the %_segdir table.
146466**
146467** Specifically, each language-id/index combination is allocated 1024
146468** 64-bit integer level values ("absolute levels"). The main terms index
146469** for language-id 0 is allocate values 0-1023. The first prefix index
146470** (if any) for language-id 0 is allocated values 1024-2047. And so on.
146471** Language 1 indexes are allocated immediately following language 0.
146472**
146473** So, for a system with nPrefix prefix indexes configured, the block of
146474** absolute levels that corresponds to language-id iLangid and index
146475** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
146476*/
146477static sqlite3_int64 getAbsoluteLevel(
146478  Fts3Table *p,                   /* FTS3 table handle */
146479  int iLangid,                    /* Language id */
146480  int iIndex,                     /* Index in p->aIndex[] */
146481  int iLevel                      /* Level of segments */
146482){
146483  sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
146484  assert( iLangid>=0 );
146485  assert( p->nIndex>0 );
146486  assert( iIndex>=0 && iIndex<p->nIndex );
146487
146488  iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
146489  return iBase + iLevel;
146490}
146491
146492/*
146493** Set *ppStmt to a statement handle that may be used to iterate through
146494** all rows in the %_segdir table, from oldest to newest. If successful,
146495** return SQLITE_OK. If an error occurs while preparing the statement,
146496** return an SQLite error code.
146497**
146498** There is only ever one instance of this SQL statement compiled for
146499** each FTS3 table.
146500**
146501** The statement returns the following columns from the %_segdir table:
146502**
146503**   0: idx
146504**   1: start_block
146505**   2: leaves_end_block
146506**   3: end_block
146507**   4: root
146508*/
146509SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
146510  Fts3Table *p,                   /* FTS3 table */
146511  int iLangid,                    /* Language being queried */
146512  int iIndex,                     /* Index for p->aIndex[] */
146513  int iLevel,                     /* Level to select (relative level) */
146514  sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
146515){
146516  int rc;
146517  sqlite3_stmt *pStmt = 0;
146518
146519  assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
146520  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
146521  assert( iIndex>=0 && iIndex<p->nIndex );
146522
146523  if( iLevel<0 ){
146524    /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
146525    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
146526    if( rc==SQLITE_OK ){
146527      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
146528      sqlite3_bind_int64(pStmt, 2,
146529          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
146530      );
146531    }
146532  }else{
146533    /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
146534    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
146535    if( rc==SQLITE_OK ){
146536      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
146537    }
146538  }
146539  *ppStmt = pStmt;
146540  return rc;
146541}
146542
146543
146544/*
146545** Append a single varint to a PendingList buffer. SQLITE_OK is returned
146546** if successful, or an SQLite error code otherwise.
146547**
146548** This function also serves to allocate the PendingList structure itself.
146549** For example, to create a new PendingList structure containing two
146550** varints:
146551**
146552**   PendingList *p = 0;
146553**   fts3PendingListAppendVarint(&p, 1);
146554**   fts3PendingListAppendVarint(&p, 2);
146555*/
146556static int fts3PendingListAppendVarint(
146557  PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
146558  sqlite3_int64 i                 /* Value to append to data */
146559){
146560  PendingList *p = *pp;
146561
146562  /* Allocate or grow the PendingList as required. */
146563  if( !p ){
146564    p = sqlite3_malloc(sizeof(*p) + 100);
146565    if( !p ){
146566      return SQLITE_NOMEM;
146567    }
146568    p->nSpace = 100;
146569    p->aData = (char *)&p[1];
146570    p->nData = 0;
146571  }
146572  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
146573    int nNew = p->nSpace * 2;
146574    p = sqlite3_realloc(p, sizeof(*p) + nNew);
146575    if( !p ){
146576      sqlite3_free(*pp);
146577      *pp = 0;
146578      return SQLITE_NOMEM;
146579    }
146580    p->nSpace = nNew;
146581    p->aData = (char *)&p[1];
146582  }
146583
146584  /* Append the new serialized varint to the end of the list. */
146585  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
146586  p->aData[p->nData] = '\0';
146587  *pp = p;
146588  return SQLITE_OK;
146589}
146590
146591/*
146592** Add a docid/column/position entry to a PendingList structure. Non-zero
146593** is returned if the structure is sqlite3_realloced as part of adding
146594** the entry. Otherwise, zero.
146595**
146596** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
146597** Zero is always returned in this case. Otherwise, if no OOM error occurs,
146598** it is set to SQLITE_OK.
146599*/
146600static int fts3PendingListAppend(
146601  PendingList **pp,               /* IN/OUT: PendingList structure */
146602  sqlite3_int64 iDocid,           /* Docid for entry to add */
146603  sqlite3_int64 iCol,             /* Column for entry to add */
146604  sqlite3_int64 iPos,             /* Position of term for entry to add */
146605  int *pRc                        /* OUT: Return code */
146606){
146607  PendingList *p = *pp;
146608  int rc = SQLITE_OK;
146609
146610  assert( !p || p->iLastDocid<=iDocid );
146611
146612  if( !p || p->iLastDocid!=iDocid ){
146613    sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
146614    if( p ){
146615      assert( p->nData<p->nSpace );
146616      assert( p->aData[p->nData]==0 );
146617      p->nData++;
146618    }
146619    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
146620      goto pendinglistappend_out;
146621    }
146622    p->iLastCol = -1;
146623    p->iLastPos = 0;
146624    p->iLastDocid = iDocid;
146625  }
146626  if( iCol>0 && p->iLastCol!=iCol ){
146627    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
146628     || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
146629    ){
146630      goto pendinglistappend_out;
146631    }
146632    p->iLastCol = iCol;
146633    p->iLastPos = 0;
146634  }
146635  if( iCol>=0 ){
146636    assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
146637    rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
146638    if( rc==SQLITE_OK ){
146639      p->iLastPos = iPos;
146640    }
146641  }
146642
146643 pendinglistappend_out:
146644  *pRc = rc;
146645  if( p!=*pp ){
146646    *pp = p;
146647    return 1;
146648  }
146649  return 0;
146650}
146651
146652/*
146653** Free a PendingList object allocated by fts3PendingListAppend().
146654*/
146655static void fts3PendingListDelete(PendingList *pList){
146656  sqlite3_free(pList);
146657}
146658
146659/*
146660** Add an entry to one of the pending-terms hash tables.
146661*/
146662static int fts3PendingTermsAddOne(
146663  Fts3Table *p,
146664  int iCol,
146665  int iPos,
146666  Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
146667  const char *zToken,
146668  int nToken
146669){
146670  PendingList *pList;
146671  int rc = SQLITE_OK;
146672
146673  pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
146674  if( pList ){
146675    p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
146676  }
146677  if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
146678    if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
146679      /* Malloc failed while inserting the new entry. This can only
146680      ** happen if there was no previous entry for this token.
146681      */
146682      assert( 0==fts3HashFind(pHash, zToken, nToken) );
146683      sqlite3_free(pList);
146684      rc = SQLITE_NOMEM;
146685    }
146686  }
146687  if( rc==SQLITE_OK ){
146688    p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
146689  }
146690  return rc;
146691}
146692
146693/*
146694** Tokenize the nul-terminated string zText and add all tokens to the
146695** pending-terms hash-table. The docid used is that currently stored in
146696** p->iPrevDocid, and the column is specified by argument iCol.
146697**
146698** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
146699*/
146700static int fts3PendingTermsAdd(
146701  Fts3Table *p,                   /* Table into which text will be inserted */
146702  int iLangid,                    /* Language id to use */
146703  const char *zText,              /* Text of document to be inserted */
146704  int iCol,                       /* Column into which text is being inserted */
146705  u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
146706){
146707  int rc;
146708  int iStart = 0;
146709  int iEnd = 0;
146710  int iPos = 0;
146711  int nWord = 0;
146712
146713  char const *zToken;
146714  int nToken = 0;
146715
146716  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
146717  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
146718  sqlite3_tokenizer_cursor *pCsr;
146719  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
146720      const char**,int*,int*,int*,int*);
146721
146722  assert( pTokenizer && pModule );
146723
146724  /* If the user has inserted a NULL value, this function may be called with
146725  ** zText==0. In this case, add zero token entries to the hash table and
146726  ** return early. */
146727  if( zText==0 ){
146728    *pnWord = 0;
146729    return SQLITE_OK;
146730  }
146731
146732  rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
146733  if( rc!=SQLITE_OK ){
146734    return rc;
146735  }
146736
146737  xNext = pModule->xNext;
146738  while( SQLITE_OK==rc
146739      && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
146740  ){
146741    int i;
146742    if( iPos>=nWord ) nWord = iPos+1;
146743
146744    /* Positions cannot be negative; we use -1 as a terminator internally.
146745    ** Tokens must have a non-zero length.
146746    */
146747    if( iPos<0 || !zToken || nToken<=0 ){
146748      rc = SQLITE_ERROR;
146749      break;
146750    }
146751
146752    /* Add the term to the terms index */
146753    rc = fts3PendingTermsAddOne(
146754        p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
146755    );
146756
146757    /* Add the term to each of the prefix indexes that it is not too
146758    ** short for. */
146759    for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
146760      struct Fts3Index *pIndex = &p->aIndex[i];
146761      if( nToken<pIndex->nPrefix ) continue;
146762      rc = fts3PendingTermsAddOne(
146763          p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
146764      );
146765    }
146766  }
146767
146768  pModule->xClose(pCsr);
146769  *pnWord += nWord;
146770  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
146771}
146772
146773/*
146774** Calling this function indicates that subsequent calls to
146775** fts3PendingTermsAdd() are to add term/position-list pairs for the
146776** contents of the document with docid iDocid.
146777*/
146778static int fts3PendingTermsDocid(
146779  Fts3Table *p,                   /* Full-text table handle */
146780  int bDelete,                    /* True if this op is a delete */
146781  int iLangid,                    /* Language id of row being written */
146782  sqlite_int64 iDocid             /* Docid of row being written */
146783){
146784  assert( iLangid>=0 );
146785  assert( bDelete==1 || bDelete==0 );
146786
146787  /* TODO(shess) Explore whether partially flushing the buffer on
146788  ** forced-flush would provide better performance.  I suspect that if
146789  ** we ordered the doclists by size and flushed the largest until the
146790  ** buffer was half empty, that would let the less frequent terms
146791  ** generate longer doclists.
146792  */
146793  if( iDocid<p->iPrevDocid
146794   || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
146795   || p->iPrevLangid!=iLangid
146796   || p->nPendingData>p->nMaxPendingData
146797  ){
146798    int rc = sqlite3Fts3PendingTermsFlush(p);
146799    if( rc!=SQLITE_OK ) return rc;
146800  }
146801  p->iPrevDocid = iDocid;
146802  p->iPrevLangid = iLangid;
146803  p->bPrevDelete = bDelete;
146804  return SQLITE_OK;
146805}
146806
146807/*
146808** Discard the contents of the pending-terms hash tables.
146809*/
146810SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
146811  int i;
146812  for(i=0; i<p->nIndex; i++){
146813    Fts3HashElem *pElem;
146814    Fts3Hash *pHash = &p->aIndex[i].hPending;
146815    for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
146816      PendingList *pList = (PendingList *)fts3HashData(pElem);
146817      fts3PendingListDelete(pList);
146818    }
146819    fts3HashClear(pHash);
146820  }
146821  p->nPendingData = 0;
146822}
146823
146824/*
146825** This function is called by the xUpdate() method as part of an INSERT
146826** operation. It adds entries for each term in the new record to the
146827** pendingTerms hash table.
146828**
146829** Argument apVal is the same as the similarly named argument passed to
146830** fts3InsertData(). Parameter iDocid is the docid of the new row.
146831*/
146832static int fts3InsertTerms(
146833  Fts3Table *p,
146834  int iLangid,
146835  sqlite3_value **apVal,
146836  u32 *aSz
146837){
146838  int i;                          /* Iterator variable */
146839  for(i=2; i<p->nColumn+2; i++){
146840    int iCol = i-2;
146841    if( p->abNotindexed[iCol]==0 ){
146842      const char *zText = (const char *)sqlite3_value_text(apVal[i]);
146843      int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
146844      if( rc!=SQLITE_OK ){
146845        return rc;
146846      }
146847      aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
146848    }
146849  }
146850  return SQLITE_OK;
146851}
146852
146853/*
146854** This function is called by the xUpdate() method for an INSERT operation.
146855** The apVal parameter is passed a copy of the apVal argument passed by
146856** SQLite to the xUpdate() method. i.e:
146857**
146858**   apVal[0]                Not used for INSERT.
146859**   apVal[1]                rowid
146860**   apVal[2]                Left-most user-defined column
146861**   ...
146862**   apVal[p->nColumn+1]     Right-most user-defined column
146863**   apVal[p->nColumn+2]     Hidden column with same name as table
146864**   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
146865**   apVal[p->nColumn+4]     Hidden languageid column
146866*/
146867static int fts3InsertData(
146868  Fts3Table *p,                   /* Full-text table */
146869  sqlite3_value **apVal,          /* Array of values to insert */
146870  sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
146871){
146872  int rc;                         /* Return code */
146873  sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
146874
146875  if( p->zContentTbl ){
146876    sqlite3_value *pRowid = apVal[p->nColumn+3];
146877    if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
146878      pRowid = apVal[1];
146879    }
146880    if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
146881      return SQLITE_CONSTRAINT;
146882    }
146883    *piDocid = sqlite3_value_int64(pRowid);
146884    return SQLITE_OK;
146885  }
146886
146887  /* Locate the statement handle used to insert data into the %_content
146888  ** table. The SQL for this statement is:
146889  **
146890  **   INSERT INTO %_content VALUES(?, ?, ?, ...)
146891  **
146892  ** The statement features N '?' variables, where N is the number of user
146893  ** defined columns in the FTS3 table, plus one for the docid field.
146894  */
146895  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
146896  if( rc==SQLITE_OK && p->zLanguageid ){
146897    rc = sqlite3_bind_int(
146898        pContentInsert, p->nColumn+2,
146899        sqlite3_value_int(apVal[p->nColumn+4])
146900    );
146901  }
146902  if( rc!=SQLITE_OK ) return rc;
146903
146904  /* There is a quirk here. The users INSERT statement may have specified
146905  ** a value for the "rowid" field, for the "docid" field, or for both.
146906  ** Which is a problem, since "rowid" and "docid" are aliases for the
146907  ** same value. For example:
146908  **
146909  **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
146910  **
146911  ** In FTS3, this is an error. It is an error to specify non-NULL values
146912  ** for both docid and some other rowid alias.
146913  */
146914  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
146915    if( SQLITE_NULL==sqlite3_value_type(apVal[0])
146916     && SQLITE_NULL!=sqlite3_value_type(apVal[1])
146917    ){
146918      /* A rowid/docid conflict. */
146919      return SQLITE_ERROR;
146920    }
146921    rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
146922    if( rc!=SQLITE_OK ) return rc;
146923  }
146924
146925  /* Execute the statement to insert the record. Set *piDocid to the
146926  ** new docid value.
146927  */
146928  sqlite3_step(pContentInsert);
146929  rc = sqlite3_reset(pContentInsert);
146930
146931  *piDocid = sqlite3_last_insert_rowid(p->db);
146932  return rc;
146933}
146934
146935
146936
146937/*
146938** Remove all data from the FTS3 table. Clear the hash table containing
146939** pending terms.
146940*/
146941static int fts3DeleteAll(Fts3Table *p, int bContent){
146942  int rc = SQLITE_OK;             /* Return code */
146943
146944  /* Discard the contents of the pending-terms hash table. */
146945  sqlite3Fts3PendingTermsClear(p);
146946
146947  /* Delete everything from the shadow tables. Except, leave %_content as
146948  ** is if bContent is false.  */
146949  assert( p->zContentTbl==0 || bContent==0 );
146950  if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
146951  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
146952  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
146953  if( p->bHasDocsize ){
146954    fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
146955  }
146956  if( p->bHasStat ){
146957    fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
146958  }
146959  return rc;
146960}
146961
146962/*
146963**
146964*/
146965static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
146966  int iLangid = 0;
146967  if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
146968  return iLangid;
146969}
146970
146971/*
146972** The first element in the apVal[] array is assumed to contain the docid
146973** (an integer) of a row about to be deleted. Remove all terms from the
146974** full-text index.
146975*/
146976static void fts3DeleteTerms(
146977  int *pRC,               /* Result code */
146978  Fts3Table *p,           /* The FTS table to delete from */
146979  sqlite3_value *pRowid,  /* The docid to be deleted */
146980  u32 *aSz,               /* Sizes of deleted document written here */
146981  int *pbFound            /* OUT: Set to true if row really does exist */
146982){
146983  int rc;
146984  sqlite3_stmt *pSelect;
146985
146986  assert( *pbFound==0 );
146987  if( *pRC ) return;
146988  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
146989  if( rc==SQLITE_OK ){
146990    if( SQLITE_ROW==sqlite3_step(pSelect) ){
146991      int i;
146992      int iLangid = langidFromSelect(p, pSelect);
146993      i64 iDocid = sqlite3_column_int64(pSelect, 0);
146994      rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
146995      for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
146996        int iCol = i-1;
146997        if( p->abNotindexed[iCol]==0 ){
146998          const char *zText = (const char *)sqlite3_column_text(pSelect, i);
146999          rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
147000          aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
147001        }
147002      }
147003      if( rc!=SQLITE_OK ){
147004        sqlite3_reset(pSelect);
147005        *pRC = rc;
147006        return;
147007      }
147008      *pbFound = 1;
147009    }
147010    rc = sqlite3_reset(pSelect);
147011  }else{
147012    sqlite3_reset(pSelect);
147013  }
147014  *pRC = rc;
147015}
147016
147017/*
147018** Forward declaration to account for the circular dependency between
147019** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
147020*/
147021static int fts3SegmentMerge(Fts3Table *, int, int, int);
147022
147023/*
147024** This function allocates a new level iLevel index in the segdir table.
147025** Usually, indexes are allocated within a level sequentially starting
147026** with 0, so the allocated index is one greater than the value returned
147027** by:
147028**
147029**   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
147030**
147031** However, if there are already FTS3_MERGE_COUNT indexes at the requested
147032** level, they are merged into a single level (iLevel+1) segment and the
147033** allocated index is 0.
147034**
147035** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
147036** returned. Otherwise, an SQLite error code is returned.
147037*/
147038static int fts3AllocateSegdirIdx(
147039  Fts3Table *p,
147040  int iLangid,                    /* Language id */
147041  int iIndex,                     /* Index for p->aIndex */
147042  int iLevel,
147043  int *piIdx
147044){
147045  int rc;                         /* Return Code */
147046  sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
147047  int iNext = 0;                  /* Result of query pNextIdx */
147048
147049  assert( iLangid>=0 );
147050  assert( p->nIndex>=1 );
147051
147052  /* Set variable iNext to the next available segdir index at level iLevel. */
147053  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
147054  if( rc==SQLITE_OK ){
147055    sqlite3_bind_int64(
147056        pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
147057    );
147058    if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
147059      iNext = sqlite3_column_int(pNextIdx, 0);
147060    }
147061    rc = sqlite3_reset(pNextIdx);
147062  }
147063
147064  if( rc==SQLITE_OK ){
147065    /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
147066    ** full, merge all segments in level iLevel into a single iLevel+1
147067    ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
147068    ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
147069    */
147070    if( iNext>=FTS3_MERGE_COUNT ){
147071      fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
147072      rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
147073      *piIdx = 0;
147074    }else{
147075      *piIdx = iNext;
147076    }
147077  }
147078
147079  return rc;
147080}
147081
147082/*
147083** The %_segments table is declared as follows:
147084**
147085**   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
147086**
147087** This function reads data from a single row of the %_segments table. The
147088** specific row is identified by the iBlockid parameter. If paBlob is not
147089** NULL, then a buffer is allocated using sqlite3_malloc() and populated
147090** with the contents of the blob stored in the "block" column of the
147091** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
147092** to the size of the blob in bytes before returning.
147093**
147094** If an error occurs, or the table does not contain the specified row,
147095** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
147096** paBlob is non-NULL, then it is the responsibility of the caller to
147097** eventually free the returned buffer.
147098**
147099** This function may leave an open sqlite3_blob* handle in the
147100** Fts3Table.pSegments variable. This handle is reused by subsequent calls
147101** to this function. The handle may be closed by calling the
147102** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
147103** performance improvement, but the blob handle should always be closed
147104** before control is returned to the user (to prevent a lock being held
147105** on the database file for longer than necessary). Thus, any virtual table
147106** method (xFilter etc.) that may directly or indirectly call this function
147107** must call sqlite3Fts3SegmentsClose() before returning.
147108*/
147109SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
147110  Fts3Table *p,                   /* FTS3 table handle */
147111  sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
147112  char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
147113  int *pnBlob,                    /* OUT: Size of blob data */
147114  int *pnLoad                     /* OUT: Bytes actually loaded */
147115){
147116  int rc;                         /* Return code */
147117
147118  /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
147119  assert( pnBlob );
147120
147121  if( p->pSegments ){
147122    rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
147123  }else{
147124    if( 0==p->zSegmentsTbl ){
147125      p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
147126      if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
147127    }
147128    rc = sqlite3_blob_open(
147129       p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
147130    );
147131  }
147132
147133  if( rc==SQLITE_OK ){
147134    int nByte = sqlite3_blob_bytes(p->pSegments);
147135    *pnBlob = nByte;
147136    if( paBlob ){
147137      char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
147138      if( !aByte ){
147139        rc = SQLITE_NOMEM;
147140      }else{
147141        if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
147142          nByte = FTS3_NODE_CHUNKSIZE;
147143          *pnLoad = nByte;
147144        }
147145        rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
147146        memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
147147        if( rc!=SQLITE_OK ){
147148          sqlite3_free(aByte);
147149          aByte = 0;
147150        }
147151      }
147152      *paBlob = aByte;
147153    }
147154  }
147155
147156  return rc;
147157}
147158
147159/*
147160** Close the blob handle at p->pSegments, if it is open. See comments above
147161** the sqlite3Fts3ReadBlock() function for details.
147162*/
147163SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
147164  sqlite3_blob_close(p->pSegments);
147165  p->pSegments = 0;
147166}
147167
147168static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
147169  int nRead;                      /* Number of bytes to read */
147170  int rc;                         /* Return code */
147171
147172  nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
147173  rc = sqlite3_blob_read(
147174      pReader->pBlob,
147175      &pReader->aNode[pReader->nPopulate],
147176      nRead,
147177      pReader->nPopulate
147178  );
147179
147180  if( rc==SQLITE_OK ){
147181    pReader->nPopulate += nRead;
147182    memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
147183    if( pReader->nPopulate==pReader->nNode ){
147184      sqlite3_blob_close(pReader->pBlob);
147185      pReader->pBlob = 0;
147186      pReader->nPopulate = 0;
147187    }
147188  }
147189  return rc;
147190}
147191
147192static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
147193  int rc = SQLITE_OK;
147194  assert( !pReader->pBlob
147195       || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
147196  );
147197  while( pReader->pBlob && rc==SQLITE_OK
147198     &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
147199  ){
147200    rc = fts3SegReaderIncrRead(pReader);
147201  }
147202  return rc;
147203}
147204
147205/*
147206** Set an Fts3SegReader cursor to point at EOF.
147207*/
147208static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
147209  if( !fts3SegReaderIsRootOnly(pSeg) ){
147210    sqlite3_free(pSeg->aNode);
147211    sqlite3_blob_close(pSeg->pBlob);
147212    pSeg->pBlob = 0;
147213  }
147214  pSeg->aNode = 0;
147215}
147216
147217/*
147218** Move the iterator passed as the first argument to the next term in the
147219** segment. If successful, SQLITE_OK is returned. If there is no next term,
147220** SQLITE_DONE. Otherwise, an SQLite error code.
147221*/
147222static int fts3SegReaderNext(
147223  Fts3Table *p,
147224  Fts3SegReader *pReader,
147225  int bIncr
147226){
147227  int rc;                         /* Return code of various sub-routines */
147228  char *pNext;                    /* Cursor variable */
147229  int nPrefix;                    /* Number of bytes in term prefix */
147230  int nSuffix;                    /* Number of bytes in term suffix */
147231
147232  if( !pReader->aDoclist ){
147233    pNext = pReader->aNode;
147234  }else{
147235    pNext = &pReader->aDoclist[pReader->nDoclist];
147236  }
147237
147238  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
147239
147240    if( fts3SegReaderIsPending(pReader) ){
147241      Fts3HashElem *pElem = *(pReader->ppNextElem);
147242      sqlite3_free(pReader->aNode);
147243      pReader->aNode = 0;
147244      if( pElem ){
147245        char *aCopy;
147246        PendingList *pList = (PendingList *)fts3HashData(pElem);
147247        int nCopy = pList->nData+1;
147248        pReader->zTerm = (char *)fts3HashKey(pElem);
147249        pReader->nTerm = fts3HashKeysize(pElem);
147250        aCopy = (char*)sqlite3_malloc(nCopy);
147251        if( !aCopy ) return SQLITE_NOMEM;
147252        memcpy(aCopy, pList->aData, nCopy);
147253        pReader->nNode = pReader->nDoclist = nCopy;
147254        pReader->aNode = pReader->aDoclist = aCopy;
147255        pReader->ppNextElem++;
147256        assert( pReader->aNode );
147257      }
147258      return SQLITE_OK;
147259    }
147260
147261    fts3SegReaderSetEof(pReader);
147262
147263    /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
147264    ** blocks have already been traversed.  */
147265    assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
147266    if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
147267      return SQLITE_OK;
147268    }
147269
147270    rc = sqlite3Fts3ReadBlock(
147271        p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
147272        (bIncr ? &pReader->nPopulate : 0)
147273    );
147274    if( rc!=SQLITE_OK ) return rc;
147275    assert( pReader->pBlob==0 );
147276    if( bIncr && pReader->nPopulate<pReader->nNode ){
147277      pReader->pBlob = p->pSegments;
147278      p->pSegments = 0;
147279    }
147280    pNext = pReader->aNode;
147281  }
147282
147283  assert( !fts3SegReaderIsPending(pReader) );
147284
147285  rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
147286  if( rc!=SQLITE_OK ) return rc;
147287
147288  /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
147289  ** safe (no risk of overread) even if the node data is corrupted. */
147290  pNext += fts3GetVarint32(pNext, &nPrefix);
147291  pNext += fts3GetVarint32(pNext, &nSuffix);
147292  if( nPrefix<0 || nSuffix<=0
147293   || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
147294  ){
147295    return FTS_CORRUPT_VTAB;
147296  }
147297
147298  if( nPrefix+nSuffix>pReader->nTermAlloc ){
147299    int nNew = (nPrefix+nSuffix)*2;
147300    char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
147301    if( !zNew ){
147302      return SQLITE_NOMEM;
147303    }
147304    pReader->zTerm = zNew;
147305    pReader->nTermAlloc = nNew;
147306  }
147307
147308  rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
147309  if( rc!=SQLITE_OK ) return rc;
147310
147311  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
147312  pReader->nTerm = nPrefix+nSuffix;
147313  pNext += nSuffix;
147314  pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
147315  pReader->aDoclist = pNext;
147316  pReader->pOffsetList = 0;
147317
147318  /* Check that the doclist does not appear to extend past the end of the
147319  ** b-tree node. And that the final byte of the doclist is 0x00. If either
147320  ** of these statements is untrue, then the data structure is corrupt.
147321  */
147322  if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
147323   || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
147324  ){
147325    return FTS_CORRUPT_VTAB;
147326  }
147327  return SQLITE_OK;
147328}
147329
147330/*
147331** Set the SegReader to point to the first docid in the doclist associated
147332** with the current term.
147333*/
147334static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
147335  int rc = SQLITE_OK;
147336  assert( pReader->aDoclist );
147337  assert( !pReader->pOffsetList );
147338  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
147339    u8 bEof = 0;
147340    pReader->iDocid = 0;
147341    pReader->nOffsetList = 0;
147342    sqlite3Fts3DoclistPrev(0,
147343        pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
147344        &pReader->iDocid, &pReader->nOffsetList, &bEof
147345    );
147346  }else{
147347    rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
147348    if( rc==SQLITE_OK ){
147349      int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
147350      pReader->pOffsetList = &pReader->aDoclist[n];
147351    }
147352  }
147353  return rc;
147354}
147355
147356/*
147357** Advance the SegReader to point to the next docid in the doclist
147358** associated with the current term.
147359**
147360** If arguments ppOffsetList and pnOffsetList are not NULL, then
147361** *ppOffsetList is set to point to the first column-offset list
147362** in the doclist entry (i.e. immediately past the docid varint).
147363** *pnOffsetList is set to the length of the set of column-offset
147364** lists, not including the nul-terminator byte. For example:
147365*/
147366static int fts3SegReaderNextDocid(
147367  Fts3Table *pTab,
147368  Fts3SegReader *pReader,         /* Reader to advance to next docid */
147369  char **ppOffsetList,            /* OUT: Pointer to current position-list */
147370  int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
147371){
147372  int rc = SQLITE_OK;
147373  char *p = pReader->pOffsetList;
147374  char c = 0;
147375
147376  assert( p );
147377
147378  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
147379    /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
147380    ** Pending-terms doclists are always built up in ascending order, so
147381    ** we have to iterate through them backwards here. */
147382    u8 bEof = 0;
147383    if( ppOffsetList ){
147384      *ppOffsetList = pReader->pOffsetList;
147385      *pnOffsetList = pReader->nOffsetList - 1;
147386    }
147387    sqlite3Fts3DoclistPrev(0,
147388        pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
147389        &pReader->nOffsetList, &bEof
147390    );
147391    if( bEof ){
147392      pReader->pOffsetList = 0;
147393    }else{
147394      pReader->pOffsetList = p;
147395    }
147396  }else{
147397    char *pEnd = &pReader->aDoclist[pReader->nDoclist];
147398
147399    /* Pointer p currently points at the first byte of an offset list. The
147400    ** following block advances it to point one byte past the end of
147401    ** the same offset list. */
147402    while( 1 ){
147403
147404      /* The following line of code (and the "p++" below the while() loop) is
147405      ** normally all that is required to move pointer p to the desired
147406      ** position. The exception is if this node is being loaded from disk
147407      ** incrementally and pointer "p" now points to the first byte past
147408      ** the populated part of pReader->aNode[].
147409      */
147410      while( *p | c ) c = *p++ & 0x80;
147411      assert( *p==0 );
147412
147413      if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
147414      rc = fts3SegReaderIncrRead(pReader);
147415      if( rc!=SQLITE_OK ) return rc;
147416    }
147417    p++;
147418
147419    /* If required, populate the output variables with a pointer to and the
147420    ** size of the previous offset-list.
147421    */
147422    if( ppOffsetList ){
147423      *ppOffsetList = pReader->pOffsetList;
147424      *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
147425    }
147426
147427    /* List may have been edited in place by fts3EvalNearTrim() */
147428    while( p<pEnd && *p==0 ) p++;
147429
147430    /* If there are no more entries in the doclist, set pOffsetList to
147431    ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
147432    ** Fts3SegReader.pOffsetList to point to the next offset list before
147433    ** returning.
147434    */
147435    if( p>=pEnd ){
147436      pReader->pOffsetList = 0;
147437    }else{
147438      rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
147439      if( rc==SQLITE_OK ){
147440        sqlite3_int64 iDelta;
147441        pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
147442        if( pTab->bDescIdx ){
147443          pReader->iDocid -= iDelta;
147444        }else{
147445          pReader->iDocid += iDelta;
147446        }
147447      }
147448    }
147449  }
147450
147451  return SQLITE_OK;
147452}
147453
147454
147455SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
147456  Fts3Cursor *pCsr,
147457  Fts3MultiSegReader *pMsr,
147458  int *pnOvfl
147459){
147460  Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
147461  int nOvfl = 0;
147462  int ii;
147463  int rc = SQLITE_OK;
147464  int pgsz = p->nPgsz;
147465
147466  assert( p->bFts4 );
147467  assert( pgsz>0 );
147468
147469  for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
147470    Fts3SegReader *pReader = pMsr->apSegment[ii];
147471    if( !fts3SegReaderIsPending(pReader)
147472     && !fts3SegReaderIsRootOnly(pReader)
147473    ){
147474      sqlite3_int64 jj;
147475      for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
147476        int nBlob;
147477        rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
147478        if( rc!=SQLITE_OK ) break;
147479        if( (nBlob+35)>pgsz ){
147480          nOvfl += (nBlob + 34)/pgsz;
147481        }
147482      }
147483    }
147484  }
147485  *pnOvfl = nOvfl;
147486  return rc;
147487}
147488
147489/*
147490** Free all allocations associated with the iterator passed as the
147491** second argument.
147492*/
147493SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
147494  if( pReader ){
147495    if( !fts3SegReaderIsPending(pReader) ){
147496      sqlite3_free(pReader->zTerm);
147497    }
147498    if( !fts3SegReaderIsRootOnly(pReader) ){
147499      sqlite3_free(pReader->aNode);
147500    }
147501    sqlite3_blob_close(pReader->pBlob);
147502  }
147503  sqlite3_free(pReader);
147504}
147505
147506/*
147507** Allocate a new SegReader object.
147508*/
147509SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
147510  int iAge,                       /* Segment "age". */
147511  int bLookup,                    /* True for a lookup only */
147512  sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
147513  sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
147514  sqlite3_int64 iEndBlock,        /* Final block of segment */
147515  const char *zRoot,              /* Buffer containing root node */
147516  int nRoot,                      /* Size of buffer containing root node */
147517  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
147518){
147519  Fts3SegReader *pReader;         /* Newly allocated SegReader object */
147520  int nExtra = 0;                 /* Bytes to allocate segment root node */
147521
147522  assert( iStartLeaf<=iEndLeaf );
147523  if( iStartLeaf==0 ){
147524    nExtra = nRoot + FTS3_NODE_PADDING;
147525  }
147526
147527  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
147528  if( !pReader ){
147529    return SQLITE_NOMEM;
147530  }
147531  memset(pReader, 0, sizeof(Fts3SegReader));
147532  pReader->iIdx = iAge;
147533  pReader->bLookup = bLookup!=0;
147534  pReader->iStartBlock = iStartLeaf;
147535  pReader->iLeafEndBlock = iEndLeaf;
147536  pReader->iEndBlock = iEndBlock;
147537
147538  if( nExtra ){
147539    /* The entire segment is stored in the root node. */
147540    pReader->aNode = (char *)&pReader[1];
147541    pReader->rootOnly = 1;
147542    pReader->nNode = nRoot;
147543    memcpy(pReader->aNode, zRoot, nRoot);
147544    memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
147545  }else{
147546    pReader->iCurrentBlock = iStartLeaf-1;
147547  }
147548  *ppReader = pReader;
147549  return SQLITE_OK;
147550}
147551
147552/*
147553** This is a comparison function used as a qsort() callback when sorting
147554** an array of pending terms by term. This occurs as part of flushing
147555** the contents of the pending-terms hash table to the database.
147556*/
147557static int SQLITE_CDECL fts3CompareElemByTerm(
147558  const void *lhs,
147559  const void *rhs
147560){
147561  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
147562  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
147563  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
147564  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
147565
147566  int n = (n1<n2 ? n1 : n2);
147567  int c = memcmp(z1, z2, n);
147568  if( c==0 ){
147569    c = n1 - n2;
147570  }
147571  return c;
147572}
147573
147574/*
147575** This function is used to allocate an Fts3SegReader that iterates through
147576** a subset of the terms stored in the Fts3Table.pendingTerms array.
147577**
147578** If the isPrefixIter parameter is zero, then the returned SegReader iterates
147579** through each term in the pending-terms table. Or, if isPrefixIter is
147580** non-zero, it iterates through each term and its prefixes. For example, if
147581** the pending terms hash table contains the terms "sqlite", "mysql" and
147582** "firebird", then the iterator visits the following 'terms' (in the order
147583** shown):
147584**
147585**   f fi fir fire fireb firebi firebir firebird
147586**   m my mys mysq mysql
147587**   s sq sql sqli sqlit sqlite
147588**
147589** Whereas if isPrefixIter is zero, the terms visited are:
147590**
147591**   firebird mysql sqlite
147592*/
147593SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
147594  Fts3Table *p,                   /* Virtual table handle */
147595  int iIndex,                     /* Index for p->aIndex */
147596  const char *zTerm,              /* Term to search for */
147597  int nTerm,                      /* Size of buffer zTerm */
147598  int bPrefix,                    /* True for a prefix iterator */
147599  Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
147600){
147601  Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
147602  Fts3HashElem *pE;               /* Iterator variable */
147603  Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
147604  int nElem = 0;                  /* Size of array at aElem */
147605  int rc = SQLITE_OK;             /* Return Code */
147606  Fts3Hash *pHash;
147607
147608  pHash = &p->aIndex[iIndex].hPending;
147609  if( bPrefix ){
147610    int nAlloc = 0;               /* Size of allocated array at aElem */
147611
147612    for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
147613      char *zKey = (char *)fts3HashKey(pE);
147614      int nKey = fts3HashKeysize(pE);
147615      if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
147616        if( nElem==nAlloc ){
147617          Fts3HashElem **aElem2;
147618          nAlloc += 16;
147619          aElem2 = (Fts3HashElem **)sqlite3_realloc(
147620              aElem, nAlloc*sizeof(Fts3HashElem *)
147621          );
147622          if( !aElem2 ){
147623            rc = SQLITE_NOMEM;
147624            nElem = 0;
147625            break;
147626          }
147627          aElem = aElem2;
147628        }
147629
147630        aElem[nElem++] = pE;
147631      }
147632    }
147633
147634    /* If more than one term matches the prefix, sort the Fts3HashElem
147635    ** objects in term order using qsort(). This uses the same comparison
147636    ** callback as is used when flushing terms to disk.
147637    */
147638    if( nElem>1 ){
147639      qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
147640    }
147641
147642  }else{
147643    /* The query is a simple term lookup that matches at most one term in
147644    ** the index. All that is required is a straight hash-lookup.
147645    **
147646    ** Because the stack address of pE may be accessed via the aElem pointer
147647    ** below, the "Fts3HashElem *pE" must be declared so that it is valid
147648    ** within this entire function, not just this "else{...}" block.
147649    */
147650    pE = fts3HashFindElem(pHash, zTerm, nTerm);
147651    if( pE ){
147652      aElem = &pE;
147653      nElem = 1;
147654    }
147655  }
147656
147657  if( nElem>0 ){
147658    int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
147659    pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
147660    if( !pReader ){
147661      rc = SQLITE_NOMEM;
147662    }else{
147663      memset(pReader, 0, nByte);
147664      pReader->iIdx = 0x7FFFFFFF;
147665      pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
147666      memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
147667    }
147668  }
147669
147670  if( bPrefix ){
147671    sqlite3_free(aElem);
147672  }
147673  *ppReader = pReader;
147674  return rc;
147675}
147676
147677/*
147678** Compare the entries pointed to by two Fts3SegReader structures.
147679** Comparison is as follows:
147680**
147681**   1) EOF is greater than not EOF.
147682**
147683**   2) The current terms (if any) are compared using memcmp(). If one
147684**      term is a prefix of another, the longer term is considered the
147685**      larger.
147686**
147687**   3) By segment age. An older segment is considered larger.
147688*/
147689static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
147690  int rc;
147691  if( pLhs->aNode && pRhs->aNode ){
147692    int rc2 = pLhs->nTerm - pRhs->nTerm;
147693    if( rc2<0 ){
147694      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
147695    }else{
147696      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
147697    }
147698    if( rc==0 ){
147699      rc = rc2;
147700    }
147701  }else{
147702    rc = (pLhs->aNode==0) - (pRhs->aNode==0);
147703  }
147704  if( rc==0 ){
147705    rc = pRhs->iIdx - pLhs->iIdx;
147706  }
147707  assert( rc!=0 );
147708  return rc;
147709}
147710
147711/*
147712** A different comparison function for SegReader structures. In this
147713** version, it is assumed that each SegReader points to an entry in
147714** a doclist for identical terms. Comparison is made as follows:
147715**
147716**   1) EOF (end of doclist in this case) is greater than not EOF.
147717**
147718**   2) By current docid.
147719**
147720**   3) By segment age. An older segment is considered larger.
147721*/
147722static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
147723  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
147724  if( rc==0 ){
147725    if( pLhs->iDocid==pRhs->iDocid ){
147726      rc = pRhs->iIdx - pLhs->iIdx;
147727    }else{
147728      rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
147729    }
147730  }
147731  assert( pLhs->aNode && pRhs->aNode );
147732  return rc;
147733}
147734static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
147735  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
147736  if( rc==0 ){
147737    if( pLhs->iDocid==pRhs->iDocid ){
147738      rc = pRhs->iIdx - pLhs->iIdx;
147739    }else{
147740      rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
147741    }
147742  }
147743  assert( pLhs->aNode && pRhs->aNode );
147744  return rc;
147745}
147746
147747/*
147748** Compare the term that the Fts3SegReader object passed as the first argument
147749** points to with the term specified by arguments zTerm and nTerm.
147750**
147751** If the pSeg iterator is already at EOF, return 0. Otherwise, return
147752** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
147753** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
147754*/
147755static int fts3SegReaderTermCmp(
147756  Fts3SegReader *pSeg,            /* Segment reader object */
147757  const char *zTerm,              /* Term to compare to */
147758  int nTerm                       /* Size of term zTerm in bytes */
147759){
147760  int res = 0;
147761  if( pSeg->aNode ){
147762    if( pSeg->nTerm>nTerm ){
147763      res = memcmp(pSeg->zTerm, zTerm, nTerm);
147764    }else{
147765      res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
147766    }
147767    if( res==0 ){
147768      res = pSeg->nTerm-nTerm;
147769    }
147770  }
147771  return res;
147772}
147773
147774/*
147775** Argument apSegment is an array of nSegment elements. It is known that
147776** the final (nSegment-nSuspect) members are already in sorted order
147777** (according to the comparison function provided). This function shuffles
147778** the array around until all entries are in sorted order.
147779*/
147780static void fts3SegReaderSort(
147781  Fts3SegReader **apSegment,                     /* Array to sort entries of */
147782  int nSegment,                                  /* Size of apSegment array */
147783  int nSuspect,                                  /* Unsorted entry count */
147784  int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
147785){
147786  int i;                          /* Iterator variable */
147787
147788  assert( nSuspect<=nSegment );
147789
147790  if( nSuspect==nSegment ) nSuspect--;
147791  for(i=nSuspect-1; i>=0; i--){
147792    int j;
147793    for(j=i; j<(nSegment-1); j++){
147794      Fts3SegReader *pTmp;
147795      if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
147796      pTmp = apSegment[j+1];
147797      apSegment[j+1] = apSegment[j];
147798      apSegment[j] = pTmp;
147799    }
147800  }
147801
147802#ifndef NDEBUG
147803  /* Check that the list really is sorted now. */
147804  for(i=0; i<(nSuspect-1); i++){
147805    assert( xCmp(apSegment[i], apSegment[i+1])<0 );
147806  }
147807#endif
147808}
147809
147810/*
147811** Insert a record into the %_segments table.
147812*/
147813static int fts3WriteSegment(
147814  Fts3Table *p,                   /* Virtual table handle */
147815  sqlite3_int64 iBlock,           /* Block id for new block */
147816  char *z,                        /* Pointer to buffer containing block data */
147817  int n                           /* Size of buffer z in bytes */
147818){
147819  sqlite3_stmt *pStmt;
147820  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
147821  if( rc==SQLITE_OK ){
147822    sqlite3_bind_int64(pStmt, 1, iBlock);
147823    sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
147824    sqlite3_step(pStmt);
147825    rc = sqlite3_reset(pStmt);
147826  }
147827  return rc;
147828}
147829
147830/*
147831** Find the largest relative level number in the table. If successful, set
147832** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
147833** set *pnMax to zero and return an SQLite error code.
147834*/
147835SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
147836  int rc;
147837  int mxLevel = 0;
147838  sqlite3_stmt *pStmt = 0;
147839
147840  rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
147841  if( rc==SQLITE_OK ){
147842    if( SQLITE_ROW==sqlite3_step(pStmt) ){
147843      mxLevel = sqlite3_column_int(pStmt, 0);
147844    }
147845    rc = sqlite3_reset(pStmt);
147846  }
147847  *pnMax = mxLevel;
147848  return rc;
147849}
147850
147851/*
147852** Insert a record into the %_segdir table.
147853*/
147854static int fts3WriteSegdir(
147855  Fts3Table *p,                   /* Virtual table handle */
147856  sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
147857  int iIdx,                       /* Value for "idx" field */
147858  sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
147859  sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
147860  sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
147861  sqlite3_int64 nLeafData,        /* Bytes of leaf data in segment */
147862  char *zRoot,                    /* Blob value for "root" field */
147863  int nRoot                       /* Number of bytes in buffer zRoot */
147864){
147865  sqlite3_stmt *pStmt;
147866  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
147867  if( rc==SQLITE_OK ){
147868    sqlite3_bind_int64(pStmt, 1, iLevel);
147869    sqlite3_bind_int(pStmt, 2, iIdx);
147870    sqlite3_bind_int64(pStmt, 3, iStartBlock);
147871    sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
147872    if( nLeafData==0 ){
147873      sqlite3_bind_int64(pStmt, 5, iEndBlock);
147874    }else{
147875      char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
147876      if( !zEnd ) return SQLITE_NOMEM;
147877      sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
147878    }
147879    sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
147880    sqlite3_step(pStmt);
147881    rc = sqlite3_reset(pStmt);
147882  }
147883  return rc;
147884}
147885
147886/*
147887** Return the size of the common prefix (if any) shared by zPrev and
147888** zNext, in bytes. For example,
147889**
147890**   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
147891**   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
147892**   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
147893*/
147894static int fts3PrefixCompress(
147895  const char *zPrev,              /* Buffer containing previous term */
147896  int nPrev,                      /* Size of buffer zPrev in bytes */
147897  const char *zNext,              /* Buffer containing next term */
147898  int nNext                       /* Size of buffer zNext in bytes */
147899){
147900  int n;
147901  UNUSED_PARAMETER(nNext);
147902  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
147903  return n;
147904}
147905
147906/*
147907** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
147908** (according to memcmp) than the previous term.
147909*/
147910static int fts3NodeAddTerm(
147911  Fts3Table *p,                   /* Virtual table handle */
147912  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
147913  int isCopyTerm,                 /* True if zTerm/nTerm is transient */
147914  const char *zTerm,              /* Pointer to buffer containing term */
147915  int nTerm                       /* Size of term in bytes */
147916){
147917  SegmentNode *pTree = *ppTree;
147918  int rc;
147919  SegmentNode *pNew;
147920
147921  /* First try to append the term to the current node. Return early if
147922  ** this is possible.
147923  */
147924  if( pTree ){
147925    int nData = pTree->nData;     /* Current size of node in bytes */
147926    int nReq = nData;             /* Required space after adding zTerm */
147927    int nPrefix;                  /* Number of bytes of prefix compression */
147928    int nSuffix;                  /* Suffix length */
147929
147930    nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
147931    nSuffix = nTerm-nPrefix;
147932
147933    nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
147934    if( nReq<=p->nNodeSize || !pTree->zTerm ){
147935
147936      if( nReq>p->nNodeSize ){
147937        /* An unusual case: this is the first term to be added to the node
147938        ** and the static node buffer (p->nNodeSize bytes) is not large
147939        ** enough. Use a separately malloced buffer instead This wastes
147940        ** p->nNodeSize bytes, but since this scenario only comes about when
147941        ** the database contain two terms that share a prefix of almost 2KB,
147942        ** this is not expected to be a serious problem.
147943        */
147944        assert( pTree->aData==(char *)&pTree[1] );
147945        pTree->aData = (char *)sqlite3_malloc(nReq);
147946        if( !pTree->aData ){
147947          return SQLITE_NOMEM;
147948        }
147949      }
147950
147951      if( pTree->zTerm ){
147952        /* There is no prefix-length field for first term in a node */
147953        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
147954      }
147955
147956      nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
147957      memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
147958      pTree->nData = nData + nSuffix;
147959      pTree->nEntry++;
147960
147961      if( isCopyTerm ){
147962        if( pTree->nMalloc<nTerm ){
147963          char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
147964          if( !zNew ){
147965            return SQLITE_NOMEM;
147966          }
147967          pTree->nMalloc = nTerm*2;
147968          pTree->zMalloc = zNew;
147969        }
147970        pTree->zTerm = pTree->zMalloc;
147971        memcpy(pTree->zTerm, zTerm, nTerm);
147972        pTree->nTerm = nTerm;
147973      }else{
147974        pTree->zTerm = (char *)zTerm;
147975        pTree->nTerm = nTerm;
147976      }
147977      return SQLITE_OK;
147978    }
147979  }
147980
147981  /* If control flows to here, it was not possible to append zTerm to the
147982  ** current node. Create a new node (a right-sibling of the current node).
147983  ** If this is the first node in the tree, the term is added to it.
147984  **
147985  ** Otherwise, the term is not added to the new node, it is left empty for
147986  ** now. Instead, the term is inserted into the parent of pTree. If pTree
147987  ** has no parent, one is created here.
147988  */
147989  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
147990  if( !pNew ){
147991    return SQLITE_NOMEM;
147992  }
147993  memset(pNew, 0, sizeof(SegmentNode));
147994  pNew->nData = 1 + FTS3_VARINT_MAX;
147995  pNew->aData = (char *)&pNew[1];
147996
147997  if( pTree ){
147998    SegmentNode *pParent = pTree->pParent;
147999    rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
148000    if( pTree->pParent==0 ){
148001      pTree->pParent = pParent;
148002    }
148003    pTree->pRight = pNew;
148004    pNew->pLeftmost = pTree->pLeftmost;
148005    pNew->pParent = pParent;
148006    pNew->zMalloc = pTree->zMalloc;
148007    pNew->nMalloc = pTree->nMalloc;
148008    pTree->zMalloc = 0;
148009  }else{
148010    pNew->pLeftmost = pNew;
148011    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
148012  }
148013
148014  *ppTree = pNew;
148015  return rc;
148016}
148017
148018/*
148019** Helper function for fts3NodeWrite().
148020*/
148021static int fts3TreeFinishNode(
148022  SegmentNode *pTree,
148023  int iHeight,
148024  sqlite3_int64 iLeftChild
148025){
148026  int nStart;
148027  assert( iHeight>=1 && iHeight<128 );
148028  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
148029  pTree->aData[nStart] = (char)iHeight;
148030  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
148031  return nStart;
148032}
148033
148034/*
148035** Write the buffer for the segment node pTree and all of its peers to the
148036** database. Then call this function recursively to write the parent of
148037** pTree and its peers to the database.
148038**
148039** Except, if pTree is a root node, do not write it to the database. Instead,
148040** set output variables *paRoot and *pnRoot to contain the root node.
148041**
148042** If successful, SQLITE_OK is returned and output variable *piLast is
148043** set to the largest blockid written to the database (or zero if no
148044** blocks were written to the db). Otherwise, an SQLite error code is
148045** returned.
148046*/
148047static int fts3NodeWrite(
148048  Fts3Table *p,                   /* Virtual table handle */
148049  SegmentNode *pTree,             /* SegmentNode handle */
148050  int iHeight,                    /* Height of this node in tree */
148051  sqlite3_int64 iLeaf,            /* Block id of first leaf node */
148052  sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
148053  sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
148054  char **paRoot,                  /* OUT: Data for root node */
148055  int *pnRoot                     /* OUT: Size of root node in bytes */
148056){
148057  int rc = SQLITE_OK;
148058
148059  if( !pTree->pParent ){
148060    /* Root node of the tree. */
148061    int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
148062    *piLast = iFree-1;
148063    *pnRoot = pTree->nData - nStart;
148064    *paRoot = &pTree->aData[nStart];
148065  }else{
148066    SegmentNode *pIter;
148067    sqlite3_int64 iNextFree = iFree;
148068    sqlite3_int64 iNextLeaf = iLeaf;
148069    for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
148070      int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
148071      int nWrite = pIter->nData - nStart;
148072
148073      rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
148074      iNextFree++;
148075      iNextLeaf += (pIter->nEntry+1);
148076    }
148077    if( rc==SQLITE_OK ){
148078      assert( iNextLeaf==iFree );
148079      rc = fts3NodeWrite(
148080          p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
148081      );
148082    }
148083  }
148084
148085  return rc;
148086}
148087
148088/*
148089** Free all memory allocations associated with the tree pTree.
148090*/
148091static void fts3NodeFree(SegmentNode *pTree){
148092  if( pTree ){
148093    SegmentNode *p = pTree->pLeftmost;
148094    fts3NodeFree(p->pParent);
148095    while( p ){
148096      SegmentNode *pRight = p->pRight;
148097      if( p->aData!=(char *)&p[1] ){
148098        sqlite3_free(p->aData);
148099      }
148100      assert( pRight==0 || p->zMalloc==0 );
148101      sqlite3_free(p->zMalloc);
148102      sqlite3_free(p);
148103      p = pRight;
148104    }
148105  }
148106}
148107
148108/*
148109** Add a term to the segment being constructed by the SegmentWriter object
148110** *ppWriter. When adding the first term to a segment, *ppWriter should
148111** be passed NULL. This function will allocate a new SegmentWriter object
148112** and return it via the input/output variable *ppWriter in this case.
148113**
148114** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
148115*/
148116static int fts3SegWriterAdd(
148117  Fts3Table *p,                   /* Virtual table handle */
148118  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
148119  int isCopyTerm,                 /* True if buffer zTerm must be copied */
148120  const char *zTerm,              /* Pointer to buffer containing term */
148121  int nTerm,                      /* Size of term in bytes */
148122  const char *aDoclist,           /* Pointer to buffer containing doclist */
148123  int nDoclist                    /* Size of doclist in bytes */
148124){
148125  int nPrefix;                    /* Size of term prefix in bytes */
148126  int nSuffix;                    /* Size of term suffix in bytes */
148127  int nReq;                       /* Number of bytes required on leaf page */
148128  int nData;
148129  SegmentWriter *pWriter = *ppWriter;
148130
148131  if( !pWriter ){
148132    int rc;
148133    sqlite3_stmt *pStmt;
148134
148135    /* Allocate the SegmentWriter structure */
148136    pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
148137    if( !pWriter ) return SQLITE_NOMEM;
148138    memset(pWriter, 0, sizeof(SegmentWriter));
148139    *ppWriter = pWriter;
148140
148141    /* Allocate a buffer in which to accumulate data */
148142    pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
148143    if( !pWriter->aData ) return SQLITE_NOMEM;
148144    pWriter->nSize = p->nNodeSize;
148145
148146    /* Find the next free blockid in the %_segments table */
148147    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
148148    if( rc!=SQLITE_OK ) return rc;
148149    if( SQLITE_ROW==sqlite3_step(pStmt) ){
148150      pWriter->iFree = sqlite3_column_int64(pStmt, 0);
148151      pWriter->iFirst = pWriter->iFree;
148152    }
148153    rc = sqlite3_reset(pStmt);
148154    if( rc!=SQLITE_OK ) return rc;
148155  }
148156  nData = pWriter->nData;
148157
148158  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
148159  nSuffix = nTerm-nPrefix;
148160
148161  /* Figure out how many bytes are required by this new entry */
148162  nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
148163    sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
148164    nSuffix +                               /* Term suffix */
148165    sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
148166    nDoclist;                               /* Doclist data */
148167
148168  if( nData>0 && nData+nReq>p->nNodeSize ){
148169    int rc;
148170
148171    /* The current leaf node is full. Write it out to the database. */
148172    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
148173    if( rc!=SQLITE_OK ) return rc;
148174    p->nLeafAdd++;
148175
148176    /* Add the current term to the interior node tree. The term added to
148177    ** the interior tree must:
148178    **
148179    **   a) be greater than the largest term on the leaf node just written
148180    **      to the database (still available in pWriter->zTerm), and
148181    **
148182    **   b) be less than or equal to the term about to be added to the new
148183    **      leaf node (zTerm/nTerm).
148184    **
148185    ** In other words, it must be the prefix of zTerm 1 byte longer than
148186    ** the common prefix (if any) of zTerm and pWriter->zTerm.
148187    */
148188    assert( nPrefix<nTerm );
148189    rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
148190    if( rc!=SQLITE_OK ) return rc;
148191
148192    nData = 0;
148193    pWriter->nTerm = 0;
148194
148195    nPrefix = 0;
148196    nSuffix = nTerm;
148197    nReq = 1 +                              /* varint containing prefix size */
148198      sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
148199      nTerm +                               /* Term suffix */
148200      sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
148201      nDoclist;                             /* Doclist data */
148202  }
148203
148204  /* Increase the total number of bytes written to account for the new entry. */
148205  pWriter->nLeafData += nReq;
148206
148207  /* If the buffer currently allocated is too small for this entry, realloc
148208  ** the buffer to make it large enough.
148209  */
148210  if( nReq>pWriter->nSize ){
148211    char *aNew = sqlite3_realloc(pWriter->aData, nReq);
148212    if( !aNew ) return SQLITE_NOMEM;
148213    pWriter->aData = aNew;
148214    pWriter->nSize = nReq;
148215  }
148216  assert( nData+nReq<=pWriter->nSize );
148217
148218  /* Append the prefix-compressed term and doclist to the buffer. */
148219  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
148220  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
148221  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
148222  nData += nSuffix;
148223  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
148224  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
148225  pWriter->nData = nData + nDoclist;
148226
148227  /* Save the current term so that it can be used to prefix-compress the next.
148228  ** If the isCopyTerm parameter is true, then the buffer pointed to by
148229  ** zTerm is transient, so take a copy of the term data. Otherwise, just
148230  ** store a copy of the pointer.
148231  */
148232  if( isCopyTerm ){
148233    if( nTerm>pWriter->nMalloc ){
148234      char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
148235      if( !zNew ){
148236        return SQLITE_NOMEM;
148237      }
148238      pWriter->nMalloc = nTerm*2;
148239      pWriter->zMalloc = zNew;
148240      pWriter->zTerm = zNew;
148241    }
148242    assert( pWriter->zTerm==pWriter->zMalloc );
148243    memcpy(pWriter->zTerm, zTerm, nTerm);
148244  }else{
148245    pWriter->zTerm = (char *)zTerm;
148246  }
148247  pWriter->nTerm = nTerm;
148248
148249  return SQLITE_OK;
148250}
148251
148252/*
148253** Flush all data associated with the SegmentWriter object pWriter to the
148254** database. This function must be called after all terms have been added
148255** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
148256** returned. Otherwise, an SQLite error code.
148257*/
148258static int fts3SegWriterFlush(
148259  Fts3Table *p,                   /* Virtual table handle */
148260  SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
148261  sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
148262  int iIdx                        /* Value for 'idx' column of %_segdir */
148263){
148264  int rc;                         /* Return code */
148265  if( pWriter->pTree ){
148266    sqlite3_int64 iLast = 0;      /* Largest block id written to database */
148267    sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
148268    char *zRoot = NULL;           /* Pointer to buffer containing root node */
148269    int nRoot = 0;                /* Size of buffer zRoot */
148270
148271    iLastLeaf = pWriter->iFree;
148272    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
148273    if( rc==SQLITE_OK ){
148274      rc = fts3NodeWrite(p, pWriter->pTree, 1,
148275          pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
148276    }
148277    if( rc==SQLITE_OK ){
148278      rc = fts3WriteSegdir(p, iLevel, iIdx,
148279          pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
148280    }
148281  }else{
148282    /* The entire tree fits on the root node. Write it to the segdir table. */
148283    rc = fts3WriteSegdir(p, iLevel, iIdx,
148284        0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
148285  }
148286  p->nLeafAdd++;
148287  return rc;
148288}
148289
148290/*
148291** Release all memory held by the SegmentWriter object passed as the
148292** first argument.
148293*/
148294static void fts3SegWriterFree(SegmentWriter *pWriter){
148295  if( pWriter ){
148296    sqlite3_free(pWriter->aData);
148297    sqlite3_free(pWriter->zMalloc);
148298    fts3NodeFree(pWriter->pTree);
148299    sqlite3_free(pWriter);
148300  }
148301}
148302
148303/*
148304** The first value in the apVal[] array is assumed to contain an integer.
148305** This function tests if there exist any documents with docid values that
148306** are different from that integer. i.e. if deleting the document with docid
148307** pRowid would mean the FTS3 table were empty.
148308**
148309** If successful, *pisEmpty is set to true if the table is empty except for
148310** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
148311** error occurs, an SQLite error code is returned.
148312*/
148313static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
148314  sqlite3_stmt *pStmt;
148315  int rc;
148316  if( p->zContentTbl ){
148317    /* If using the content=xxx option, assume the table is never empty */
148318    *pisEmpty = 0;
148319    rc = SQLITE_OK;
148320  }else{
148321    rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
148322    if( rc==SQLITE_OK ){
148323      if( SQLITE_ROW==sqlite3_step(pStmt) ){
148324        *pisEmpty = sqlite3_column_int(pStmt, 0);
148325      }
148326      rc = sqlite3_reset(pStmt);
148327    }
148328  }
148329  return rc;
148330}
148331
148332/*
148333** Set *pnMax to the largest segment level in the database for the index
148334** iIndex.
148335**
148336** Segment levels are stored in the 'level' column of the %_segdir table.
148337**
148338** Return SQLITE_OK if successful, or an SQLite error code if not.
148339*/
148340static int fts3SegmentMaxLevel(
148341  Fts3Table *p,
148342  int iLangid,
148343  int iIndex,
148344  sqlite3_int64 *pnMax
148345){
148346  sqlite3_stmt *pStmt;
148347  int rc;
148348  assert( iIndex>=0 && iIndex<p->nIndex );
148349
148350  /* Set pStmt to the compiled version of:
148351  **
148352  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
148353  **
148354  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
148355  */
148356  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
148357  if( rc!=SQLITE_OK ) return rc;
148358  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
148359  sqlite3_bind_int64(pStmt, 2,
148360      getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
148361  );
148362  if( SQLITE_ROW==sqlite3_step(pStmt) ){
148363    *pnMax = sqlite3_column_int64(pStmt, 0);
148364  }
148365  return sqlite3_reset(pStmt);
148366}
148367
148368/*
148369** iAbsLevel is an absolute level that may be assumed to exist within
148370** the database. This function checks if it is the largest level number
148371** within its index. Assuming no error occurs, *pbMax is set to 1 if
148372** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
148373** is returned. If an error occurs, an error code is returned and the
148374** final value of *pbMax is undefined.
148375*/
148376static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
148377
148378  /* Set pStmt to the compiled version of:
148379  **
148380  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
148381  **
148382  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
148383  */
148384  sqlite3_stmt *pStmt;
148385  int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
148386  if( rc!=SQLITE_OK ) return rc;
148387  sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
148388  sqlite3_bind_int64(pStmt, 2,
148389      ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
148390  );
148391
148392  *pbMax = 0;
148393  if( SQLITE_ROW==sqlite3_step(pStmt) ){
148394    *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
148395  }
148396  return sqlite3_reset(pStmt);
148397}
148398
148399/*
148400** Delete all entries in the %_segments table associated with the segment
148401** opened with seg-reader pSeg. This function does not affect the contents
148402** of the %_segdir table.
148403*/
148404static int fts3DeleteSegment(
148405  Fts3Table *p,                   /* FTS table handle */
148406  Fts3SegReader *pSeg             /* Segment to delete */
148407){
148408  int rc = SQLITE_OK;             /* Return code */
148409  if( pSeg->iStartBlock ){
148410    sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
148411    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
148412    if( rc==SQLITE_OK ){
148413      sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
148414      sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
148415      sqlite3_step(pDelete);
148416      rc = sqlite3_reset(pDelete);
148417    }
148418  }
148419  return rc;
148420}
148421
148422/*
148423** This function is used after merging multiple segments into a single large
148424** segment to delete the old, now redundant, segment b-trees. Specifically,
148425** it:
148426**
148427**   1) Deletes all %_segments entries for the segments associated with
148428**      each of the SegReader objects in the array passed as the third
148429**      argument, and
148430**
148431**   2) deletes all %_segdir entries with level iLevel, or all %_segdir
148432**      entries regardless of level if (iLevel<0).
148433**
148434** SQLITE_OK is returned if successful, otherwise an SQLite error code.
148435*/
148436static int fts3DeleteSegdir(
148437  Fts3Table *p,                   /* Virtual table handle */
148438  int iLangid,                    /* Language id */
148439  int iIndex,                     /* Index for p->aIndex */
148440  int iLevel,                     /* Level of %_segdir entries to delete */
148441  Fts3SegReader **apSegment,      /* Array of SegReader objects */
148442  int nReader                     /* Size of array apSegment */
148443){
148444  int rc = SQLITE_OK;             /* Return Code */
148445  int i;                          /* Iterator variable */
148446  sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
148447
148448  for(i=0; rc==SQLITE_OK && i<nReader; i++){
148449    rc = fts3DeleteSegment(p, apSegment[i]);
148450  }
148451  if( rc!=SQLITE_OK ){
148452    return rc;
148453  }
148454
148455  assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
148456  if( iLevel==FTS3_SEGCURSOR_ALL ){
148457    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
148458    if( rc==SQLITE_OK ){
148459      sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
148460      sqlite3_bind_int64(pDelete, 2,
148461          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
148462      );
148463    }
148464  }else{
148465    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
148466    if( rc==SQLITE_OK ){
148467      sqlite3_bind_int64(
148468          pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
148469      );
148470    }
148471  }
148472
148473  if( rc==SQLITE_OK ){
148474    sqlite3_step(pDelete);
148475    rc = sqlite3_reset(pDelete);
148476  }
148477
148478  return rc;
148479}
148480
148481/*
148482** When this function is called, buffer *ppList (size *pnList bytes) contains
148483** a position list that may (or may not) feature multiple columns. This
148484** function adjusts the pointer *ppList and the length *pnList so that they
148485** identify the subset of the position list that corresponds to column iCol.
148486**
148487** If there are no entries in the input position list for column iCol, then
148488** *pnList is set to zero before returning.
148489**
148490** If parameter bZero is non-zero, then any part of the input list following
148491** the end of the output list is zeroed before returning.
148492*/
148493static void fts3ColumnFilter(
148494  int iCol,                       /* Column to filter on */
148495  int bZero,                      /* Zero out anything following *ppList */
148496  char **ppList,                  /* IN/OUT: Pointer to position list */
148497  int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
148498){
148499  char *pList = *ppList;
148500  int nList = *pnList;
148501  char *pEnd = &pList[nList];
148502  int iCurrent = 0;
148503  char *p = pList;
148504
148505  assert( iCol>=0 );
148506  while( 1 ){
148507    char c = 0;
148508    while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
148509
148510    if( iCol==iCurrent ){
148511      nList = (int)(p - pList);
148512      break;
148513    }
148514
148515    nList -= (int)(p - pList);
148516    pList = p;
148517    if( nList==0 ){
148518      break;
148519    }
148520    p = &pList[1];
148521    p += fts3GetVarint32(p, &iCurrent);
148522  }
148523
148524  if( bZero && &pList[nList]!=pEnd ){
148525    memset(&pList[nList], 0, pEnd - &pList[nList]);
148526  }
148527  *ppList = pList;
148528  *pnList = nList;
148529}
148530
148531/*
148532** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
148533** existing data). Grow the buffer if required.
148534**
148535** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
148536** trying to resize the buffer, return SQLITE_NOMEM.
148537*/
148538static int fts3MsrBufferData(
148539  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
148540  char *pList,
148541  int nList
148542){
148543  if( nList>pMsr->nBuffer ){
148544    char *pNew;
148545    pMsr->nBuffer = nList*2;
148546    pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
148547    if( !pNew ) return SQLITE_NOMEM;
148548    pMsr->aBuffer = pNew;
148549  }
148550
148551  memcpy(pMsr->aBuffer, pList, nList);
148552  return SQLITE_OK;
148553}
148554
148555SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
148556  Fts3Table *p,                   /* Virtual table handle */
148557  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
148558  sqlite3_int64 *piDocid,         /* OUT: Docid value */
148559  char **paPoslist,               /* OUT: Pointer to position list */
148560  int *pnPoslist                  /* OUT: Size of position list in bytes */
148561){
148562  int nMerge = pMsr->nAdvance;
148563  Fts3SegReader **apSegment = pMsr->apSegment;
148564  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
148565    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
148566  );
148567
148568  if( nMerge==0 ){
148569    *paPoslist = 0;
148570    return SQLITE_OK;
148571  }
148572
148573  while( 1 ){
148574    Fts3SegReader *pSeg;
148575    pSeg = pMsr->apSegment[0];
148576
148577    if( pSeg->pOffsetList==0 ){
148578      *paPoslist = 0;
148579      break;
148580    }else{
148581      int rc;
148582      char *pList;
148583      int nList;
148584      int j;
148585      sqlite3_int64 iDocid = apSegment[0]->iDocid;
148586
148587      rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
148588      j = 1;
148589      while( rc==SQLITE_OK
148590        && j<nMerge
148591        && apSegment[j]->pOffsetList
148592        && apSegment[j]->iDocid==iDocid
148593      ){
148594        rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
148595        j++;
148596      }
148597      if( rc!=SQLITE_OK ) return rc;
148598      fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
148599
148600      if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
148601        rc = fts3MsrBufferData(pMsr, pList, nList+1);
148602        if( rc!=SQLITE_OK ) return rc;
148603        assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
148604        pList = pMsr->aBuffer;
148605      }
148606
148607      if( pMsr->iColFilter>=0 ){
148608        fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
148609      }
148610
148611      if( nList>0 ){
148612        *paPoslist = pList;
148613        *piDocid = iDocid;
148614        *pnPoslist = nList;
148615        break;
148616      }
148617    }
148618  }
148619
148620  return SQLITE_OK;
148621}
148622
148623static int fts3SegReaderStart(
148624  Fts3Table *p,                   /* Virtual table handle */
148625  Fts3MultiSegReader *pCsr,       /* Cursor object */
148626  const char *zTerm,              /* Term searched for (or NULL) */
148627  int nTerm                       /* Length of zTerm in bytes */
148628){
148629  int i;
148630  int nSeg = pCsr->nSegment;
148631
148632  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
148633  ** for, then advance each segment iterator until it points to a term of
148634  ** equal or greater value than the specified term. This prevents many
148635  ** unnecessary merge/sort operations for the case where single segment
148636  ** b-tree leaf nodes contain more than one term.
148637  */
148638  for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
148639    int res = 0;
148640    Fts3SegReader *pSeg = pCsr->apSegment[i];
148641    do {
148642      int rc = fts3SegReaderNext(p, pSeg, 0);
148643      if( rc!=SQLITE_OK ) return rc;
148644    }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
148645
148646    if( pSeg->bLookup && res!=0 ){
148647      fts3SegReaderSetEof(pSeg);
148648    }
148649  }
148650  fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
148651
148652  return SQLITE_OK;
148653}
148654
148655SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
148656  Fts3Table *p,                   /* Virtual table handle */
148657  Fts3MultiSegReader *pCsr,       /* Cursor object */
148658  Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
148659){
148660  pCsr->pFilter = pFilter;
148661  return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
148662}
148663
148664SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
148665  Fts3Table *p,                   /* Virtual table handle */
148666  Fts3MultiSegReader *pCsr,       /* Cursor object */
148667  int iCol,                       /* Column to match on. */
148668  const char *zTerm,              /* Term to iterate through a doclist for */
148669  int nTerm                       /* Number of bytes in zTerm */
148670){
148671  int i;
148672  int rc;
148673  int nSegment = pCsr->nSegment;
148674  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
148675    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
148676  );
148677
148678  assert( pCsr->pFilter==0 );
148679  assert( zTerm && nTerm>0 );
148680
148681  /* Advance each segment iterator until it points to the term zTerm/nTerm. */
148682  rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
148683  if( rc!=SQLITE_OK ) return rc;
148684
148685  /* Determine how many of the segments actually point to zTerm/nTerm. */
148686  for(i=0; i<nSegment; i++){
148687    Fts3SegReader *pSeg = pCsr->apSegment[i];
148688    if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
148689      break;
148690    }
148691  }
148692  pCsr->nAdvance = i;
148693
148694  /* Advance each of the segments to point to the first docid. */
148695  for(i=0; i<pCsr->nAdvance; i++){
148696    rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
148697    if( rc!=SQLITE_OK ) return rc;
148698  }
148699  fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
148700
148701  assert( iCol<0 || iCol<p->nColumn );
148702  pCsr->iColFilter = iCol;
148703
148704  return SQLITE_OK;
148705}
148706
148707/*
148708** This function is called on a MultiSegReader that has been started using
148709** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
148710** have been made. Calling this function puts the MultiSegReader in such
148711** a state that if the next two calls are:
148712**
148713**   sqlite3Fts3SegReaderStart()
148714**   sqlite3Fts3SegReaderStep()
148715**
148716** then the entire doclist for the term is available in
148717** MultiSegReader.aDoclist/nDoclist.
148718*/
148719SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
148720  int i;                          /* Used to iterate through segment-readers */
148721
148722  assert( pCsr->zTerm==0 );
148723  assert( pCsr->nTerm==0 );
148724  assert( pCsr->aDoclist==0 );
148725  assert( pCsr->nDoclist==0 );
148726
148727  pCsr->nAdvance = 0;
148728  pCsr->bRestart = 1;
148729  for(i=0; i<pCsr->nSegment; i++){
148730    pCsr->apSegment[i]->pOffsetList = 0;
148731    pCsr->apSegment[i]->nOffsetList = 0;
148732    pCsr->apSegment[i]->iDocid = 0;
148733  }
148734
148735  return SQLITE_OK;
148736}
148737
148738
148739SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
148740  Fts3Table *p,                   /* Virtual table handle */
148741  Fts3MultiSegReader *pCsr        /* Cursor object */
148742){
148743  int rc = SQLITE_OK;
148744
148745  int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
148746  int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
148747  int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
148748  int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
148749  int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
148750  int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
148751
148752  Fts3SegReader **apSegment = pCsr->apSegment;
148753  int nSegment = pCsr->nSegment;
148754  Fts3SegFilter *pFilter = pCsr->pFilter;
148755  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
148756    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
148757  );
148758
148759  if( pCsr->nSegment==0 ) return SQLITE_OK;
148760
148761  do {
148762    int nMerge;
148763    int i;
148764
148765    /* Advance the first pCsr->nAdvance entries in the apSegment[] array
148766    ** forward. Then sort the list in order of current term again.
148767    */
148768    for(i=0; i<pCsr->nAdvance; i++){
148769      Fts3SegReader *pSeg = apSegment[i];
148770      if( pSeg->bLookup ){
148771        fts3SegReaderSetEof(pSeg);
148772      }else{
148773        rc = fts3SegReaderNext(p, pSeg, 0);
148774      }
148775      if( rc!=SQLITE_OK ) return rc;
148776    }
148777    fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
148778    pCsr->nAdvance = 0;
148779
148780    /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
148781    assert( rc==SQLITE_OK );
148782    if( apSegment[0]->aNode==0 ) break;
148783
148784    pCsr->nTerm = apSegment[0]->nTerm;
148785    pCsr->zTerm = apSegment[0]->zTerm;
148786
148787    /* If this is a prefix-search, and if the term that apSegment[0] points
148788    ** to does not share a suffix with pFilter->zTerm/nTerm, then all
148789    ** required callbacks have been made. In this case exit early.
148790    **
148791    ** Similarly, if this is a search for an exact match, and the first term
148792    ** of segment apSegment[0] is not a match, exit early.
148793    */
148794    if( pFilter->zTerm && !isScan ){
148795      if( pCsr->nTerm<pFilter->nTerm
148796       || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
148797       || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
148798      ){
148799        break;
148800      }
148801    }
148802
148803    nMerge = 1;
148804    while( nMerge<nSegment
148805        && apSegment[nMerge]->aNode
148806        && apSegment[nMerge]->nTerm==pCsr->nTerm
148807        && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
148808    ){
148809      nMerge++;
148810    }
148811
148812    assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
148813    if( nMerge==1
148814     && !isIgnoreEmpty
148815     && !isFirst
148816     && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
148817    ){
148818      pCsr->nDoclist = apSegment[0]->nDoclist;
148819      if( fts3SegReaderIsPending(apSegment[0]) ){
148820        rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
148821        pCsr->aDoclist = pCsr->aBuffer;
148822      }else{
148823        pCsr->aDoclist = apSegment[0]->aDoclist;
148824      }
148825      if( rc==SQLITE_OK ) rc = SQLITE_ROW;
148826    }else{
148827      int nDoclist = 0;           /* Size of doclist */
148828      sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
148829
148830      /* The current term of the first nMerge entries in the array
148831      ** of Fts3SegReader objects is the same. The doclists must be merged
148832      ** and a single term returned with the merged doclist.
148833      */
148834      for(i=0; i<nMerge; i++){
148835        fts3SegReaderFirstDocid(p, apSegment[i]);
148836      }
148837      fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
148838      while( apSegment[0]->pOffsetList ){
148839        int j;                    /* Number of segments that share a docid */
148840        char *pList = 0;
148841        int nList = 0;
148842        int nByte;
148843        sqlite3_int64 iDocid = apSegment[0]->iDocid;
148844        fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
148845        j = 1;
148846        while( j<nMerge
148847            && apSegment[j]->pOffsetList
148848            && apSegment[j]->iDocid==iDocid
148849        ){
148850          fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
148851          j++;
148852        }
148853
148854        if( isColFilter ){
148855          fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
148856        }
148857
148858        if( !isIgnoreEmpty || nList>0 ){
148859
148860          /* Calculate the 'docid' delta value to write into the merged
148861          ** doclist. */
148862          sqlite3_int64 iDelta;
148863          if( p->bDescIdx && nDoclist>0 ){
148864            iDelta = iPrev - iDocid;
148865          }else{
148866            iDelta = iDocid - iPrev;
148867          }
148868          assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
148869          assert( nDoclist>0 || iDelta==iDocid );
148870
148871          nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
148872          if( nDoclist+nByte>pCsr->nBuffer ){
148873            char *aNew;
148874            pCsr->nBuffer = (nDoclist+nByte)*2;
148875            aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
148876            if( !aNew ){
148877              return SQLITE_NOMEM;
148878            }
148879            pCsr->aBuffer = aNew;
148880          }
148881
148882          if( isFirst ){
148883            char *a = &pCsr->aBuffer[nDoclist];
148884            int nWrite;
148885
148886            nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
148887            if( nWrite ){
148888              iPrev = iDocid;
148889              nDoclist += nWrite;
148890            }
148891          }else{
148892            nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
148893            iPrev = iDocid;
148894            if( isRequirePos ){
148895              memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
148896              nDoclist += nList;
148897              pCsr->aBuffer[nDoclist++] = '\0';
148898            }
148899          }
148900        }
148901
148902        fts3SegReaderSort(apSegment, nMerge, j, xCmp);
148903      }
148904      if( nDoclist>0 ){
148905        pCsr->aDoclist = pCsr->aBuffer;
148906        pCsr->nDoclist = nDoclist;
148907        rc = SQLITE_ROW;
148908      }
148909    }
148910    pCsr->nAdvance = nMerge;
148911  }while( rc==SQLITE_OK );
148912
148913  return rc;
148914}
148915
148916
148917SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
148918  Fts3MultiSegReader *pCsr       /* Cursor object */
148919){
148920  if( pCsr ){
148921    int i;
148922    for(i=0; i<pCsr->nSegment; i++){
148923      sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
148924    }
148925    sqlite3_free(pCsr->apSegment);
148926    sqlite3_free(pCsr->aBuffer);
148927
148928    pCsr->nSegment = 0;
148929    pCsr->apSegment = 0;
148930    pCsr->aBuffer = 0;
148931  }
148932}
148933
148934/*
148935** Decode the "end_block" field, selected by column iCol of the SELECT
148936** statement passed as the first argument.
148937**
148938** The "end_block" field may contain either an integer, or a text field
148939** containing the text representation of two non-negative integers separated
148940** by one or more space (0x20) characters. In the first case, set *piEndBlock
148941** to the integer value and *pnByte to zero before returning. In the second,
148942** set *piEndBlock to the first value and *pnByte to the second.
148943*/
148944static void fts3ReadEndBlockField(
148945  sqlite3_stmt *pStmt,
148946  int iCol,
148947  i64 *piEndBlock,
148948  i64 *pnByte
148949){
148950  const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
148951  if( zText ){
148952    int i;
148953    int iMul = 1;
148954    i64 iVal = 0;
148955    for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
148956      iVal = iVal*10 + (zText[i] - '0');
148957    }
148958    *piEndBlock = iVal;
148959    while( zText[i]==' ' ) i++;
148960    iVal = 0;
148961    if( zText[i]=='-' ){
148962      i++;
148963      iMul = -1;
148964    }
148965    for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
148966      iVal = iVal*10 + (zText[i] - '0');
148967    }
148968    *pnByte = (iVal * (i64)iMul);
148969  }
148970}
148971
148972
148973/*
148974** A segment of size nByte bytes has just been written to absolute level
148975** iAbsLevel. Promote any segments that should be promoted as a result.
148976*/
148977static int fts3PromoteSegments(
148978  Fts3Table *p,                   /* FTS table handle */
148979  sqlite3_int64 iAbsLevel,        /* Absolute level just updated */
148980  sqlite3_int64 nByte             /* Size of new segment at iAbsLevel */
148981){
148982  int rc = SQLITE_OK;
148983  sqlite3_stmt *pRange;
148984
148985  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
148986
148987  if( rc==SQLITE_OK ){
148988    int bOk = 0;
148989    i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
148990    i64 nLimit = (nByte*3)/2;
148991
148992    /* Loop through all entries in the %_segdir table corresponding to
148993    ** segments in this index on levels greater than iAbsLevel. If there is
148994    ** at least one such segment, and it is possible to determine that all
148995    ** such segments are smaller than nLimit bytes in size, they will be
148996    ** promoted to level iAbsLevel.  */
148997    sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
148998    sqlite3_bind_int64(pRange, 2, iLast);
148999    while( SQLITE_ROW==sqlite3_step(pRange) ){
149000      i64 nSize = 0, dummy;
149001      fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
149002      if( nSize<=0 || nSize>nLimit ){
149003        /* If nSize==0, then the %_segdir.end_block field does not not
149004        ** contain a size value. This happens if it was written by an
149005        ** old version of FTS. In this case it is not possible to determine
149006        ** the size of the segment, and so segment promotion does not
149007        ** take place.  */
149008        bOk = 0;
149009        break;
149010      }
149011      bOk = 1;
149012    }
149013    rc = sqlite3_reset(pRange);
149014
149015    if( bOk ){
149016      int iIdx = 0;
149017      sqlite3_stmt *pUpdate1 = 0;
149018      sqlite3_stmt *pUpdate2 = 0;
149019
149020      if( rc==SQLITE_OK ){
149021        rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
149022      }
149023      if( rc==SQLITE_OK ){
149024        rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
149025      }
149026
149027      if( rc==SQLITE_OK ){
149028
149029        /* Loop through all %_segdir entries for segments in this index with
149030        ** levels equal to or greater than iAbsLevel. As each entry is visited,
149031        ** updated it to set (level = -1) and (idx = N), where N is 0 for the
149032        ** oldest segment in the range, 1 for the next oldest, and so on.
149033        **
149034        ** In other words, move all segments being promoted to level -1,
149035        ** setting the "idx" fields as appropriate to keep them in the same
149036        ** order. The contents of level -1 (which is never used, except
149037        ** transiently here), will be moved back to level iAbsLevel below.  */
149038        sqlite3_bind_int64(pRange, 1, iAbsLevel);
149039        while( SQLITE_ROW==sqlite3_step(pRange) ){
149040          sqlite3_bind_int(pUpdate1, 1, iIdx++);
149041          sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
149042          sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
149043          sqlite3_step(pUpdate1);
149044          rc = sqlite3_reset(pUpdate1);
149045          if( rc!=SQLITE_OK ){
149046            sqlite3_reset(pRange);
149047            break;
149048          }
149049        }
149050      }
149051      if( rc==SQLITE_OK ){
149052        rc = sqlite3_reset(pRange);
149053      }
149054
149055      /* Move level -1 to level iAbsLevel */
149056      if( rc==SQLITE_OK ){
149057        sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
149058        sqlite3_step(pUpdate2);
149059        rc = sqlite3_reset(pUpdate2);
149060      }
149061    }
149062  }
149063
149064
149065  return rc;
149066}
149067
149068/*
149069** Merge all level iLevel segments in the database into a single
149070** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
149071** single segment with a level equal to the numerically largest level
149072** currently present in the database.
149073**
149074** If this function is called with iLevel<0, but there is only one
149075** segment in the database, SQLITE_DONE is returned immediately.
149076** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
149077** an SQLite error code is returned.
149078*/
149079static int fts3SegmentMerge(
149080  Fts3Table *p,
149081  int iLangid,                    /* Language id to merge */
149082  int iIndex,                     /* Index in p->aIndex[] to merge */
149083  int iLevel                      /* Level to merge */
149084){
149085  int rc;                         /* Return code */
149086  int iIdx = 0;                   /* Index of new segment */
149087  sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
149088  SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
149089  Fts3SegFilter filter;           /* Segment term filter condition */
149090  Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
149091  int bIgnoreEmpty = 0;           /* True to ignore empty segments */
149092  i64 iMaxLevel = 0;              /* Max level number for this index/langid */
149093
149094  assert( iLevel==FTS3_SEGCURSOR_ALL
149095       || iLevel==FTS3_SEGCURSOR_PENDING
149096       || iLevel>=0
149097  );
149098  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
149099  assert( iIndex>=0 && iIndex<p->nIndex );
149100
149101  rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
149102  if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
149103
149104  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
149105    rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
149106    if( rc!=SQLITE_OK ) goto finished;
149107  }
149108
149109  if( iLevel==FTS3_SEGCURSOR_ALL ){
149110    /* This call is to merge all segments in the database to a single
149111    ** segment. The level of the new segment is equal to the numerically
149112    ** greatest segment level currently present in the database for this
149113    ** index. The idx of the new segment is always 0.  */
149114    if( csr.nSegment==1 ){
149115      rc = SQLITE_DONE;
149116      goto finished;
149117    }
149118    iNewLevel = iMaxLevel;
149119    bIgnoreEmpty = 1;
149120
149121  }else{
149122    /* This call is to merge all segments at level iLevel. find the next
149123    ** available segment index at level iLevel+1. The call to
149124    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
149125    ** a single iLevel+2 segment if necessary.  */
149126    assert( FTS3_SEGCURSOR_PENDING==-1 );
149127    iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
149128    rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
149129    bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
149130  }
149131  if( rc!=SQLITE_OK ) goto finished;
149132
149133  assert( csr.nSegment>0 );
149134  assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
149135  assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
149136
149137  memset(&filter, 0, sizeof(Fts3SegFilter));
149138  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
149139  filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
149140
149141  rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
149142  while( SQLITE_OK==rc ){
149143    rc = sqlite3Fts3SegReaderStep(p, &csr);
149144    if( rc!=SQLITE_ROW ) break;
149145    rc = fts3SegWriterAdd(p, &pWriter, 1,
149146        csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
149147  }
149148  if( rc!=SQLITE_OK ) goto finished;
149149  assert( pWriter || bIgnoreEmpty );
149150
149151  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
149152    rc = fts3DeleteSegdir(
149153        p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
149154    );
149155    if( rc!=SQLITE_OK ) goto finished;
149156  }
149157  if( pWriter ){
149158    rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
149159    if( rc==SQLITE_OK ){
149160      if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
149161        rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
149162      }
149163    }
149164  }
149165
149166 finished:
149167  fts3SegWriterFree(pWriter);
149168  sqlite3Fts3SegReaderFinish(&csr);
149169  return rc;
149170}
149171
149172
149173/*
149174** Flush the contents of pendingTerms to level 0 segments.
149175*/
149176SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
149177  int rc = SQLITE_OK;
149178  int i;
149179
149180  for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
149181    rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
149182    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
149183  }
149184  sqlite3Fts3PendingTermsClear(p);
149185
149186  /* Determine the auto-incr-merge setting if unknown.  If enabled,
149187  ** estimate the number of leaf blocks of content to be written
149188  */
149189  if( rc==SQLITE_OK && p->bHasStat
149190   && p->nAutoincrmerge==0xff && p->nLeafAdd>0
149191  ){
149192    sqlite3_stmt *pStmt = 0;
149193    rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
149194    if( rc==SQLITE_OK ){
149195      sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
149196      rc = sqlite3_step(pStmt);
149197      if( rc==SQLITE_ROW ){
149198        p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
149199        if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
149200      }else if( rc==SQLITE_DONE ){
149201        p->nAutoincrmerge = 0;
149202      }
149203      rc = sqlite3_reset(pStmt);
149204    }
149205  }
149206  return rc;
149207}
149208
149209/*
149210** Encode N integers as varints into a blob.
149211*/
149212static void fts3EncodeIntArray(
149213  int N,             /* The number of integers to encode */
149214  u32 *a,            /* The integer values */
149215  char *zBuf,        /* Write the BLOB here */
149216  int *pNBuf         /* Write number of bytes if zBuf[] used here */
149217){
149218  int i, j;
149219  for(i=j=0; i<N; i++){
149220    j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
149221  }
149222  *pNBuf = j;
149223}
149224
149225/*
149226** Decode a blob of varints into N integers
149227*/
149228static void fts3DecodeIntArray(
149229  int N,             /* The number of integers to decode */
149230  u32 *a,            /* Write the integer values */
149231  const char *zBuf,  /* The BLOB containing the varints */
149232  int nBuf           /* size of the BLOB */
149233){
149234  int i, j;
149235  UNUSED_PARAMETER(nBuf);
149236  for(i=j=0; i<N; i++){
149237    sqlite3_int64 x;
149238    j += sqlite3Fts3GetVarint(&zBuf[j], &x);
149239    assert(j<=nBuf);
149240    a[i] = (u32)(x & 0xffffffff);
149241  }
149242}
149243
149244/*
149245** Insert the sizes (in tokens) for each column of the document
149246** with docid equal to p->iPrevDocid.  The sizes are encoded as
149247** a blob of varints.
149248*/
149249static void fts3InsertDocsize(
149250  int *pRC,                       /* Result code */
149251  Fts3Table *p,                   /* Table into which to insert */
149252  u32 *aSz                        /* Sizes of each column, in tokens */
149253){
149254  char *pBlob;             /* The BLOB encoding of the document size */
149255  int nBlob;               /* Number of bytes in the BLOB */
149256  sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
149257  int rc;                  /* Result code from subfunctions */
149258
149259  if( *pRC ) return;
149260  pBlob = sqlite3_malloc( 10*p->nColumn );
149261  if( pBlob==0 ){
149262    *pRC = SQLITE_NOMEM;
149263    return;
149264  }
149265  fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
149266  rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
149267  if( rc ){
149268    sqlite3_free(pBlob);
149269    *pRC = rc;
149270    return;
149271  }
149272  sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
149273  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
149274  sqlite3_step(pStmt);
149275  *pRC = sqlite3_reset(pStmt);
149276}
149277
149278/*
149279** Record 0 of the %_stat table contains a blob consisting of N varints,
149280** where N is the number of user defined columns in the fts3 table plus
149281** two. If nCol is the number of user defined columns, then values of the
149282** varints are set as follows:
149283**
149284**   Varint 0:       Total number of rows in the table.
149285**
149286**   Varint 1..nCol: For each column, the total number of tokens stored in
149287**                   the column for all rows of the table.
149288**
149289**   Varint 1+nCol:  The total size, in bytes, of all text values in all
149290**                   columns of all rows of the table.
149291**
149292*/
149293static void fts3UpdateDocTotals(
149294  int *pRC,                       /* The result code */
149295  Fts3Table *p,                   /* Table being updated */
149296  u32 *aSzIns,                    /* Size increases */
149297  u32 *aSzDel,                    /* Size decreases */
149298  int nChng                       /* Change in the number of documents */
149299){
149300  char *pBlob;             /* Storage for BLOB written into %_stat */
149301  int nBlob;               /* Size of BLOB written into %_stat */
149302  u32 *a;                  /* Array of integers that becomes the BLOB */
149303  sqlite3_stmt *pStmt;     /* Statement for reading and writing */
149304  int i;                   /* Loop counter */
149305  int rc;                  /* Result code from subfunctions */
149306
149307  const int nStat = p->nColumn+2;
149308
149309  if( *pRC ) return;
149310  a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
149311  if( a==0 ){
149312    *pRC = SQLITE_NOMEM;
149313    return;
149314  }
149315  pBlob = (char*)&a[nStat];
149316  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
149317  if( rc ){
149318    sqlite3_free(a);
149319    *pRC = rc;
149320    return;
149321  }
149322  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
149323  if( sqlite3_step(pStmt)==SQLITE_ROW ){
149324    fts3DecodeIntArray(nStat, a,
149325         sqlite3_column_blob(pStmt, 0),
149326         sqlite3_column_bytes(pStmt, 0));
149327  }else{
149328    memset(a, 0, sizeof(u32)*(nStat) );
149329  }
149330  rc = sqlite3_reset(pStmt);
149331  if( rc!=SQLITE_OK ){
149332    sqlite3_free(a);
149333    *pRC = rc;
149334    return;
149335  }
149336  if( nChng<0 && a[0]<(u32)(-nChng) ){
149337    a[0] = 0;
149338  }else{
149339    a[0] += nChng;
149340  }
149341  for(i=0; i<p->nColumn+1; i++){
149342    u32 x = a[i+1];
149343    if( x+aSzIns[i] < aSzDel[i] ){
149344      x = 0;
149345    }else{
149346      x = x + aSzIns[i] - aSzDel[i];
149347    }
149348    a[i+1] = x;
149349  }
149350  fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
149351  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
149352  if( rc ){
149353    sqlite3_free(a);
149354    *pRC = rc;
149355    return;
149356  }
149357  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
149358  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
149359  sqlite3_step(pStmt);
149360  *pRC = sqlite3_reset(pStmt);
149361  sqlite3_free(a);
149362}
149363
149364/*
149365** Merge the entire database so that there is one segment for each
149366** iIndex/iLangid combination.
149367*/
149368static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
149369  int bSeenDone = 0;
149370  int rc;
149371  sqlite3_stmt *pAllLangid = 0;
149372
149373  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
149374  if( rc==SQLITE_OK ){
149375    int rc2;
149376    sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
149377    sqlite3_bind_int(pAllLangid, 2, p->nIndex);
149378    while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
149379      int i;
149380      int iLangid = sqlite3_column_int(pAllLangid, 0);
149381      for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
149382        rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
149383        if( rc==SQLITE_DONE ){
149384          bSeenDone = 1;
149385          rc = SQLITE_OK;
149386        }
149387      }
149388    }
149389    rc2 = sqlite3_reset(pAllLangid);
149390    if( rc==SQLITE_OK ) rc = rc2;
149391  }
149392
149393  sqlite3Fts3SegmentsClose(p);
149394  sqlite3Fts3PendingTermsClear(p);
149395
149396  return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
149397}
149398
149399/*
149400** This function is called when the user executes the following statement:
149401**
149402**     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
149403**
149404** The entire FTS index is discarded and rebuilt. If the table is one
149405** created using the content=xxx option, then the new index is based on
149406** the current contents of the xxx table. Otherwise, it is rebuilt based
149407** on the contents of the %_content table.
149408*/
149409static int fts3DoRebuild(Fts3Table *p){
149410  int rc;                         /* Return Code */
149411
149412  rc = fts3DeleteAll(p, 0);
149413  if( rc==SQLITE_OK ){
149414    u32 *aSz = 0;
149415    u32 *aSzIns = 0;
149416    u32 *aSzDel = 0;
149417    sqlite3_stmt *pStmt = 0;
149418    int nEntry = 0;
149419
149420    /* Compose and prepare an SQL statement to loop through the content table */
149421    char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
149422    if( !zSql ){
149423      rc = SQLITE_NOMEM;
149424    }else{
149425      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
149426      sqlite3_free(zSql);
149427    }
149428
149429    if( rc==SQLITE_OK ){
149430      int nByte = sizeof(u32) * (p->nColumn+1)*3;
149431      aSz = (u32 *)sqlite3_malloc(nByte);
149432      if( aSz==0 ){
149433        rc = SQLITE_NOMEM;
149434      }else{
149435        memset(aSz, 0, nByte);
149436        aSzIns = &aSz[p->nColumn+1];
149437        aSzDel = &aSzIns[p->nColumn+1];
149438      }
149439    }
149440
149441    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
149442      int iCol;
149443      int iLangid = langidFromSelect(p, pStmt);
149444      rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
149445      memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
149446      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
149447        if( p->abNotindexed[iCol]==0 ){
149448          const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
149449          rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
149450          aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
149451        }
149452      }
149453      if( p->bHasDocsize ){
149454        fts3InsertDocsize(&rc, p, aSz);
149455      }
149456      if( rc!=SQLITE_OK ){
149457        sqlite3_finalize(pStmt);
149458        pStmt = 0;
149459      }else{
149460        nEntry++;
149461        for(iCol=0; iCol<=p->nColumn; iCol++){
149462          aSzIns[iCol] += aSz[iCol];
149463        }
149464      }
149465    }
149466    if( p->bFts4 ){
149467      fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
149468    }
149469    sqlite3_free(aSz);
149470
149471    if( pStmt ){
149472      int rc2 = sqlite3_finalize(pStmt);
149473      if( rc==SQLITE_OK ){
149474        rc = rc2;
149475      }
149476    }
149477  }
149478
149479  return rc;
149480}
149481
149482
149483/*
149484** This function opens a cursor used to read the input data for an
149485** incremental merge operation. Specifically, it opens a cursor to scan
149486** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
149487** level iAbsLevel.
149488*/
149489static int fts3IncrmergeCsr(
149490  Fts3Table *p,                   /* FTS3 table handle */
149491  sqlite3_int64 iAbsLevel,        /* Absolute level to open */
149492  int nSeg,                       /* Number of segments to merge */
149493  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
149494){
149495  int rc;                         /* Return Code */
149496  sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */
149497  int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
149498
149499  /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
149500  memset(pCsr, 0, sizeof(*pCsr));
149501  nByte = sizeof(Fts3SegReader *) * nSeg;
149502  pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
149503
149504  if( pCsr->apSegment==0 ){
149505    rc = SQLITE_NOMEM;
149506  }else{
149507    memset(pCsr->apSegment, 0, nByte);
149508    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
149509  }
149510  if( rc==SQLITE_OK ){
149511    int i;
149512    int rc2;
149513    sqlite3_bind_int64(pStmt, 1, iAbsLevel);
149514    assert( pCsr->nSegment==0 );
149515    for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
149516      rc = sqlite3Fts3SegReaderNew(i, 0,
149517          sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
149518          sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
149519          sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
149520          sqlite3_column_blob(pStmt, 4),         /* segdir.root */
149521          sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
149522          &pCsr->apSegment[i]
149523      );
149524      pCsr->nSegment++;
149525    }
149526    rc2 = sqlite3_reset(pStmt);
149527    if( rc==SQLITE_OK ) rc = rc2;
149528  }
149529
149530  return rc;
149531}
149532
149533typedef struct IncrmergeWriter IncrmergeWriter;
149534typedef struct NodeWriter NodeWriter;
149535typedef struct Blob Blob;
149536typedef struct NodeReader NodeReader;
149537
149538/*
149539** An instance of the following structure is used as a dynamic buffer
149540** to build up nodes or other blobs of data in.
149541**
149542** The function blobGrowBuffer() is used to extend the allocation.
149543*/
149544struct Blob {
149545  char *a;                        /* Pointer to allocation */
149546  int n;                          /* Number of valid bytes of data in a[] */
149547  int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
149548};
149549
149550/*
149551** This structure is used to build up buffers containing segment b-tree
149552** nodes (blocks).
149553*/
149554struct NodeWriter {
149555  sqlite3_int64 iBlock;           /* Current block id */
149556  Blob key;                       /* Last key written to the current block */
149557  Blob block;                     /* Current block image */
149558};
149559
149560/*
149561** An object of this type contains the state required to create or append
149562** to an appendable b-tree segment.
149563*/
149564struct IncrmergeWriter {
149565  int nLeafEst;                   /* Space allocated for leaf blocks */
149566  int nWork;                      /* Number of leaf pages flushed */
149567  sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
149568  int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
149569  sqlite3_int64 iStart;           /* Block number of first allocated block */
149570  sqlite3_int64 iEnd;             /* Block number of last allocated block */
149571  sqlite3_int64 nLeafData;        /* Bytes of leaf page data so far */
149572  u8 bNoLeafData;                 /* If true, store 0 for segment size */
149573  NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
149574};
149575
149576/*
149577** An object of the following type is used to read data from a single
149578** FTS segment node. See the following functions:
149579**
149580**     nodeReaderInit()
149581**     nodeReaderNext()
149582**     nodeReaderRelease()
149583*/
149584struct NodeReader {
149585  const char *aNode;
149586  int nNode;
149587  int iOff;                       /* Current offset within aNode[] */
149588
149589  /* Output variables. Containing the current node entry. */
149590  sqlite3_int64 iChild;           /* Pointer to child node */
149591  Blob term;                      /* Current term */
149592  const char *aDoclist;           /* Pointer to doclist */
149593  int nDoclist;                   /* Size of doclist in bytes */
149594};
149595
149596/*
149597** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
149598** Otherwise, if the allocation at pBlob->a is not already at least nMin
149599** bytes in size, extend (realloc) it to be so.
149600**
149601** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
149602** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
149603** to reflect the new size of the pBlob->a[] buffer.
149604*/
149605static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
149606  if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
149607    int nAlloc = nMin;
149608    char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
149609    if( a ){
149610      pBlob->nAlloc = nAlloc;
149611      pBlob->a = a;
149612    }else{
149613      *pRc = SQLITE_NOMEM;
149614    }
149615  }
149616}
149617
149618/*
149619** Attempt to advance the node-reader object passed as the first argument to
149620** the next entry on the node.
149621**
149622** Return an error code if an error occurs (SQLITE_NOMEM is possible).
149623** Otherwise return SQLITE_OK. If there is no next entry on the node
149624** (e.g. because the current entry is the last) set NodeReader->aNode to
149625** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
149626** variables for the new entry.
149627*/
149628static int nodeReaderNext(NodeReader *p){
149629  int bFirst = (p->term.n==0);    /* True for first term on the node */
149630  int nPrefix = 0;                /* Bytes to copy from previous term */
149631  int nSuffix = 0;                /* Bytes to append to the prefix */
149632  int rc = SQLITE_OK;             /* Return code */
149633
149634  assert( p->aNode );
149635  if( p->iChild && bFirst==0 ) p->iChild++;
149636  if( p->iOff>=p->nNode ){
149637    /* EOF */
149638    p->aNode = 0;
149639  }else{
149640    if( bFirst==0 ){
149641      p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
149642    }
149643    p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
149644
149645    blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
149646    if( rc==SQLITE_OK ){
149647      memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
149648      p->term.n = nPrefix+nSuffix;
149649      p->iOff += nSuffix;
149650      if( p->iChild==0 ){
149651        p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
149652        p->aDoclist = &p->aNode[p->iOff];
149653        p->iOff += p->nDoclist;
149654      }
149655    }
149656  }
149657
149658  assert( p->iOff<=p->nNode );
149659
149660  return rc;
149661}
149662
149663/*
149664** Release all dynamic resources held by node-reader object *p.
149665*/
149666static void nodeReaderRelease(NodeReader *p){
149667  sqlite3_free(p->term.a);
149668}
149669
149670/*
149671** Initialize a node-reader object to read the node in buffer aNode/nNode.
149672**
149673** If successful, SQLITE_OK is returned and the NodeReader object set to
149674** point to the first entry on the node (if any). Otherwise, an SQLite
149675** error code is returned.
149676*/
149677static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
149678  memset(p, 0, sizeof(NodeReader));
149679  p->aNode = aNode;
149680  p->nNode = nNode;
149681
149682  /* Figure out if this is a leaf or an internal node. */
149683  if( p->aNode[0] ){
149684    /* An internal node. */
149685    p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
149686  }else{
149687    p->iOff = 1;
149688  }
149689
149690  return nodeReaderNext(p);
149691}
149692
149693/*
149694** This function is called while writing an FTS segment each time a leaf o
149695** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
149696** to be greater than the largest key on the node just written, but smaller
149697** than or equal to the first key that will be written to the next leaf
149698** node.
149699**
149700** The block id of the leaf node just written to disk may be found in
149701** (pWriter->aNodeWriter[0].iBlock) when this function is called.
149702*/
149703static int fts3IncrmergePush(
149704  Fts3Table *p,                   /* Fts3 table handle */
149705  IncrmergeWriter *pWriter,       /* Writer object */
149706  const char *zTerm,              /* Term to write to internal node */
149707  int nTerm                       /* Bytes at zTerm */
149708){
149709  sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
149710  int iLayer;
149711
149712  assert( nTerm>0 );
149713  for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
149714    sqlite3_int64 iNextPtr = 0;
149715    NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
149716    int rc = SQLITE_OK;
149717    int nPrefix;
149718    int nSuffix;
149719    int nSpace;
149720
149721    /* Figure out how much space the key will consume if it is written to
149722    ** the current node of layer iLayer. Due to the prefix compression,
149723    ** the space required changes depending on which node the key is to
149724    ** be added to.  */
149725    nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
149726    nSuffix = nTerm - nPrefix;
149727    nSpace  = sqlite3Fts3VarintLen(nPrefix);
149728    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
149729
149730    if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
149731      /* If the current node of layer iLayer contains zero keys, or if adding
149732      ** the key to it will not cause it to grow to larger than nNodeSize
149733      ** bytes in size, write the key here.  */
149734
149735      Blob *pBlk = &pNode->block;
149736      if( pBlk->n==0 ){
149737        blobGrowBuffer(pBlk, p->nNodeSize, &rc);
149738        if( rc==SQLITE_OK ){
149739          pBlk->a[0] = (char)iLayer;
149740          pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
149741        }
149742      }
149743      blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
149744      blobGrowBuffer(&pNode->key, nTerm, &rc);
149745
149746      if( rc==SQLITE_OK ){
149747        if( pNode->key.n ){
149748          pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
149749        }
149750        pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
149751        memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
149752        pBlk->n += nSuffix;
149753
149754        memcpy(pNode->key.a, zTerm, nTerm);
149755        pNode->key.n = nTerm;
149756      }
149757    }else{
149758      /* Otherwise, flush the current node of layer iLayer to disk.
149759      ** Then allocate a new, empty sibling node. The key will be written
149760      ** into the parent of this node. */
149761      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
149762
149763      assert( pNode->block.nAlloc>=p->nNodeSize );
149764      pNode->block.a[0] = (char)iLayer;
149765      pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
149766
149767      iNextPtr = pNode->iBlock;
149768      pNode->iBlock++;
149769      pNode->key.n = 0;
149770    }
149771
149772    if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
149773    iPtr = iNextPtr;
149774  }
149775
149776  assert( 0 );
149777  return 0;
149778}
149779
149780/*
149781** Append a term and (optionally) doclist to the FTS segment node currently
149782** stored in blob *pNode. The node need not contain any terms, but the
149783** header must be written before this function is called.
149784**
149785** A node header is a single 0x00 byte for a leaf node, or a height varint
149786** followed by the left-hand-child varint for an internal node.
149787**
149788** The term to be appended is passed via arguments zTerm/nTerm. For a
149789** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
149790** node, both aDoclist and nDoclist must be passed 0.
149791**
149792** If the size of the value in blob pPrev is zero, then this is the first
149793** term written to the node. Otherwise, pPrev contains a copy of the
149794** previous term. Before this function returns, it is updated to contain a
149795** copy of zTerm/nTerm.
149796**
149797** It is assumed that the buffer associated with pNode is already large
149798** enough to accommodate the new entry. The buffer associated with pPrev
149799** is extended by this function if requrired.
149800**
149801** If an error (i.e. OOM condition) occurs, an SQLite error code is
149802** returned. Otherwise, SQLITE_OK.
149803*/
149804static int fts3AppendToNode(
149805  Blob *pNode,                    /* Current node image to append to */
149806  Blob *pPrev,                    /* Buffer containing previous term written */
149807  const char *zTerm,              /* New term to write */
149808  int nTerm,                      /* Size of zTerm in bytes */
149809  const char *aDoclist,           /* Doclist (or NULL) to write */
149810  int nDoclist                    /* Size of aDoclist in bytes */
149811){
149812  int rc = SQLITE_OK;             /* Return code */
149813  int bFirst = (pPrev->n==0);     /* True if this is the first term written */
149814  int nPrefix;                    /* Size of term prefix in bytes */
149815  int nSuffix;                    /* Size of term suffix in bytes */
149816
149817  /* Node must have already been started. There must be a doclist for a
149818  ** leaf node, and there must not be a doclist for an internal node.  */
149819  assert( pNode->n>0 );
149820  assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
149821
149822  blobGrowBuffer(pPrev, nTerm, &rc);
149823  if( rc!=SQLITE_OK ) return rc;
149824
149825  nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
149826  nSuffix = nTerm - nPrefix;
149827  memcpy(pPrev->a, zTerm, nTerm);
149828  pPrev->n = nTerm;
149829
149830  if( bFirst==0 ){
149831    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
149832  }
149833  pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
149834  memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
149835  pNode->n += nSuffix;
149836
149837  if( aDoclist ){
149838    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
149839    memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
149840    pNode->n += nDoclist;
149841  }
149842
149843  assert( pNode->n<=pNode->nAlloc );
149844
149845  return SQLITE_OK;
149846}
149847
149848/*
149849** Append the current term and doclist pointed to by cursor pCsr to the
149850** appendable b-tree segment opened for writing by pWriter.
149851**
149852** Return SQLITE_OK if successful, or an SQLite error code otherwise.
149853*/
149854static int fts3IncrmergeAppend(
149855  Fts3Table *p,                   /* Fts3 table handle */
149856  IncrmergeWriter *pWriter,       /* Writer object */
149857  Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
149858){
149859  const char *zTerm = pCsr->zTerm;
149860  int nTerm = pCsr->nTerm;
149861  const char *aDoclist = pCsr->aDoclist;
149862  int nDoclist = pCsr->nDoclist;
149863  int rc = SQLITE_OK;           /* Return code */
149864  int nSpace;                   /* Total space in bytes required on leaf */
149865  int nPrefix;                  /* Size of prefix shared with previous term */
149866  int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
149867  NodeWriter *pLeaf;            /* Object used to write leaf nodes */
149868
149869  pLeaf = &pWriter->aNodeWriter[0];
149870  nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
149871  nSuffix = nTerm - nPrefix;
149872
149873  nSpace  = sqlite3Fts3VarintLen(nPrefix);
149874  nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
149875  nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
149876
149877  /* If the current block is not empty, and if adding this term/doclist
149878  ** to the current block would make it larger than Fts3Table.nNodeSize
149879  ** bytes, write this block out to the database. */
149880  if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
149881    rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
149882    pWriter->nWork++;
149883
149884    /* Add the current term to the parent node. The term added to the
149885    ** parent must:
149886    **
149887    **   a) be greater than the largest term on the leaf node just written
149888    **      to the database (still available in pLeaf->key), and
149889    **
149890    **   b) be less than or equal to the term about to be added to the new
149891    **      leaf node (zTerm/nTerm).
149892    **
149893    ** In other words, it must be the prefix of zTerm 1 byte longer than
149894    ** the common prefix (if any) of zTerm and pWriter->zTerm.
149895    */
149896    if( rc==SQLITE_OK ){
149897      rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
149898    }
149899
149900    /* Advance to the next output block */
149901    pLeaf->iBlock++;
149902    pLeaf->key.n = 0;
149903    pLeaf->block.n = 0;
149904
149905    nSuffix = nTerm;
149906    nSpace  = 1;
149907    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
149908    nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
149909  }
149910
149911  pWriter->nLeafData += nSpace;
149912  blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
149913  if( rc==SQLITE_OK ){
149914    if( pLeaf->block.n==0 ){
149915      pLeaf->block.n = 1;
149916      pLeaf->block.a[0] = '\0';
149917    }
149918    rc = fts3AppendToNode(
149919        &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
149920    );
149921  }
149922
149923  return rc;
149924}
149925
149926/*
149927** This function is called to release all dynamic resources held by the
149928** merge-writer object pWriter, and if no error has occurred, to flush
149929** all outstanding node buffers held by pWriter to disk.
149930**
149931** If *pRc is not SQLITE_OK when this function is called, then no attempt
149932** is made to write any data to disk. Instead, this function serves only
149933** to release outstanding resources.
149934**
149935** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
149936** flushing buffers to disk, *pRc is set to an SQLite error code before
149937** returning.
149938*/
149939static void fts3IncrmergeRelease(
149940  Fts3Table *p,                   /* FTS3 table handle */
149941  IncrmergeWriter *pWriter,       /* Merge-writer object */
149942  int *pRc                        /* IN/OUT: Error code */
149943){
149944  int i;                          /* Used to iterate through non-root layers */
149945  int iRoot;                      /* Index of root in pWriter->aNodeWriter */
149946  NodeWriter *pRoot;              /* NodeWriter for root node */
149947  int rc = *pRc;                  /* Error code */
149948
149949  /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
149950  ** root node. If the segment fits entirely on a single leaf node, iRoot
149951  ** will be set to 0. If the root node is the parent of the leaves, iRoot
149952  ** will be 1. And so on.  */
149953  for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
149954    NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
149955    if( pNode->block.n>0 ) break;
149956    assert( *pRc || pNode->block.nAlloc==0 );
149957    assert( *pRc || pNode->key.nAlloc==0 );
149958    sqlite3_free(pNode->block.a);
149959    sqlite3_free(pNode->key.a);
149960  }
149961
149962  /* Empty output segment. This is a no-op. */
149963  if( iRoot<0 ) return;
149964
149965  /* The entire output segment fits on a single node. Normally, this means
149966  ** the node would be stored as a blob in the "root" column of the %_segdir
149967  ** table. However, this is not permitted in this case. The problem is that
149968  ** space has already been reserved in the %_segments table, and so the
149969  ** start_block and end_block fields of the %_segdir table must be populated.
149970  ** And, by design or by accident, released versions of FTS cannot handle
149971  ** segments that fit entirely on the root node with start_block!=0.
149972  **
149973  ** Instead, create a synthetic root node that contains nothing but a
149974  ** pointer to the single content node. So that the segment consists of a
149975  ** single leaf and a single interior (root) node.
149976  **
149977  ** Todo: Better might be to defer allocating space in the %_segments
149978  ** table until we are sure it is needed.
149979  */
149980  if( iRoot==0 ){
149981    Blob *pBlock = &pWriter->aNodeWriter[1].block;
149982    blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
149983    if( rc==SQLITE_OK ){
149984      pBlock->a[0] = 0x01;
149985      pBlock->n = 1 + sqlite3Fts3PutVarint(
149986          &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
149987      );
149988    }
149989    iRoot = 1;
149990  }
149991  pRoot = &pWriter->aNodeWriter[iRoot];
149992
149993  /* Flush all currently outstanding nodes to disk. */
149994  for(i=0; i<iRoot; i++){
149995    NodeWriter *pNode = &pWriter->aNodeWriter[i];
149996    if( pNode->block.n>0 && rc==SQLITE_OK ){
149997      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
149998    }
149999    sqlite3_free(pNode->block.a);
150000    sqlite3_free(pNode->key.a);
150001  }
150002
150003  /* Write the %_segdir record. */
150004  if( rc==SQLITE_OK ){
150005    rc = fts3WriteSegdir(p,
150006        pWriter->iAbsLevel+1,               /* level */
150007        pWriter->iIdx,                      /* idx */
150008        pWriter->iStart,                    /* start_block */
150009        pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
150010        pWriter->iEnd,                      /* end_block */
150011        (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0),   /* end_block */
150012        pRoot->block.a, pRoot->block.n      /* root */
150013    );
150014  }
150015  sqlite3_free(pRoot->block.a);
150016  sqlite3_free(pRoot->key.a);
150017
150018  *pRc = rc;
150019}
150020
150021/*
150022** Compare the term in buffer zLhs (size in bytes nLhs) with that in
150023** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
150024** the other, it is considered to be smaller than the other.
150025**
150026** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
150027** if it is greater.
150028*/
150029static int fts3TermCmp(
150030  const char *zLhs, int nLhs,     /* LHS of comparison */
150031  const char *zRhs, int nRhs      /* RHS of comparison */
150032){
150033  int nCmp = MIN(nLhs, nRhs);
150034  int res;
150035
150036  res = memcmp(zLhs, zRhs, nCmp);
150037  if( res==0 ) res = nLhs - nRhs;
150038
150039  return res;
150040}
150041
150042
150043/*
150044** Query to see if the entry in the %_segments table with blockid iEnd is
150045** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
150046** returning. Otherwise, set *pbRes to 0.
150047**
150048** Or, if an error occurs while querying the database, return an SQLite
150049** error code. The final value of *pbRes is undefined in this case.
150050**
150051** This is used to test if a segment is an "appendable" segment. If it
150052** is, then a NULL entry has been inserted into the %_segments table
150053** with blockid %_segdir.end_block.
150054*/
150055static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
150056  int bRes = 0;                   /* Result to set *pbRes to */
150057  sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
150058  int rc;                         /* Return code */
150059
150060  rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
150061  if( rc==SQLITE_OK ){
150062    sqlite3_bind_int64(pCheck, 1, iEnd);
150063    if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
150064    rc = sqlite3_reset(pCheck);
150065  }
150066
150067  *pbRes = bRes;
150068  return rc;
150069}
150070
150071/*
150072** This function is called when initializing an incremental-merge operation.
150073** It checks if the existing segment with index value iIdx at absolute level
150074** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
150075** merge-writer object *pWriter is initialized to write to it.
150076**
150077** An existing segment can be appended to by an incremental merge if:
150078**
150079**   * It was initially created as an appendable segment (with all required
150080**     space pre-allocated), and
150081**
150082**   * The first key read from the input (arguments zKey and nKey) is
150083**     greater than the largest key currently stored in the potential
150084**     output segment.
150085*/
150086static int fts3IncrmergeLoad(
150087  Fts3Table *p,                   /* Fts3 table handle */
150088  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
150089  int iIdx,                       /* Index of candidate output segment */
150090  const char *zKey,               /* First key to write */
150091  int nKey,                       /* Number of bytes in nKey */
150092  IncrmergeWriter *pWriter        /* Populate this object */
150093){
150094  int rc;                         /* Return code */
150095  sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
150096
150097  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
150098  if( rc==SQLITE_OK ){
150099    sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
150100    sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
150101    sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
150102    const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
150103    int nRoot = 0;                /* Size of aRoot[] in bytes */
150104    int rc2;                      /* Return code from sqlite3_reset() */
150105    int bAppendable = 0;          /* Set to true if segment is appendable */
150106
150107    /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
150108    sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
150109    sqlite3_bind_int(pSelect, 2, iIdx);
150110    if( sqlite3_step(pSelect)==SQLITE_ROW ){
150111      iStart = sqlite3_column_int64(pSelect, 1);
150112      iLeafEnd = sqlite3_column_int64(pSelect, 2);
150113      fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
150114      if( pWriter->nLeafData<0 ){
150115        pWriter->nLeafData = pWriter->nLeafData * -1;
150116      }
150117      pWriter->bNoLeafData = (pWriter->nLeafData==0);
150118      nRoot = sqlite3_column_bytes(pSelect, 4);
150119      aRoot = sqlite3_column_blob(pSelect, 4);
150120    }else{
150121      return sqlite3_reset(pSelect);
150122    }
150123
150124    /* Check for the zero-length marker in the %_segments table */
150125    rc = fts3IsAppendable(p, iEnd, &bAppendable);
150126
150127    /* Check that zKey/nKey is larger than the largest key the candidate */
150128    if( rc==SQLITE_OK && bAppendable ){
150129      char *aLeaf = 0;
150130      int nLeaf = 0;
150131
150132      rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
150133      if( rc==SQLITE_OK ){
150134        NodeReader reader;
150135        for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
150136            rc==SQLITE_OK && reader.aNode;
150137            rc = nodeReaderNext(&reader)
150138        ){
150139          assert( reader.aNode );
150140        }
150141        if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
150142          bAppendable = 0;
150143        }
150144        nodeReaderRelease(&reader);
150145      }
150146      sqlite3_free(aLeaf);
150147    }
150148
150149    if( rc==SQLITE_OK && bAppendable ){
150150      /* It is possible to append to this segment. Set up the IncrmergeWriter
150151      ** object to do so.  */
150152      int i;
150153      int nHeight = (int)aRoot[0];
150154      NodeWriter *pNode;
150155
150156      pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
150157      pWriter->iStart = iStart;
150158      pWriter->iEnd = iEnd;
150159      pWriter->iAbsLevel = iAbsLevel;
150160      pWriter->iIdx = iIdx;
150161
150162      for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
150163        pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
150164      }
150165
150166      pNode = &pWriter->aNodeWriter[nHeight];
150167      pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
150168      blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
150169      if( rc==SQLITE_OK ){
150170        memcpy(pNode->block.a, aRoot, nRoot);
150171        pNode->block.n = nRoot;
150172      }
150173
150174      for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
150175        NodeReader reader;
150176        pNode = &pWriter->aNodeWriter[i];
150177
150178        rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
150179        while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
150180        blobGrowBuffer(&pNode->key, reader.term.n, &rc);
150181        if( rc==SQLITE_OK ){
150182          memcpy(pNode->key.a, reader.term.a, reader.term.n);
150183          pNode->key.n = reader.term.n;
150184          if( i>0 ){
150185            char *aBlock = 0;
150186            int nBlock = 0;
150187            pNode = &pWriter->aNodeWriter[i-1];
150188            pNode->iBlock = reader.iChild;
150189            rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
150190            blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
150191            if( rc==SQLITE_OK ){
150192              memcpy(pNode->block.a, aBlock, nBlock);
150193              pNode->block.n = nBlock;
150194            }
150195            sqlite3_free(aBlock);
150196          }
150197        }
150198        nodeReaderRelease(&reader);
150199      }
150200    }
150201
150202    rc2 = sqlite3_reset(pSelect);
150203    if( rc==SQLITE_OK ) rc = rc2;
150204  }
150205
150206  return rc;
150207}
150208
150209/*
150210** Determine the largest segment index value that exists within absolute
150211** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
150212** one before returning SQLITE_OK. Or, if there are no segments at all
150213** within level iAbsLevel, set *piIdx to zero.
150214**
150215** If an error occurs, return an SQLite error code. The final value of
150216** *piIdx is undefined in this case.
150217*/
150218static int fts3IncrmergeOutputIdx(
150219  Fts3Table *p,                   /* FTS Table handle */
150220  sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
150221  int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
150222){
150223  int rc;
150224  sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
150225
150226  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
150227  if( rc==SQLITE_OK ){
150228    sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
150229    sqlite3_step(pOutputIdx);
150230    *piIdx = sqlite3_column_int(pOutputIdx, 0);
150231    rc = sqlite3_reset(pOutputIdx);
150232  }
150233
150234  return rc;
150235}
150236
150237/*
150238** Allocate an appendable output segment on absolute level iAbsLevel+1
150239** with idx value iIdx.
150240**
150241** In the %_segdir table, a segment is defined by the values in three
150242** columns:
150243**
150244**     start_block
150245**     leaves_end_block
150246**     end_block
150247**
150248** When an appendable segment is allocated, it is estimated that the
150249** maximum number of leaf blocks that may be required is the sum of the
150250** number of leaf blocks consumed by the input segments, plus the number
150251** of input segments, multiplied by two. This value is stored in stack
150252** variable nLeafEst.
150253**
150254** A total of 16*nLeafEst blocks are allocated when an appendable segment
150255** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
150256** array of leaf nodes starts at the first block allocated. The array
150257** of interior nodes that are parents of the leaf nodes start at block
150258** (start_block + (1 + end_block - start_block) / 16). And so on.
150259**
150260** In the actual code below, the value "16" is replaced with the
150261** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
150262*/
150263static int fts3IncrmergeWriter(
150264  Fts3Table *p,                   /* Fts3 table handle */
150265  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
150266  int iIdx,                       /* Index of new output segment */
150267  Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
150268  IncrmergeWriter *pWriter        /* Populate this object */
150269){
150270  int rc;                         /* Return Code */
150271  int i;                          /* Iterator variable */
150272  int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
150273  sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
150274  sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
150275
150276  /* Calculate nLeafEst. */
150277  rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
150278  if( rc==SQLITE_OK ){
150279    sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
150280    sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
150281    if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
150282      nLeafEst = sqlite3_column_int(pLeafEst, 0);
150283    }
150284    rc = sqlite3_reset(pLeafEst);
150285  }
150286  if( rc!=SQLITE_OK ) return rc;
150287
150288  /* Calculate the first block to use in the output segment */
150289  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
150290  if( rc==SQLITE_OK ){
150291    if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
150292      pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
150293      pWriter->iEnd = pWriter->iStart - 1;
150294      pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
150295    }
150296    rc = sqlite3_reset(pFirstBlock);
150297  }
150298  if( rc!=SQLITE_OK ) return rc;
150299
150300  /* Insert the marker in the %_segments table to make sure nobody tries
150301  ** to steal the space just allocated. This is also used to identify
150302  ** appendable segments.  */
150303  rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
150304  if( rc!=SQLITE_OK ) return rc;
150305
150306  pWriter->iAbsLevel = iAbsLevel;
150307  pWriter->nLeafEst = nLeafEst;
150308  pWriter->iIdx = iIdx;
150309
150310  /* Set up the array of NodeWriter objects */
150311  for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
150312    pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
150313  }
150314  return SQLITE_OK;
150315}
150316
150317/*
150318** Remove an entry from the %_segdir table. This involves running the
150319** following two statements:
150320**
150321**   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
150322**   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
150323**
150324** The DELETE statement removes the specific %_segdir level. The UPDATE
150325** statement ensures that the remaining segments have contiguously allocated
150326** idx values.
150327*/
150328static int fts3RemoveSegdirEntry(
150329  Fts3Table *p,                   /* FTS3 table handle */
150330  sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
150331  int iIdx                        /* Index of %_segdir entry to delete */
150332){
150333  int rc;                         /* Return code */
150334  sqlite3_stmt *pDelete = 0;      /* DELETE statement */
150335
150336  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
150337  if( rc==SQLITE_OK ){
150338    sqlite3_bind_int64(pDelete, 1, iAbsLevel);
150339    sqlite3_bind_int(pDelete, 2, iIdx);
150340    sqlite3_step(pDelete);
150341    rc = sqlite3_reset(pDelete);
150342  }
150343
150344  return rc;
150345}
150346
150347/*
150348** One or more segments have just been removed from absolute level iAbsLevel.
150349** Update the 'idx' values of the remaining segments in the level so that
150350** the idx values are a contiguous sequence starting from 0.
150351*/
150352static int fts3RepackSegdirLevel(
150353  Fts3Table *p,                   /* FTS3 table handle */
150354  sqlite3_int64 iAbsLevel         /* Absolute level to repack */
150355){
150356  int rc;                         /* Return code */
150357  int *aIdx = 0;                  /* Array of remaining idx values */
150358  int nIdx = 0;                   /* Valid entries in aIdx[] */
150359  int nAlloc = 0;                 /* Allocated size of aIdx[] */
150360  int i;                          /* Iterator variable */
150361  sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
150362  sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
150363
150364  rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
150365  if( rc==SQLITE_OK ){
150366    int rc2;
150367    sqlite3_bind_int64(pSelect, 1, iAbsLevel);
150368    while( SQLITE_ROW==sqlite3_step(pSelect) ){
150369      if( nIdx>=nAlloc ){
150370        int *aNew;
150371        nAlloc += 16;
150372        aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
150373        if( !aNew ){
150374          rc = SQLITE_NOMEM;
150375          break;
150376        }
150377        aIdx = aNew;
150378      }
150379      aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
150380    }
150381    rc2 = sqlite3_reset(pSelect);
150382    if( rc==SQLITE_OK ) rc = rc2;
150383  }
150384
150385  if( rc==SQLITE_OK ){
150386    rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
150387  }
150388  if( rc==SQLITE_OK ){
150389    sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
150390  }
150391
150392  assert( p->bIgnoreSavepoint==0 );
150393  p->bIgnoreSavepoint = 1;
150394  for(i=0; rc==SQLITE_OK && i<nIdx; i++){
150395    if( aIdx[i]!=i ){
150396      sqlite3_bind_int(pUpdate, 3, aIdx[i]);
150397      sqlite3_bind_int(pUpdate, 1, i);
150398      sqlite3_step(pUpdate);
150399      rc = sqlite3_reset(pUpdate);
150400    }
150401  }
150402  p->bIgnoreSavepoint = 0;
150403
150404  sqlite3_free(aIdx);
150405  return rc;
150406}
150407
150408static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
150409  pNode->a[0] = (char)iHeight;
150410  if( iChild ){
150411    assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
150412    pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
150413  }else{
150414    assert( pNode->nAlloc>=1 );
150415    pNode->n = 1;
150416  }
150417}
150418
150419/*
150420** The first two arguments are a pointer to and the size of a segment b-tree
150421** node. The node may be a leaf or an internal node.
150422**
150423** This function creates a new node image in blob object *pNew by copying
150424** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
150425** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
150426*/
150427static int fts3TruncateNode(
150428  const char *aNode,              /* Current node image */
150429  int nNode,                      /* Size of aNode in bytes */
150430  Blob *pNew,                     /* OUT: Write new node image here */
150431  const char *zTerm,              /* Omit all terms smaller than this */
150432  int nTerm,                      /* Size of zTerm in bytes */
150433  sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
150434){
150435  NodeReader reader;              /* Reader object */
150436  Blob prev = {0, 0, 0};          /* Previous term written to new node */
150437  int rc = SQLITE_OK;             /* Return code */
150438  int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
150439
150440  /* Allocate required output space */
150441  blobGrowBuffer(pNew, nNode, &rc);
150442  if( rc!=SQLITE_OK ) return rc;
150443  pNew->n = 0;
150444
150445  /* Populate new node buffer */
150446  for(rc = nodeReaderInit(&reader, aNode, nNode);
150447      rc==SQLITE_OK && reader.aNode;
150448      rc = nodeReaderNext(&reader)
150449  ){
150450    if( pNew->n==0 ){
150451      int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
150452      if( res<0 || (bLeaf==0 && res==0) ) continue;
150453      fts3StartNode(pNew, (int)aNode[0], reader.iChild);
150454      *piBlock = reader.iChild;
150455    }
150456    rc = fts3AppendToNode(
150457        pNew, &prev, reader.term.a, reader.term.n,
150458        reader.aDoclist, reader.nDoclist
150459    );
150460    if( rc!=SQLITE_OK ) break;
150461  }
150462  if( pNew->n==0 ){
150463    fts3StartNode(pNew, (int)aNode[0], reader.iChild);
150464    *piBlock = reader.iChild;
150465  }
150466  assert( pNew->n<=pNew->nAlloc );
150467
150468  nodeReaderRelease(&reader);
150469  sqlite3_free(prev.a);
150470  return rc;
150471}
150472
150473/*
150474** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
150475** level iAbsLevel. This may involve deleting entries from the %_segments
150476** table, and modifying existing entries in both the %_segments and %_segdir
150477** tables.
150478**
150479** SQLITE_OK is returned if the segment is updated successfully. Or an
150480** SQLite error code otherwise.
150481*/
150482static int fts3TruncateSegment(
150483  Fts3Table *p,                   /* FTS3 table handle */
150484  sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
150485  int iIdx,                       /* Index within level of segment to modify */
150486  const char *zTerm,              /* Remove terms smaller than this */
150487  int nTerm                      /* Number of bytes in buffer zTerm */
150488){
150489  int rc = SQLITE_OK;             /* Return code */
150490  Blob root = {0,0,0};            /* New root page image */
150491  Blob block = {0,0,0};           /* Buffer used for any other block */
150492  sqlite3_int64 iBlock = 0;       /* Block id */
150493  sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
150494  sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
150495  sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
150496
150497  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
150498  if( rc==SQLITE_OK ){
150499    int rc2;                      /* sqlite3_reset() return code */
150500    sqlite3_bind_int64(pFetch, 1, iAbsLevel);
150501    sqlite3_bind_int(pFetch, 2, iIdx);
150502    if( SQLITE_ROW==sqlite3_step(pFetch) ){
150503      const char *aRoot = sqlite3_column_blob(pFetch, 4);
150504      int nRoot = sqlite3_column_bytes(pFetch, 4);
150505      iOldStart = sqlite3_column_int64(pFetch, 1);
150506      rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
150507    }
150508    rc2 = sqlite3_reset(pFetch);
150509    if( rc==SQLITE_OK ) rc = rc2;
150510  }
150511
150512  while( rc==SQLITE_OK && iBlock ){
150513    char *aBlock = 0;
150514    int nBlock = 0;
150515    iNewStart = iBlock;
150516
150517    rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
150518    if( rc==SQLITE_OK ){
150519      rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
150520    }
150521    if( rc==SQLITE_OK ){
150522      rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
150523    }
150524    sqlite3_free(aBlock);
150525  }
150526
150527  /* Variable iNewStart now contains the first valid leaf node. */
150528  if( rc==SQLITE_OK && iNewStart ){
150529    sqlite3_stmt *pDel = 0;
150530    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
150531    if( rc==SQLITE_OK ){
150532      sqlite3_bind_int64(pDel, 1, iOldStart);
150533      sqlite3_bind_int64(pDel, 2, iNewStart-1);
150534      sqlite3_step(pDel);
150535      rc = sqlite3_reset(pDel);
150536    }
150537  }
150538
150539  if( rc==SQLITE_OK ){
150540    sqlite3_stmt *pChomp = 0;
150541    rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
150542    if( rc==SQLITE_OK ){
150543      sqlite3_bind_int64(pChomp, 1, iNewStart);
150544      sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
150545      sqlite3_bind_int64(pChomp, 3, iAbsLevel);
150546      sqlite3_bind_int(pChomp, 4, iIdx);
150547      sqlite3_step(pChomp);
150548      rc = sqlite3_reset(pChomp);
150549    }
150550  }
150551
150552  sqlite3_free(root.a);
150553  sqlite3_free(block.a);
150554  return rc;
150555}
150556
150557/*
150558** This function is called after an incrmental-merge operation has run to
150559** merge (or partially merge) two or more segments from absolute level
150560** iAbsLevel.
150561**
150562** Each input segment is either removed from the db completely (if all of
150563** its data was copied to the output segment by the incrmerge operation)
150564** or modified in place so that it no longer contains those entries that
150565** have been duplicated in the output segment.
150566*/
150567static int fts3IncrmergeChomp(
150568  Fts3Table *p,                   /* FTS table handle */
150569  sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
150570  Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
150571  int *pnRem                      /* Number of segments not deleted */
150572){
150573  int i;
150574  int nRem = 0;
150575  int rc = SQLITE_OK;
150576
150577  for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
150578    Fts3SegReader *pSeg = 0;
150579    int j;
150580
150581    /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
150582    ** somewhere in the pCsr->apSegment[] array.  */
150583    for(j=0; ALWAYS(j<pCsr->nSegment); j++){
150584      pSeg = pCsr->apSegment[j];
150585      if( pSeg->iIdx==i ) break;
150586    }
150587    assert( j<pCsr->nSegment && pSeg->iIdx==i );
150588
150589    if( pSeg->aNode==0 ){
150590      /* Seg-reader is at EOF. Remove the entire input segment. */
150591      rc = fts3DeleteSegment(p, pSeg);
150592      if( rc==SQLITE_OK ){
150593        rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
150594      }
150595      *pnRem = 0;
150596    }else{
150597      /* The incremental merge did not copy all the data from this
150598      ** segment to the upper level. The segment is modified in place
150599      ** so that it contains no keys smaller than zTerm/nTerm. */
150600      const char *zTerm = pSeg->zTerm;
150601      int nTerm = pSeg->nTerm;
150602      rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
150603      nRem++;
150604    }
150605  }
150606
150607  if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
150608    rc = fts3RepackSegdirLevel(p, iAbsLevel);
150609  }
150610
150611  *pnRem = nRem;
150612  return rc;
150613}
150614
150615/*
150616** Store an incr-merge hint in the database.
150617*/
150618static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
150619  sqlite3_stmt *pReplace = 0;
150620  int rc;                         /* Return code */
150621
150622  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
150623  if( rc==SQLITE_OK ){
150624    sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
150625    sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
150626    sqlite3_step(pReplace);
150627    rc = sqlite3_reset(pReplace);
150628  }
150629
150630  return rc;
150631}
150632
150633/*
150634** Load an incr-merge hint from the database. The incr-merge hint, if one
150635** exists, is stored in the rowid==1 row of the %_stat table.
150636**
150637** If successful, populate blob *pHint with the value read from the %_stat
150638** table and return SQLITE_OK. Otherwise, if an error occurs, return an
150639** SQLite error code.
150640*/
150641static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
150642  sqlite3_stmt *pSelect = 0;
150643  int rc;
150644
150645  pHint->n = 0;
150646  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
150647  if( rc==SQLITE_OK ){
150648    int rc2;
150649    sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
150650    if( SQLITE_ROW==sqlite3_step(pSelect) ){
150651      const char *aHint = sqlite3_column_blob(pSelect, 0);
150652      int nHint = sqlite3_column_bytes(pSelect, 0);
150653      if( aHint ){
150654        blobGrowBuffer(pHint, nHint, &rc);
150655        if( rc==SQLITE_OK ){
150656          memcpy(pHint->a, aHint, nHint);
150657          pHint->n = nHint;
150658        }
150659      }
150660    }
150661    rc2 = sqlite3_reset(pSelect);
150662    if( rc==SQLITE_OK ) rc = rc2;
150663  }
150664
150665  return rc;
150666}
150667
150668/*
150669** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
150670** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
150671** consists of two varints, the absolute level number of the input segments
150672** and the number of input segments.
150673**
150674** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
150675** set *pRc to an SQLite error code before returning.
150676*/
150677static void fts3IncrmergeHintPush(
150678  Blob *pHint,                    /* Hint blob to append to */
150679  i64 iAbsLevel,                  /* First varint to store in hint */
150680  int nInput,                     /* Second varint to store in hint */
150681  int *pRc                        /* IN/OUT: Error code */
150682){
150683  blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
150684  if( *pRc==SQLITE_OK ){
150685    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
150686    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
150687  }
150688}
150689
150690/*
150691** Read the last entry (most recently pushed) from the hint blob *pHint
150692** and then remove the entry. Write the two values read to *piAbsLevel and
150693** *pnInput before returning.
150694**
150695** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
150696** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
150697*/
150698static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
150699  const int nHint = pHint->n;
150700  int i;
150701
150702  i = pHint->n-2;
150703  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
150704  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
150705
150706  pHint->n = i;
150707  i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
150708  i += fts3GetVarint32(&pHint->a[i], pnInput);
150709  if( i!=nHint ) return FTS_CORRUPT_VTAB;
150710
150711  return SQLITE_OK;
150712}
150713
150714
150715/*
150716** Attempt an incremental merge that writes nMerge leaf blocks.
150717**
150718** Incremental merges happen nMin segments at a time. The segments
150719** to be merged are the nMin oldest segments (the ones with the smallest
150720** values for the _segdir.idx field) in the highest level that contains
150721** at least nMin segments. Multiple merges might occur in an attempt to
150722** write the quota of nMerge leaf blocks.
150723*/
150724SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
150725  int rc;                         /* Return code */
150726  int nRem = nMerge;              /* Number of leaf pages yet to  be written */
150727  Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
150728  Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
150729  IncrmergeWriter *pWriter;       /* Writer object */
150730  int nSeg = 0;                   /* Number of input segments */
150731  sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
150732  Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
150733  int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
150734
150735  /* Allocate space for the cursor, filter and writer objects */
150736  const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
150737  pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
150738  if( !pWriter ) return SQLITE_NOMEM;
150739  pFilter = (Fts3SegFilter *)&pWriter[1];
150740  pCsr = (Fts3MultiSegReader *)&pFilter[1];
150741
150742  rc = fts3IncrmergeHintLoad(p, &hint);
150743  while( rc==SQLITE_OK && nRem>0 ){
150744    const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
150745    sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
150746    int bUseHint = 0;             /* True if attempting to append */
150747    int iIdx = 0;                 /* Largest idx in level (iAbsLevel+1) */
150748
150749    /* Search the %_segdir table for the absolute level with the smallest
150750    ** relative level number that contains at least nMin segments, if any.
150751    ** If one is found, set iAbsLevel to the absolute level number and
150752    ** nSeg to nMin. If no level with at least nMin segments can be found,
150753    ** set nSeg to -1.
150754    */
150755    rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
150756    sqlite3_bind_int(pFindLevel, 1, nMin);
150757    if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
150758      iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
150759      nSeg = nMin;
150760    }else{
150761      nSeg = -1;
150762    }
150763    rc = sqlite3_reset(pFindLevel);
150764
150765    /* If the hint read from the %_stat table is not empty, check if the
150766    ** last entry in it specifies a relative level smaller than or equal
150767    ** to the level identified by the block above (if any). If so, this
150768    ** iteration of the loop will work on merging at the hinted level.
150769    */
150770    if( rc==SQLITE_OK && hint.n ){
150771      int nHint = hint.n;
150772      sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
150773      int nHintSeg = 0;                     /* Hint number of segments */
150774
150775      rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
150776      if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
150777        iAbsLevel = iHintAbsLevel;
150778        nSeg = nHintSeg;
150779        bUseHint = 1;
150780        bDirtyHint = 1;
150781      }else{
150782        /* This undoes the effect of the HintPop() above - so that no entry
150783        ** is removed from the hint blob.  */
150784        hint.n = nHint;
150785      }
150786    }
150787
150788    /* If nSeg is less that zero, then there is no level with at least
150789    ** nMin segments and no hint in the %_stat table. No work to do.
150790    ** Exit early in this case.  */
150791    if( nSeg<0 ) break;
150792
150793    /* Open a cursor to iterate through the contents of the oldest nSeg
150794    ** indexes of absolute level iAbsLevel. If this cursor is opened using
150795    ** the 'hint' parameters, it is possible that there are less than nSeg
150796    ** segments available in level iAbsLevel. In this case, no work is
150797    ** done on iAbsLevel - fall through to the next iteration of the loop
150798    ** to start work on some other level.  */
150799    memset(pWriter, 0, nAlloc);
150800    pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
150801
150802    if( rc==SQLITE_OK ){
150803      rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
150804      assert( bUseHint==1 || bUseHint==0 );
150805      if( iIdx==0 || (bUseHint && iIdx==1) ){
150806        int bIgnore = 0;
150807        rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
150808        if( bIgnore ){
150809          pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
150810        }
150811      }
150812    }
150813
150814    if( rc==SQLITE_OK ){
150815      rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
150816    }
150817    if( SQLITE_OK==rc && pCsr->nSegment==nSeg
150818     && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
150819     && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
150820    ){
150821      if( bUseHint && iIdx>0 ){
150822        const char *zKey = pCsr->zTerm;
150823        int nKey = pCsr->nTerm;
150824        rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
150825      }else{
150826        rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
150827      }
150828
150829      if( rc==SQLITE_OK && pWriter->nLeafEst ){
150830        fts3LogMerge(nSeg, iAbsLevel);
150831        do {
150832          rc = fts3IncrmergeAppend(p, pWriter, pCsr);
150833          if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
150834          if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
150835        }while( rc==SQLITE_ROW );
150836
150837        /* Update or delete the input segments */
150838        if( rc==SQLITE_OK ){
150839          nRem -= (1 + pWriter->nWork);
150840          rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
150841          if( nSeg!=0 ){
150842            bDirtyHint = 1;
150843            fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
150844          }
150845        }
150846      }
150847
150848      if( nSeg!=0 ){
150849        pWriter->nLeafData = pWriter->nLeafData * -1;
150850      }
150851      fts3IncrmergeRelease(p, pWriter, &rc);
150852      if( nSeg==0 && pWriter->bNoLeafData==0 ){
150853        fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
150854      }
150855    }
150856
150857    sqlite3Fts3SegReaderFinish(pCsr);
150858  }
150859
150860  /* Write the hint values into the %_stat table for the next incr-merger */
150861  if( bDirtyHint && rc==SQLITE_OK ){
150862    rc = fts3IncrmergeHintStore(p, &hint);
150863  }
150864
150865  sqlite3_free(pWriter);
150866  sqlite3_free(hint.a);
150867  return rc;
150868}
150869
150870/*
150871** Convert the text beginning at *pz into an integer and return
150872** its value.  Advance *pz to point to the first character past
150873** the integer.
150874*/
150875static int fts3Getint(const char **pz){
150876  const char *z = *pz;
150877  int i = 0;
150878  while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
150879  *pz = z;
150880  return i;
150881}
150882
150883/*
150884** Process statements of the form:
150885**
150886**    INSERT INTO table(table) VALUES('merge=A,B');
150887**
150888** A and B are integers that decode to be the number of leaf pages
150889** written for the merge, and the minimum number of segments on a level
150890** before it will be selected for a merge, respectively.
150891*/
150892static int fts3DoIncrmerge(
150893  Fts3Table *p,                   /* FTS3 table handle */
150894  const char *zParam              /* Nul-terminated string containing "A,B" */
150895){
150896  int rc;
150897  int nMin = (FTS3_MERGE_COUNT / 2);
150898  int nMerge = 0;
150899  const char *z = zParam;
150900
150901  /* Read the first integer value */
150902  nMerge = fts3Getint(&z);
150903
150904  /* If the first integer value is followed by a ',',  read the second
150905  ** integer value. */
150906  if( z[0]==',' && z[1]!='\0' ){
150907    z++;
150908    nMin = fts3Getint(&z);
150909  }
150910
150911  if( z[0]!='\0' || nMin<2 ){
150912    rc = SQLITE_ERROR;
150913  }else{
150914    rc = SQLITE_OK;
150915    if( !p->bHasStat ){
150916      assert( p->bFts4==0 );
150917      sqlite3Fts3CreateStatTable(&rc, p);
150918    }
150919    if( rc==SQLITE_OK ){
150920      rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
150921    }
150922    sqlite3Fts3SegmentsClose(p);
150923  }
150924  return rc;
150925}
150926
150927/*
150928** Process statements of the form:
150929**
150930**    INSERT INTO table(table) VALUES('automerge=X');
150931**
150932** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
150933** turn it on.  The setting is persistent.
150934*/
150935static int fts3DoAutoincrmerge(
150936  Fts3Table *p,                   /* FTS3 table handle */
150937  const char *zParam              /* Nul-terminated string containing boolean */
150938){
150939  int rc = SQLITE_OK;
150940  sqlite3_stmt *pStmt = 0;
150941  p->nAutoincrmerge = fts3Getint(&zParam);
150942  if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
150943    p->nAutoincrmerge = 8;
150944  }
150945  if( !p->bHasStat ){
150946    assert( p->bFts4==0 );
150947    sqlite3Fts3CreateStatTable(&rc, p);
150948    if( rc ) return rc;
150949  }
150950  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
150951  if( rc ) return rc;
150952  sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
150953  sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
150954  sqlite3_step(pStmt);
150955  rc = sqlite3_reset(pStmt);
150956  return rc;
150957}
150958
150959/*
150960** Return a 64-bit checksum for the FTS index entry specified by the
150961** arguments to this function.
150962*/
150963static u64 fts3ChecksumEntry(
150964  const char *zTerm,              /* Pointer to buffer containing term */
150965  int nTerm,                      /* Size of zTerm in bytes */
150966  int iLangid,                    /* Language id for current row */
150967  int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
150968  i64 iDocid,                     /* Docid for current row. */
150969  int iCol,                       /* Column number */
150970  int iPos                        /* Position */
150971){
150972  int i;
150973  u64 ret = (u64)iDocid;
150974
150975  ret += (ret<<3) + iLangid;
150976  ret += (ret<<3) + iIndex;
150977  ret += (ret<<3) + iCol;
150978  ret += (ret<<3) + iPos;
150979  for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
150980
150981  return ret;
150982}
150983
150984/*
150985** Return a checksum of all entries in the FTS index that correspond to
150986** language id iLangid. The checksum is calculated by XORing the checksums
150987** of each individual entry (see fts3ChecksumEntry()) together.
150988**
150989** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
150990** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
150991** return value is undefined in this case.
150992*/
150993static u64 fts3ChecksumIndex(
150994  Fts3Table *p,                   /* FTS3 table handle */
150995  int iLangid,                    /* Language id to return cksum for */
150996  int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
150997  int *pRc                        /* OUT: Return code */
150998){
150999  Fts3SegFilter filter;
151000  Fts3MultiSegReader csr;
151001  int rc;
151002  u64 cksum = 0;
151003
151004  assert( *pRc==SQLITE_OK );
151005
151006  memset(&filter, 0, sizeof(filter));
151007  memset(&csr, 0, sizeof(csr));
151008  filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
151009  filter.flags |= FTS3_SEGMENT_SCAN;
151010
151011  rc = sqlite3Fts3SegReaderCursor(
151012      p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
151013  );
151014  if( rc==SQLITE_OK ){
151015    rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
151016  }
151017
151018  if( rc==SQLITE_OK ){
151019    while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
151020      char *pCsr = csr.aDoclist;
151021      char *pEnd = &pCsr[csr.nDoclist];
151022
151023      i64 iDocid = 0;
151024      i64 iCol = 0;
151025      i64 iPos = 0;
151026
151027      pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
151028      while( pCsr<pEnd ){
151029        i64 iVal = 0;
151030        pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
151031        if( pCsr<pEnd ){
151032          if( iVal==0 || iVal==1 ){
151033            iCol = 0;
151034            iPos = 0;
151035            if( iVal ){
151036              pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
151037            }else{
151038              pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
151039              iDocid += iVal;
151040            }
151041          }else{
151042            iPos += (iVal - 2);
151043            cksum = cksum ^ fts3ChecksumEntry(
151044                csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
151045                (int)iCol, (int)iPos
151046            );
151047          }
151048        }
151049      }
151050    }
151051  }
151052  sqlite3Fts3SegReaderFinish(&csr);
151053
151054  *pRc = rc;
151055  return cksum;
151056}
151057
151058/*
151059** Check if the contents of the FTS index match the current contents of the
151060** content table. If no error occurs and the contents do match, set *pbOk
151061** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
151062** to false before returning.
151063**
151064** If an error occurs (e.g. an OOM or IO error), return an SQLite error
151065** code. The final value of *pbOk is undefined in this case.
151066*/
151067static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
151068  int rc = SQLITE_OK;             /* Return code */
151069  u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
151070  u64 cksum2 = 0;                 /* Checksum based on %_content contents */
151071  sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
151072
151073  /* This block calculates the checksum according to the FTS index. */
151074  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
151075  if( rc==SQLITE_OK ){
151076    int rc2;
151077    sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
151078    sqlite3_bind_int(pAllLangid, 2, p->nIndex);
151079    while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
151080      int iLangid = sqlite3_column_int(pAllLangid, 0);
151081      int i;
151082      for(i=0; i<p->nIndex; i++){
151083        cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
151084      }
151085    }
151086    rc2 = sqlite3_reset(pAllLangid);
151087    if( rc==SQLITE_OK ) rc = rc2;
151088  }
151089
151090  /* This block calculates the checksum according to the %_content table */
151091  if( rc==SQLITE_OK ){
151092    sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
151093    sqlite3_stmt *pStmt = 0;
151094    char *zSql;
151095
151096    zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
151097    if( !zSql ){
151098      rc = SQLITE_NOMEM;
151099    }else{
151100      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
151101      sqlite3_free(zSql);
151102    }
151103
151104    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
151105      i64 iDocid = sqlite3_column_int64(pStmt, 0);
151106      int iLang = langidFromSelect(p, pStmt);
151107      int iCol;
151108
151109      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
151110        if( p->abNotindexed[iCol]==0 ){
151111          const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
151112          int nText = sqlite3_column_bytes(pStmt, iCol+1);
151113          sqlite3_tokenizer_cursor *pT = 0;
151114
151115          rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
151116          while( rc==SQLITE_OK ){
151117            char const *zToken;       /* Buffer containing token */
151118            int nToken = 0;           /* Number of bytes in token */
151119            int iDum1 = 0, iDum2 = 0; /* Dummy variables */
151120            int iPos = 0;             /* Position of token in zText */
151121
151122            rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
151123            if( rc==SQLITE_OK ){
151124              int i;
151125              cksum2 = cksum2 ^ fts3ChecksumEntry(
151126                  zToken, nToken, iLang, 0, iDocid, iCol, iPos
151127              );
151128              for(i=1; i<p->nIndex; i++){
151129                if( p->aIndex[i].nPrefix<=nToken ){
151130                  cksum2 = cksum2 ^ fts3ChecksumEntry(
151131                      zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
151132                  );
151133                }
151134              }
151135            }
151136          }
151137          if( pT ) pModule->xClose(pT);
151138          if( rc==SQLITE_DONE ) rc = SQLITE_OK;
151139        }
151140      }
151141    }
151142
151143    sqlite3_finalize(pStmt);
151144  }
151145
151146  *pbOk = (cksum1==cksum2);
151147  return rc;
151148}
151149
151150/*
151151** Run the integrity-check. If no error occurs and the current contents of
151152** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
151153** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
151154**
151155** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
151156** error code.
151157**
151158** The integrity-check works as follows. For each token and indexed token
151159** prefix in the document set, a 64-bit checksum is calculated (by code
151160** in fts3ChecksumEntry()) based on the following:
151161**
151162**     + The index number (0 for the main index, 1 for the first prefix
151163**       index etc.),
151164**     + The token (or token prefix) text itself,
151165**     + The language-id of the row it appears in,
151166**     + The docid of the row it appears in,
151167**     + The column it appears in, and
151168**     + The tokens position within that column.
151169**
151170** The checksums for all entries in the index are XORed together to create
151171** a single checksum for the entire index.
151172**
151173** The integrity-check code calculates the same checksum in two ways:
151174**
151175**     1. By scanning the contents of the FTS index, and
151176**     2. By scanning and tokenizing the content table.
151177**
151178** If the two checksums are identical, the integrity-check is deemed to have
151179** passed.
151180*/
151181static int fts3DoIntegrityCheck(
151182  Fts3Table *p                    /* FTS3 table handle */
151183){
151184  int rc;
151185  int bOk = 0;
151186  rc = fts3IntegrityCheck(p, &bOk);
151187  if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
151188  return rc;
151189}
151190
151191/*
151192** Handle a 'special' INSERT of the form:
151193**
151194**   "INSERT INTO tbl(tbl) VALUES(<expr>)"
151195**
151196** Argument pVal contains the result of <expr>. Currently the only
151197** meaningful value to insert is the text 'optimize'.
151198*/
151199static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
151200  int rc;                         /* Return Code */
151201  const char *zVal = (const char *)sqlite3_value_text(pVal);
151202  int nVal = sqlite3_value_bytes(pVal);
151203
151204  if( !zVal ){
151205    return SQLITE_NOMEM;
151206  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
151207    rc = fts3DoOptimize(p, 0);
151208  }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
151209    rc = fts3DoRebuild(p);
151210  }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
151211    rc = fts3DoIntegrityCheck(p);
151212  }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
151213    rc = fts3DoIncrmerge(p, &zVal[6]);
151214  }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
151215    rc = fts3DoAutoincrmerge(p, &zVal[10]);
151216#ifdef SQLITE_TEST
151217  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
151218    p->nNodeSize = atoi(&zVal[9]);
151219    rc = SQLITE_OK;
151220  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
151221    p->nMaxPendingData = atoi(&zVal[11]);
151222    rc = SQLITE_OK;
151223  }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
151224    p->bNoIncrDoclist = atoi(&zVal[21]);
151225    rc = SQLITE_OK;
151226#endif
151227  }else{
151228    rc = SQLITE_ERROR;
151229  }
151230
151231  return rc;
151232}
151233
151234#ifndef SQLITE_DISABLE_FTS4_DEFERRED
151235/*
151236** Delete all cached deferred doclists. Deferred doclists are cached
151237** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
151238*/
151239SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
151240  Fts3DeferredToken *pDef;
151241  for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
151242    fts3PendingListDelete(pDef->pList);
151243    pDef->pList = 0;
151244  }
151245}
151246
151247/*
151248** Free all entries in the pCsr->pDeffered list. Entries are added to
151249** this list using sqlite3Fts3DeferToken().
151250*/
151251SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
151252  Fts3DeferredToken *pDef;
151253  Fts3DeferredToken *pNext;
151254  for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
151255    pNext = pDef->pNext;
151256    fts3PendingListDelete(pDef->pList);
151257    sqlite3_free(pDef);
151258  }
151259  pCsr->pDeferred = 0;
151260}
151261
151262/*
151263** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
151264** based on the row that pCsr currently points to.
151265**
151266** A deferred-doclist is like any other doclist with position information
151267** included, except that it only contains entries for a single row of the
151268** table, not for all rows.
151269*/
151270SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
151271  int rc = SQLITE_OK;             /* Return code */
151272  if( pCsr->pDeferred ){
151273    int i;                        /* Used to iterate through table columns */
151274    sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
151275    Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
151276
151277    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
151278    sqlite3_tokenizer *pT = p->pTokenizer;
151279    sqlite3_tokenizer_module const *pModule = pT->pModule;
151280
151281    assert( pCsr->isRequireSeek==0 );
151282    iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
151283
151284    for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
151285      if( p->abNotindexed[i]==0 ){
151286        const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
151287        sqlite3_tokenizer_cursor *pTC = 0;
151288
151289        rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
151290        while( rc==SQLITE_OK ){
151291          char const *zToken;       /* Buffer containing token */
151292          int nToken = 0;           /* Number of bytes in token */
151293          int iDum1 = 0, iDum2 = 0; /* Dummy variables */
151294          int iPos = 0;             /* Position of token in zText */
151295
151296          rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
151297          for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
151298            Fts3PhraseToken *pPT = pDef->pToken;
151299            if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
151300                && (pPT->bFirst==0 || iPos==0)
151301                && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
151302                && (0==memcmp(zToken, pPT->z, pPT->n))
151303              ){
151304              fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
151305            }
151306          }
151307        }
151308        if( pTC ) pModule->xClose(pTC);
151309        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
151310      }
151311    }
151312
151313    for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
151314      if( pDef->pList ){
151315        rc = fts3PendingListAppendVarint(&pDef->pList, 0);
151316      }
151317    }
151318  }
151319
151320  return rc;
151321}
151322
151323SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
151324  Fts3DeferredToken *p,
151325  char **ppData,
151326  int *pnData
151327){
151328  char *pRet;
151329  int nSkip;
151330  sqlite3_int64 dummy;
151331
151332  *ppData = 0;
151333  *pnData = 0;
151334
151335  if( p->pList==0 ){
151336    return SQLITE_OK;
151337  }
151338
151339  pRet = (char *)sqlite3_malloc(p->pList->nData);
151340  if( !pRet ) return SQLITE_NOMEM;
151341
151342  nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
151343  *pnData = p->pList->nData - nSkip;
151344  *ppData = pRet;
151345
151346  memcpy(pRet, &p->pList->aData[nSkip], *pnData);
151347  return SQLITE_OK;
151348}
151349
151350/*
151351** Add an entry for token pToken to the pCsr->pDeferred list.
151352*/
151353SQLITE_PRIVATE int sqlite3Fts3DeferToken(
151354  Fts3Cursor *pCsr,               /* Fts3 table cursor */
151355  Fts3PhraseToken *pToken,        /* Token to defer */
151356  int iCol                        /* Column that token must appear in (or -1) */
151357){
151358  Fts3DeferredToken *pDeferred;
151359  pDeferred = sqlite3_malloc(sizeof(*pDeferred));
151360  if( !pDeferred ){
151361    return SQLITE_NOMEM;
151362  }
151363  memset(pDeferred, 0, sizeof(*pDeferred));
151364  pDeferred->pToken = pToken;
151365  pDeferred->pNext = pCsr->pDeferred;
151366  pDeferred->iCol = iCol;
151367  pCsr->pDeferred = pDeferred;
151368
151369  assert( pToken->pDeferred==0 );
151370  pToken->pDeferred = pDeferred;
151371
151372  return SQLITE_OK;
151373}
151374#endif
151375
151376/*
151377** SQLite value pRowid contains the rowid of a row that may or may not be
151378** present in the FTS3 table. If it is, delete it and adjust the contents
151379** of subsiduary data structures accordingly.
151380*/
151381static int fts3DeleteByRowid(
151382  Fts3Table *p,
151383  sqlite3_value *pRowid,
151384  int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
151385  u32 *aSzDel
151386){
151387  int rc = SQLITE_OK;             /* Return code */
151388  int bFound = 0;                 /* True if *pRowid really is in the table */
151389
151390  fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
151391  if( bFound && rc==SQLITE_OK ){
151392    int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
151393    rc = fts3IsEmpty(p, pRowid, &isEmpty);
151394    if( rc==SQLITE_OK ){
151395      if( isEmpty ){
151396        /* Deleting this row means the whole table is empty. In this case
151397        ** delete the contents of all three tables and throw away any
151398        ** data in the pendingTerms hash table.  */
151399        rc = fts3DeleteAll(p, 1);
151400        *pnChng = 0;
151401        memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
151402      }else{
151403        *pnChng = *pnChng - 1;
151404        if( p->zContentTbl==0 ){
151405          fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
151406        }
151407        if( p->bHasDocsize ){
151408          fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
151409        }
151410      }
151411    }
151412  }
151413
151414  return rc;
151415}
151416
151417/*
151418** This function does the work for the xUpdate method of FTS3 virtual
151419** tables. The schema of the virtual table being:
151420**
151421**     CREATE TABLE <table name>(
151422**       <user columns>,
151423**       <table name> HIDDEN,
151424**       docid HIDDEN,
151425**       <langid> HIDDEN
151426**     );
151427**
151428**
151429*/
151430SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
151431  sqlite3_vtab *pVtab,            /* FTS3 vtab object */
151432  int nArg,                       /* Size of argument array */
151433  sqlite3_value **apVal,          /* Array of arguments */
151434  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
151435){
151436  Fts3Table *p = (Fts3Table *)pVtab;
151437  int rc = SQLITE_OK;             /* Return Code */
151438  int isRemove = 0;               /* True for an UPDATE or DELETE */
151439  u32 *aSzIns = 0;                /* Sizes of inserted documents */
151440  u32 *aSzDel = 0;                /* Sizes of deleted documents */
151441  int nChng = 0;                  /* Net change in number of documents */
151442  int bInsertDone = 0;
151443
151444  /* At this point it must be known if the %_stat table exists or not.
151445  ** So bHasStat may not be 2.  */
151446  assert( p->bHasStat==0 || p->bHasStat==1 );
151447
151448  assert( p->pSegments==0 );
151449  assert(
151450      nArg==1                     /* DELETE operations */
151451   || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
151452  );
151453
151454  /* Check for a "special" INSERT operation. One of the form:
151455  **
151456  **   INSERT INTO xyz(xyz) VALUES('command');
151457  */
151458  if( nArg>1
151459   && sqlite3_value_type(apVal[0])==SQLITE_NULL
151460   && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
151461  ){
151462    rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
151463    goto update_out;
151464  }
151465
151466  if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
151467    rc = SQLITE_CONSTRAINT;
151468    goto update_out;
151469  }
151470
151471  /* Allocate space to hold the change in document sizes */
151472  aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
151473  if( aSzDel==0 ){
151474    rc = SQLITE_NOMEM;
151475    goto update_out;
151476  }
151477  aSzIns = &aSzDel[p->nColumn+1];
151478  memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
151479
151480  rc = fts3Writelock(p);
151481  if( rc!=SQLITE_OK ) goto update_out;
151482
151483  /* If this is an INSERT operation, or an UPDATE that modifies the rowid
151484  ** value, then this operation requires constraint handling.
151485  **
151486  ** If the on-conflict mode is REPLACE, this means that the existing row
151487  ** should be deleted from the database before inserting the new row. Or,
151488  ** if the on-conflict mode is other than REPLACE, then this method must
151489  ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
151490  ** modify the database file.
151491  */
151492  if( nArg>1 && p->zContentTbl==0 ){
151493    /* Find the value object that holds the new rowid value. */
151494    sqlite3_value *pNewRowid = apVal[3+p->nColumn];
151495    if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
151496      pNewRowid = apVal[1];
151497    }
151498
151499    if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
151500        sqlite3_value_type(apVal[0])==SQLITE_NULL
151501     || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
151502    )){
151503      /* The new rowid is not NULL (in this case the rowid will be
151504      ** automatically assigned and there is no chance of a conflict), and
151505      ** the statement is either an INSERT or an UPDATE that modifies the
151506      ** rowid column. So if the conflict mode is REPLACE, then delete any
151507      ** existing row with rowid=pNewRowid.
151508      **
151509      ** Or, if the conflict mode is not REPLACE, insert the new record into
151510      ** the %_content table. If we hit the duplicate rowid constraint (or any
151511      ** other error) while doing so, return immediately.
151512      **
151513      ** This branch may also run if pNewRowid contains a value that cannot
151514      ** be losslessly converted to an integer. In this case, the eventual
151515      ** call to fts3InsertData() (either just below or further on in this
151516      ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
151517      ** invoked, it will delete zero rows (since no row will have
151518      ** docid=$pNewRowid if $pNewRowid is not an integer value).
151519      */
151520      if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
151521        rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
151522      }else{
151523        rc = fts3InsertData(p, apVal, pRowid);
151524        bInsertDone = 1;
151525      }
151526    }
151527  }
151528  if( rc!=SQLITE_OK ){
151529    goto update_out;
151530  }
151531
151532  /* If this is a DELETE or UPDATE operation, remove the old record. */
151533  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
151534    assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
151535    rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
151536    isRemove = 1;
151537  }
151538
151539  /* If this is an INSERT or UPDATE operation, insert the new record. */
151540  if( nArg>1 && rc==SQLITE_OK ){
151541    int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
151542    if( bInsertDone==0 ){
151543      rc = fts3InsertData(p, apVal, pRowid);
151544      if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
151545        rc = FTS_CORRUPT_VTAB;
151546      }
151547    }
151548    if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
151549      rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
151550    }
151551    if( rc==SQLITE_OK ){
151552      assert( p->iPrevDocid==*pRowid );
151553      rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
151554    }
151555    if( p->bHasDocsize ){
151556      fts3InsertDocsize(&rc, p, aSzIns);
151557    }
151558    nChng++;
151559  }
151560
151561  if( p->bFts4 ){
151562    fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
151563  }
151564
151565 update_out:
151566  sqlite3_free(aSzDel);
151567  sqlite3Fts3SegmentsClose(p);
151568  return rc;
151569}
151570
151571/*
151572** Flush any data in the pending-terms hash table to disk. If successful,
151573** merge all segments in the database (including the new segment, if
151574** there was any data to flush) into a single segment.
151575*/
151576SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
151577  int rc;
151578  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
151579  if( rc==SQLITE_OK ){
151580    rc = fts3DoOptimize(p, 1);
151581    if( rc==SQLITE_OK || rc==SQLITE_DONE ){
151582      int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
151583      if( rc2!=SQLITE_OK ) rc = rc2;
151584    }else{
151585      sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
151586      sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
151587    }
151588  }
151589  sqlite3Fts3SegmentsClose(p);
151590  return rc;
151591}
151592
151593#endif
151594
151595/************** End of fts3_write.c ******************************************/
151596/************** Begin file fts3_snippet.c ************************************/
151597/*
151598** 2009 Oct 23
151599**
151600** The author disclaims copyright to this source code.  In place of
151601** a legal notice, here is a blessing:
151602**
151603**    May you do good and not evil.
151604**    May you find forgiveness for yourself and forgive others.
151605**    May you share freely, never taking more than you give.
151606**
151607******************************************************************************
151608*/
151609
151610/* #include "fts3Int.h" */
151611#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
151612
151613/* #include <string.h> */
151614/* #include <assert.h> */
151615
151616/*
151617** Characters that may appear in the second argument to matchinfo().
151618*/
151619#define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
151620#define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
151621#define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
151622#define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
151623#define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
151624#define FTS3_MATCHINFO_LCS       's'        /* nCol values */
151625#define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
151626#define FTS3_MATCHINFO_LHITS     'y'        /* nCol*nPhrase values */
151627#define FTS3_MATCHINFO_LHITS_BM  'b'        /* nCol*nPhrase values */
151628
151629/*
151630** The default value for the second argument to matchinfo().
151631*/
151632#define FTS3_MATCHINFO_DEFAULT   "pcx"
151633
151634
151635/*
151636** Used as an fts3ExprIterate() context when loading phrase doclists to
151637** Fts3Expr.aDoclist[]/nDoclist.
151638*/
151639typedef struct LoadDoclistCtx LoadDoclistCtx;
151640struct LoadDoclistCtx {
151641  Fts3Cursor *pCsr;               /* FTS3 Cursor */
151642  int nPhrase;                    /* Number of phrases seen so far */
151643  int nToken;                     /* Number of tokens seen so far */
151644};
151645
151646/*
151647** The following types are used as part of the implementation of the
151648** fts3BestSnippet() routine.
151649*/
151650typedef struct SnippetIter SnippetIter;
151651typedef struct SnippetPhrase SnippetPhrase;
151652typedef struct SnippetFragment SnippetFragment;
151653
151654struct SnippetIter {
151655  Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
151656  int iCol;                       /* Extract snippet from this column */
151657  int nSnippet;                   /* Requested snippet length (in tokens) */
151658  int nPhrase;                    /* Number of phrases in query */
151659  SnippetPhrase *aPhrase;         /* Array of size nPhrase */
151660  int iCurrent;                   /* First token of current snippet */
151661};
151662
151663struct SnippetPhrase {
151664  int nToken;                     /* Number of tokens in phrase */
151665  char *pList;                    /* Pointer to start of phrase position list */
151666  int iHead;                      /* Next value in position list */
151667  char *pHead;                    /* Position list data following iHead */
151668  int iTail;                      /* Next value in trailing position list */
151669  char *pTail;                    /* Position list data following iTail */
151670};
151671
151672struct SnippetFragment {
151673  int iCol;                       /* Column snippet is extracted from */
151674  int iPos;                       /* Index of first token in snippet */
151675  u64 covered;                    /* Mask of query phrases covered */
151676  u64 hlmask;                     /* Mask of snippet terms to highlight */
151677};
151678
151679/*
151680** This type is used as an fts3ExprIterate() context object while
151681** accumulating the data returned by the matchinfo() function.
151682*/
151683typedef struct MatchInfo MatchInfo;
151684struct MatchInfo {
151685  Fts3Cursor *pCursor;            /* FTS3 Cursor */
151686  int nCol;                       /* Number of columns in table */
151687  int nPhrase;                    /* Number of matchable phrases in query */
151688  sqlite3_int64 nDoc;             /* Number of docs in database */
151689  char flag;
151690  u32 *aMatchinfo;                /* Pre-allocated buffer */
151691};
151692
151693/*
151694** An instance of this structure is used to manage a pair of buffers, each
151695** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
151696** for details.
151697*/
151698struct MatchinfoBuffer {
151699  u8 aRef[3];
151700  int nElem;
151701  int bGlobal;                    /* Set if global data is loaded */
151702  char *zMatchinfo;
151703  u32 aMatchinfo[1];
151704};
151705
151706
151707/*
151708** The snippet() and offsets() functions both return text values. An instance
151709** of the following structure is used to accumulate those values while the
151710** functions are running. See fts3StringAppend() for details.
151711*/
151712typedef struct StrBuffer StrBuffer;
151713struct StrBuffer {
151714  char *z;                        /* Pointer to buffer containing string */
151715  int n;                          /* Length of z in bytes (excl. nul-term) */
151716  int nAlloc;                     /* Allocated size of buffer z in bytes */
151717};
151718
151719
151720/*************************************************************************
151721** Start of MatchinfoBuffer code.
151722*/
151723
151724/*
151725** Allocate a two-slot MatchinfoBuffer object.
151726*/
151727static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
151728  MatchinfoBuffer *pRet;
151729  int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
151730  int nStr = (int)strlen(zMatchinfo);
151731
151732  pRet = sqlite3_malloc(nByte + nStr+1);
151733  if( pRet ){
151734    memset(pRet, 0, nByte);
151735    pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
151736    pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
151737    pRet->nElem = nElem;
151738    pRet->zMatchinfo = ((char*)pRet) + nByte;
151739    memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
151740    pRet->aRef[0] = 1;
151741  }
151742
151743  return pRet;
151744}
151745
151746static void fts3MIBufferFree(void *p){
151747  MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
151748
151749  assert( (u32*)p==&pBuf->aMatchinfo[1]
151750       || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
151751  );
151752  if( (u32*)p==&pBuf->aMatchinfo[1] ){
151753    pBuf->aRef[1] = 0;
151754  }else{
151755    pBuf->aRef[2] = 0;
151756  }
151757
151758  if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
151759    sqlite3_free(pBuf);
151760  }
151761}
151762
151763static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
151764  void (*xRet)(void*) = 0;
151765  u32 *aOut = 0;
151766
151767  if( p->aRef[1]==0 ){
151768    p->aRef[1] = 1;
151769    aOut = &p->aMatchinfo[1];
151770    xRet = fts3MIBufferFree;
151771  }
151772  else if( p->aRef[2]==0 ){
151773    p->aRef[2] = 1;
151774    aOut = &p->aMatchinfo[p->nElem+2];
151775    xRet = fts3MIBufferFree;
151776  }else{
151777    aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
151778    if( aOut ){
151779      xRet = sqlite3_free;
151780      if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
151781    }
151782  }
151783
151784  *paOut = aOut;
151785  return xRet;
151786}
151787
151788static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
151789  p->bGlobal = 1;
151790  memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
151791}
151792
151793/*
151794** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
151795*/
151796SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
151797  if( p ){
151798    assert( p->aRef[0]==1 );
151799    p->aRef[0] = 0;
151800    if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
151801      sqlite3_free(p);
151802    }
151803  }
151804}
151805
151806/*
151807** End of MatchinfoBuffer code.
151808*************************************************************************/
151809
151810
151811/*
151812** This function is used to help iterate through a position-list. A position
151813** list is a list of unique integers, sorted from smallest to largest. Each
151814** element of the list is represented by an FTS3 varint that takes the value
151815** of the difference between the current element and the previous one plus
151816** two. For example, to store the position-list:
151817**
151818**     4 9 113
151819**
151820** the three varints:
151821**
151822**     6 7 106
151823**
151824** are encoded.
151825**
151826** When this function is called, *pp points to the start of an element of
151827** the list. *piPos contains the value of the previous entry in the list.
151828** After it returns, *piPos contains the value of the next element of the
151829** list and *pp is advanced to the following varint.
151830*/
151831static void fts3GetDeltaPosition(char **pp, int *piPos){
151832  int iVal;
151833  *pp += fts3GetVarint32(*pp, &iVal);
151834  *piPos += (iVal-2);
151835}
151836
151837/*
151838** Helper function for fts3ExprIterate() (see below).
151839*/
151840static int fts3ExprIterate2(
151841  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
151842  int *piPhrase,                  /* Pointer to phrase counter */
151843  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
151844  void *pCtx                      /* Second argument to pass to callback */
151845){
151846  int rc;                         /* Return code */
151847  int eType = pExpr->eType;     /* Type of expression node pExpr */
151848
151849  if( eType!=FTSQUERY_PHRASE ){
151850    assert( pExpr->pLeft && pExpr->pRight );
151851    rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
151852    if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
151853      rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
151854    }
151855  }else{
151856    rc = x(pExpr, *piPhrase, pCtx);
151857    (*piPhrase)++;
151858  }
151859  return rc;
151860}
151861
151862/*
151863** Iterate through all phrase nodes in an FTS3 query, except those that
151864** are part of a sub-tree that is the right-hand-side of a NOT operator.
151865** For each phrase node found, the supplied callback function is invoked.
151866**
151867** If the callback function returns anything other than SQLITE_OK,
151868** the iteration is abandoned and the error code returned immediately.
151869** Otherwise, SQLITE_OK is returned after a callback has been made for
151870** all eligible phrase nodes.
151871*/
151872static int fts3ExprIterate(
151873  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
151874  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
151875  void *pCtx                      /* Second argument to pass to callback */
151876){
151877  int iPhrase = 0;                /* Variable used as the phrase counter */
151878  return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
151879}
151880
151881
151882/*
151883** This is an fts3ExprIterate() callback used while loading the doclists
151884** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
151885** fts3ExprLoadDoclists().
151886*/
151887static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
151888  int rc = SQLITE_OK;
151889  Fts3Phrase *pPhrase = pExpr->pPhrase;
151890  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
151891
151892  UNUSED_PARAMETER(iPhrase);
151893
151894  p->nPhrase++;
151895  p->nToken += pPhrase->nToken;
151896
151897  return rc;
151898}
151899
151900/*
151901** Load the doclists for each phrase in the query associated with FTS3 cursor
151902** pCsr.
151903**
151904** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
151905** phrases in the expression (all phrases except those directly or
151906** indirectly descended from the right-hand-side of a NOT operator). If
151907** pnToken is not NULL, then it is set to the number of tokens in all
151908** matchable phrases of the expression.
151909*/
151910static int fts3ExprLoadDoclists(
151911  Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
151912  int *pnPhrase,                  /* OUT: Number of phrases in query */
151913  int *pnToken                    /* OUT: Number of tokens in query */
151914){
151915  int rc;                         /* Return Code */
151916  LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
151917  sCtx.pCsr = pCsr;
151918  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
151919  if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
151920  if( pnToken ) *pnToken = sCtx.nToken;
151921  return rc;
151922}
151923
151924static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
151925  (*(int *)ctx)++;
151926  pExpr->iPhrase = iPhrase;
151927  return SQLITE_OK;
151928}
151929static int fts3ExprPhraseCount(Fts3Expr *pExpr){
151930  int nPhrase = 0;
151931  (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
151932  return nPhrase;
151933}
151934
151935/*
151936** Advance the position list iterator specified by the first two
151937** arguments so that it points to the first element with a value greater
151938** than or equal to parameter iNext.
151939*/
151940static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
151941  char *pIter = *ppIter;
151942  if( pIter ){
151943    int iIter = *piIter;
151944
151945    while( iIter<iNext ){
151946      if( 0==(*pIter & 0xFE) ){
151947        iIter = -1;
151948        pIter = 0;
151949        break;
151950      }
151951      fts3GetDeltaPosition(&pIter, &iIter);
151952    }
151953
151954    *piIter = iIter;
151955    *ppIter = pIter;
151956  }
151957}
151958
151959/*
151960** Advance the snippet iterator to the next candidate snippet.
151961*/
151962static int fts3SnippetNextCandidate(SnippetIter *pIter){
151963  int i;                          /* Loop counter */
151964
151965  if( pIter->iCurrent<0 ){
151966    /* The SnippetIter object has just been initialized. The first snippet
151967    ** candidate always starts at offset 0 (even if this candidate has a
151968    ** score of 0.0).
151969    */
151970    pIter->iCurrent = 0;
151971
151972    /* Advance the 'head' iterator of each phrase to the first offset that
151973    ** is greater than or equal to (iNext+nSnippet).
151974    */
151975    for(i=0; i<pIter->nPhrase; i++){
151976      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
151977      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
151978    }
151979  }else{
151980    int iStart;
151981    int iEnd = 0x7FFFFFFF;
151982
151983    for(i=0; i<pIter->nPhrase; i++){
151984      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
151985      if( pPhrase->pHead && pPhrase->iHead<iEnd ){
151986        iEnd = pPhrase->iHead;
151987      }
151988    }
151989    if( iEnd==0x7FFFFFFF ){
151990      return 1;
151991    }
151992
151993    pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
151994    for(i=0; i<pIter->nPhrase; i++){
151995      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
151996      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
151997      fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
151998    }
151999  }
152000
152001  return 0;
152002}
152003
152004/*
152005** Retrieve information about the current candidate snippet of snippet
152006** iterator pIter.
152007*/
152008static void fts3SnippetDetails(
152009  SnippetIter *pIter,             /* Snippet iterator */
152010  u64 mCovered,                   /* Bitmask of phrases already covered */
152011  int *piToken,                   /* OUT: First token of proposed snippet */
152012  int *piScore,                   /* OUT: "Score" for this snippet */
152013  u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
152014  u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
152015){
152016  int iStart = pIter->iCurrent;   /* First token of snippet */
152017  int iScore = 0;                 /* Score of this snippet */
152018  int i;                          /* Loop counter */
152019  u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
152020  u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
152021
152022  for(i=0; i<pIter->nPhrase; i++){
152023    SnippetPhrase *pPhrase = &pIter->aPhrase[i];
152024    if( pPhrase->pTail ){
152025      char *pCsr = pPhrase->pTail;
152026      int iCsr = pPhrase->iTail;
152027
152028      while( iCsr<(iStart+pIter->nSnippet) ){
152029        int j;
152030        u64 mPhrase = (u64)1 << i;
152031        u64 mPos = (u64)1 << (iCsr - iStart);
152032        assert( iCsr>=iStart );
152033        if( (mCover|mCovered)&mPhrase ){
152034          iScore++;
152035        }else{
152036          iScore += 1000;
152037        }
152038        mCover |= mPhrase;
152039
152040        for(j=0; j<pPhrase->nToken; j++){
152041          mHighlight |= (mPos>>j);
152042        }
152043
152044        if( 0==(*pCsr & 0x0FE) ) break;
152045        fts3GetDeltaPosition(&pCsr, &iCsr);
152046      }
152047    }
152048  }
152049
152050  /* Set the output variables before returning. */
152051  *piToken = iStart;
152052  *piScore = iScore;
152053  *pmCover = mCover;
152054  *pmHighlight = mHighlight;
152055}
152056
152057/*
152058** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
152059** Each invocation populates an element of the SnippetIter.aPhrase[] array.
152060*/
152061static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
152062  SnippetIter *p = (SnippetIter *)ctx;
152063  SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
152064  char *pCsr;
152065  int rc;
152066
152067  pPhrase->nToken = pExpr->pPhrase->nToken;
152068  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
152069  assert( rc==SQLITE_OK || pCsr==0 );
152070  if( pCsr ){
152071    int iFirst = 0;
152072    pPhrase->pList = pCsr;
152073    fts3GetDeltaPosition(&pCsr, &iFirst);
152074    assert( iFirst>=0 );
152075    pPhrase->pHead = pCsr;
152076    pPhrase->pTail = pCsr;
152077    pPhrase->iHead = iFirst;
152078    pPhrase->iTail = iFirst;
152079  }else{
152080    assert( rc!=SQLITE_OK || (
152081       pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
152082    ));
152083  }
152084
152085  return rc;
152086}
152087
152088/*
152089** Select the fragment of text consisting of nFragment contiguous tokens
152090** from column iCol that represent the "best" snippet. The best snippet
152091** is the snippet with the highest score, where scores are calculated
152092** by adding:
152093**
152094**   (a) +1 point for each occurrence of a matchable phrase in the snippet.
152095**
152096**   (b) +1000 points for the first occurrence of each matchable phrase in
152097**       the snippet for which the corresponding mCovered bit is not set.
152098**
152099** The selected snippet parameters are stored in structure *pFragment before
152100** returning. The score of the selected snippet is stored in *piScore
152101** before returning.
152102*/
152103static int fts3BestSnippet(
152104  int nSnippet,                   /* Desired snippet length */
152105  Fts3Cursor *pCsr,               /* Cursor to create snippet for */
152106  int iCol,                       /* Index of column to create snippet from */
152107  u64 mCovered,                   /* Mask of phrases already covered */
152108  u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
152109  SnippetFragment *pFragment,     /* OUT: Best snippet found */
152110  int *piScore                    /* OUT: Score of snippet pFragment */
152111){
152112  int rc;                         /* Return Code */
152113  int nList;                      /* Number of phrases in expression */
152114  SnippetIter sIter;              /* Iterates through snippet candidates */
152115  int nByte;                      /* Number of bytes of space to allocate */
152116  int iBestScore = -1;            /* Best snippet score found so far */
152117  int i;                          /* Loop counter */
152118
152119  memset(&sIter, 0, sizeof(sIter));
152120
152121  /* Iterate through the phrases in the expression to count them. The same
152122  ** callback makes sure the doclists are loaded for each phrase.
152123  */
152124  rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
152125  if( rc!=SQLITE_OK ){
152126    return rc;
152127  }
152128
152129  /* Now that it is known how many phrases there are, allocate and zero
152130  ** the required space using malloc().
152131  */
152132  nByte = sizeof(SnippetPhrase) * nList;
152133  sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
152134  if( !sIter.aPhrase ){
152135    return SQLITE_NOMEM;
152136  }
152137  memset(sIter.aPhrase, 0, nByte);
152138
152139  /* Initialize the contents of the SnippetIter object. Then iterate through
152140  ** the set of phrases in the expression to populate the aPhrase[] array.
152141  */
152142  sIter.pCsr = pCsr;
152143  sIter.iCol = iCol;
152144  sIter.nSnippet = nSnippet;
152145  sIter.nPhrase = nList;
152146  sIter.iCurrent = -1;
152147  rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
152148  if( rc==SQLITE_OK ){
152149
152150    /* Set the *pmSeen output variable. */
152151    for(i=0; i<nList; i++){
152152      if( sIter.aPhrase[i].pHead ){
152153        *pmSeen |= (u64)1 << i;
152154      }
152155    }
152156
152157    /* Loop through all candidate snippets. Store the best snippet in
152158     ** *pFragment. Store its associated 'score' in iBestScore.
152159     */
152160    pFragment->iCol = iCol;
152161    while( !fts3SnippetNextCandidate(&sIter) ){
152162      int iPos;
152163      int iScore;
152164      u64 mCover;
152165      u64 mHighlite;
152166      fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
152167      assert( iScore>=0 );
152168      if( iScore>iBestScore ){
152169        pFragment->iPos = iPos;
152170        pFragment->hlmask = mHighlite;
152171        pFragment->covered = mCover;
152172        iBestScore = iScore;
152173      }
152174    }
152175
152176    *piScore = iBestScore;
152177  }
152178  sqlite3_free(sIter.aPhrase);
152179  return rc;
152180}
152181
152182
152183/*
152184** Append a string to the string-buffer passed as the first argument.
152185**
152186** If nAppend is negative, then the length of the string zAppend is
152187** determined using strlen().
152188*/
152189static int fts3StringAppend(
152190  StrBuffer *pStr,                /* Buffer to append to */
152191  const char *zAppend,            /* Pointer to data to append to buffer */
152192  int nAppend                     /* Size of zAppend in bytes (or -1) */
152193){
152194  if( nAppend<0 ){
152195    nAppend = (int)strlen(zAppend);
152196  }
152197
152198  /* If there is insufficient space allocated at StrBuffer.z, use realloc()
152199  ** to grow the buffer until so that it is big enough to accomadate the
152200  ** appended data.
152201  */
152202  if( pStr->n+nAppend+1>=pStr->nAlloc ){
152203    int nAlloc = pStr->nAlloc+nAppend+100;
152204    char *zNew = sqlite3_realloc(pStr->z, nAlloc);
152205    if( !zNew ){
152206      return SQLITE_NOMEM;
152207    }
152208    pStr->z = zNew;
152209    pStr->nAlloc = nAlloc;
152210  }
152211  assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
152212
152213  /* Append the data to the string buffer. */
152214  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
152215  pStr->n += nAppend;
152216  pStr->z[pStr->n] = '\0';
152217
152218  return SQLITE_OK;
152219}
152220
152221/*
152222** The fts3BestSnippet() function often selects snippets that end with a
152223** query term. That is, the final term of the snippet is always a term
152224** that requires highlighting. For example, if 'X' is a highlighted term
152225** and '.' is a non-highlighted term, BestSnippet() may select:
152226**
152227**     ........X.....X
152228**
152229** This function "shifts" the beginning of the snippet forward in the
152230** document so that there are approximately the same number of
152231** non-highlighted terms to the right of the final highlighted term as there
152232** are to the left of the first highlighted term. For example, to this:
152233**
152234**     ....X.....X....
152235**
152236** This is done as part of extracting the snippet text, not when selecting
152237** the snippet. Snippet selection is done based on doclists only, so there
152238** is no way for fts3BestSnippet() to know whether or not the document
152239** actually contains terms that follow the final highlighted term.
152240*/
152241static int fts3SnippetShift(
152242  Fts3Table *pTab,                /* FTS3 table snippet comes from */
152243  int iLangid,                    /* Language id to use in tokenizing */
152244  int nSnippet,                   /* Number of tokens desired for snippet */
152245  const char *zDoc,               /* Document text to extract snippet from */
152246  int nDoc,                       /* Size of buffer zDoc in bytes */
152247  int *piPos,                     /* IN/OUT: First token of snippet */
152248  u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
152249){
152250  u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
152251
152252  if( hlmask ){
152253    int nLeft;                    /* Tokens to the left of first highlight */
152254    int nRight;                   /* Tokens to the right of last highlight */
152255    int nDesired;                 /* Ideal number of tokens to shift forward */
152256
152257    for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
152258    for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
152259    nDesired = (nLeft-nRight)/2;
152260
152261    /* Ideally, the start of the snippet should be pushed forward in the
152262    ** document nDesired tokens. This block checks if there are actually
152263    ** nDesired tokens to the right of the snippet. If so, *piPos and
152264    ** *pHlMask are updated to shift the snippet nDesired tokens to the
152265    ** right. Otherwise, the snippet is shifted by the number of tokens
152266    ** available.
152267    */
152268    if( nDesired>0 ){
152269      int nShift;                 /* Number of tokens to shift snippet by */
152270      int iCurrent = 0;           /* Token counter */
152271      int rc;                     /* Return Code */
152272      sqlite3_tokenizer_module *pMod;
152273      sqlite3_tokenizer_cursor *pC;
152274      pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
152275
152276      /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
152277      ** or more tokens in zDoc/nDoc.
152278      */
152279      rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
152280      if( rc!=SQLITE_OK ){
152281        return rc;
152282      }
152283      while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
152284        const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
152285        rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
152286      }
152287      pMod->xClose(pC);
152288      if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
152289
152290      nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
152291      assert( nShift<=nDesired );
152292      if( nShift>0 ){
152293        *piPos += nShift;
152294        *pHlmask = hlmask >> nShift;
152295      }
152296    }
152297  }
152298  return SQLITE_OK;
152299}
152300
152301/*
152302** Extract the snippet text for fragment pFragment from cursor pCsr and
152303** append it to string buffer pOut.
152304*/
152305static int fts3SnippetText(
152306  Fts3Cursor *pCsr,               /* FTS3 Cursor */
152307  SnippetFragment *pFragment,     /* Snippet to extract */
152308  int iFragment,                  /* Fragment number */
152309  int isLast,                     /* True for final fragment in snippet */
152310  int nSnippet,                   /* Number of tokens in extracted snippet */
152311  const char *zOpen,              /* String inserted before highlighted term */
152312  const char *zClose,             /* String inserted after highlighted term */
152313  const char *zEllipsis,          /* String inserted between snippets */
152314  StrBuffer *pOut                 /* Write output here */
152315){
152316  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
152317  int rc;                         /* Return code */
152318  const char *zDoc;               /* Document text to extract snippet from */
152319  int nDoc;                       /* Size of zDoc in bytes */
152320  int iCurrent = 0;               /* Current token number of document */
152321  int iEnd = 0;                   /* Byte offset of end of current token */
152322  int isShiftDone = 0;            /* True after snippet is shifted */
152323  int iPos = pFragment->iPos;     /* First token of snippet */
152324  u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
152325  int iCol = pFragment->iCol+1;   /* Query column to extract text from */
152326  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
152327  sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
152328
152329  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
152330  if( zDoc==0 ){
152331    if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
152332      return SQLITE_NOMEM;
152333    }
152334    return SQLITE_OK;
152335  }
152336  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
152337
152338  /* Open a token cursor on the document. */
152339  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
152340  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
152341  if( rc!=SQLITE_OK ){
152342    return rc;
152343  }
152344
152345  while( rc==SQLITE_OK ){
152346    const char *ZDUMMY;           /* Dummy argument used with tokenizer */
152347    int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
152348    int iBegin = 0;               /* Offset in zDoc of start of token */
152349    int iFin = 0;                 /* Offset in zDoc of end of token */
152350    int isHighlight = 0;          /* True for highlighted terms */
152351
152352    /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
152353    ** in the FTS code the variable that the third argument to xNext points to
152354    ** is initialized to zero before the first (*but not necessarily
152355    ** subsequent*) call to xNext(). This is done for a particular application
152356    ** that needs to know whether or not the tokenizer is being used for
152357    ** snippet generation or for some other purpose.
152358    **
152359    ** Extreme care is required when writing code to depend on this
152360    ** initialization. It is not a documented part of the tokenizer interface.
152361    ** If a tokenizer is used directly by any code outside of FTS, this
152362    ** convention might not be respected.  */
152363    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
152364    if( rc!=SQLITE_OK ){
152365      if( rc==SQLITE_DONE ){
152366        /* Special case - the last token of the snippet is also the last token
152367        ** of the column. Append any punctuation that occurred between the end
152368        ** of the previous token and the end of the document to the output.
152369        ** Then break out of the loop. */
152370        rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
152371      }
152372      break;
152373    }
152374    if( iCurrent<iPos ){ continue; }
152375
152376    if( !isShiftDone ){
152377      int n = nDoc - iBegin;
152378      rc = fts3SnippetShift(
152379          pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
152380      );
152381      isShiftDone = 1;
152382
152383      /* Now that the shift has been done, check if the initial "..." are
152384      ** required. They are required if (a) this is not the first fragment,
152385      ** or (b) this fragment does not begin at position 0 of its column.
152386      */
152387      if( rc==SQLITE_OK ){
152388        if( iPos>0 || iFragment>0 ){
152389          rc = fts3StringAppend(pOut, zEllipsis, -1);
152390        }else if( iBegin ){
152391          rc = fts3StringAppend(pOut, zDoc, iBegin);
152392        }
152393      }
152394      if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
152395    }
152396
152397    if( iCurrent>=(iPos+nSnippet) ){
152398      if( isLast ){
152399        rc = fts3StringAppend(pOut, zEllipsis, -1);
152400      }
152401      break;
152402    }
152403
152404    /* Set isHighlight to true if this term should be highlighted. */
152405    isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
152406
152407    if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
152408    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
152409    if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
152410    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
152411
152412    iEnd = iFin;
152413  }
152414
152415  pMod->xClose(pC);
152416  return rc;
152417}
152418
152419
152420/*
152421** This function is used to count the entries in a column-list (a
152422** delta-encoded list of term offsets within a single column of a single
152423** row). When this function is called, *ppCollist should point to the
152424** beginning of the first varint in the column-list (the varint that
152425** contains the position of the first matching term in the column data).
152426** Before returning, *ppCollist is set to point to the first byte after
152427** the last varint in the column-list (either the 0x00 signifying the end
152428** of the position-list, or the 0x01 that precedes the column number of
152429** the next column in the position-list).
152430**
152431** The number of elements in the column-list is returned.
152432*/
152433static int fts3ColumnlistCount(char **ppCollist){
152434  char *pEnd = *ppCollist;
152435  char c = 0;
152436  int nEntry = 0;
152437
152438  /* A column-list is terminated by either a 0x01 or 0x00. */
152439  while( 0xFE & (*pEnd | c) ){
152440    c = *pEnd++ & 0x80;
152441    if( !c ) nEntry++;
152442  }
152443
152444  *ppCollist = pEnd;
152445  return nEntry;
152446}
152447
152448/*
152449** This function gathers 'y' or 'b' data for a single phrase.
152450*/
152451static void fts3ExprLHits(
152452  Fts3Expr *pExpr,                /* Phrase expression node */
152453  MatchInfo *p                    /* Matchinfo context */
152454){
152455  Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
152456  int iStart;
152457  Fts3Phrase *pPhrase = pExpr->pPhrase;
152458  char *pIter = pPhrase->doclist.pList;
152459  int iCol = 0;
152460
152461  assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
152462  if( p->flag==FTS3_MATCHINFO_LHITS ){
152463    iStart = pExpr->iPhrase * p->nCol;
152464  }else{
152465    iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
152466  }
152467
152468  while( 1 ){
152469    int nHit = fts3ColumnlistCount(&pIter);
152470    if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
152471      if( p->flag==FTS3_MATCHINFO_LHITS ){
152472        p->aMatchinfo[iStart + iCol] = (u32)nHit;
152473      }else if( nHit ){
152474        p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
152475      }
152476    }
152477    assert( *pIter==0x00 || *pIter==0x01 );
152478    if( *pIter!=0x01 ) break;
152479    pIter++;
152480    pIter += fts3GetVarint32(pIter, &iCol);
152481  }
152482}
152483
152484/*
152485** Gather the results for matchinfo directives 'y' and 'b'.
152486*/
152487static void fts3ExprLHitGather(
152488  Fts3Expr *pExpr,
152489  MatchInfo *p
152490){
152491  assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
152492  if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
152493    if( pExpr->pLeft ){
152494      fts3ExprLHitGather(pExpr->pLeft, p);
152495      fts3ExprLHitGather(pExpr->pRight, p);
152496    }else{
152497      fts3ExprLHits(pExpr, p);
152498    }
152499  }
152500}
152501
152502/*
152503** fts3ExprIterate() callback used to collect the "global" matchinfo stats
152504** for a single query.
152505**
152506** fts3ExprIterate() callback to load the 'global' elements of a
152507** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
152508** of the matchinfo array that are constant for all rows returned by the
152509** current query.
152510**
152511** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
152512** function populates Matchinfo.aMatchinfo[] as follows:
152513**
152514**   for(iCol=0; iCol<nCol; iCol++){
152515**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
152516**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
152517**   }
152518**
152519** where X is the number of matches for phrase iPhrase is column iCol of all
152520** rows of the table. Y is the number of rows for which column iCol contains
152521** at least one instance of phrase iPhrase.
152522**
152523** If the phrase pExpr consists entirely of deferred tokens, then all X and
152524** Y values are set to nDoc, where nDoc is the number of documents in the
152525** file system. This is done because the full-text index doclist is required
152526** to calculate these values properly, and the full-text index doclist is
152527** not available for deferred tokens.
152528*/
152529static int fts3ExprGlobalHitsCb(
152530  Fts3Expr *pExpr,                /* Phrase expression node */
152531  int iPhrase,                    /* Phrase number (numbered from zero) */
152532  void *pCtx                      /* Pointer to MatchInfo structure */
152533){
152534  MatchInfo *p = (MatchInfo *)pCtx;
152535  return sqlite3Fts3EvalPhraseStats(
152536      p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
152537  );
152538}
152539
152540/*
152541** fts3ExprIterate() callback used to collect the "local" part of the
152542** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
152543** array that are different for each row returned by the query.
152544*/
152545static int fts3ExprLocalHitsCb(
152546  Fts3Expr *pExpr,                /* Phrase expression node */
152547  int iPhrase,                    /* Phrase number */
152548  void *pCtx                      /* Pointer to MatchInfo structure */
152549){
152550  int rc = SQLITE_OK;
152551  MatchInfo *p = (MatchInfo *)pCtx;
152552  int iStart = iPhrase * p->nCol * 3;
152553  int i;
152554
152555  for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
152556    char *pCsr;
152557    rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
152558    if( pCsr ){
152559      p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
152560    }else{
152561      p->aMatchinfo[iStart+i*3] = 0;
152562    }
152563  }
152564
152565  return rc;
152566}
152567
152568static int fts3MatchinfoCheck(
152569  Fts3Table *pTab,
152570  char cArg,
152571  char **pzErr
152572){
152573  if( (cArg==FTS3_MATCHINFO_NPHRASE)
152574   || (cArg==FTS3_MATCHINFO_NCOL)
152575   || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
152576   || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
152577   || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
152578   || (cArg==FTS3_MATCHINFO_LCS)
152579   || (cArg==FTS3_MATCHINFO_HITS)
152580   || (cArg==FTS3_MATCHINFO_LHITS)
152581   || (cArg==FTS3_MATCHINFO_LHITS_BM)
152582  ){
152583    return SQLITE_OK;
152584  }
152585  sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
152586  return SQLITE_ERROR;
152587}
152588
152589static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
152590  int nVal;                       /* Number of integers output by cArg */
152591
152592  switch( cArg ){
152593    case FTS3_MATCHINFO_NDOC:
152594    case FTS3_MATCHINFO_NPHRASE:
152595    case FTS3_MATCHINFO_NCOL:
152596      nVal = 1;
152597      break;
152598
152599    case FTS3_MATCHINFO_AVGLENGTH:
152600    case FTS3_MATCHINFO_LENGTH:
152601    case FTS3_MATCHINFO_LCS:
152602      nVal = pInfo->nCol;
152603      break;
152604
152605    case FTS3_MATCHINFO_LHITS:
152606      nVal = pInfo->nCol * pInfo->nPhrase;
152607      break;
152608
152609    case FTS3_MATCHINFO_LHITS_BM:
152610      nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
152611      break;
152612
152613    default:
152614      assert( cArg==FTS3_MATCHINFO_HITS );
152615      nVal = pInfo->nCol * pInfo->nPhrase * 3;
152616      break;
152617  }
152618
152619  return nVal;
152620}
152621
152622static int fts3MatchinfoSelectDoctotal(
152623  Fts3Table *pTab,
152624  sqlite3_stmt **ppStmt,
152625  sqlite3_int64 *pnDoc,
152626  const char **paLen
152627){
152628  sqlite3_stmt *pStmt;
152629  const char *a;
152630  sqlite3_int64 nDoc;
152631
152632  if( !*ppStmt ){
152633    int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
152634    if( rc!=SQLITE_OK ) return rc;
152635  }
152636  pStmt = *ppStmt;
152637  assert( sqlite3_data_count(pStmt)==1 );
152638
152639  a = sqlite3_column_blob(pStmt, 0);
152640  a += sqlite3Fts3GetVarint(a, &nDoc);
152641  if( nDoc==0 ) return FTS_CORRUPT_VTAB;
152642  *pnDoc = (u32)nDoc;
152643
152644  if( paLen ) *paLen = a;
152645  return SQLITE_OK;
152646}
152647
152648/*
152649** An instance of the following structure is used to store state while
152650** iterating through a multi-column position-list corresponding to the
152651** hits for a single phrase on a single row in order to calculate the
152652** values for a matchinfo() FTS3_MATCHINFO_LCS request.
152653*/
152654typedef struct LcsIterator LcsIterator;
152655struct LcsIterator {
152656  Fts3Expr *pExpr;                /* Pointer to phrase expression */
152657  int iPosOffset;                 /* Tokens count up to end of this phrase */
152658  char *pRead;                    /* Cursor used to iterate through aDoclist */
152659  int iPos;                       /* Current position */
152660};
152661
152662/*
152663** If LcsIterator.iCol is set to the following value, the iterator has
152664** finished iterating through all offsets for all columns.
152665*/
152666#define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
152667
152668static int fts3MatchinfoLcsCb(
152669  Fts3Expr *pExpr,                /* Phrase expression node */
152670  int iPhrase,                    /* Phrase number (numbered from zero) */
152671  void *pCtx                      /* Pointer to MatchInfo structure */
152672){
152673  LcsIterator *aIter = (LcsIterator *)pCtx;
152674  aIter[iPhrase].pExpr = pExpr;
152675  return SQLITE_OK;
152676}
152677
152678/*
152679** Advance the iterator passed as an argument to the next position. Return
152680** 1 if the iterator is at EOF or if it now points to the start of the
152681** position list for the next column.
152682*/
152683static int fts3LcsIteratorAdvance(LcsIterator *pIter){
152684  char *pRead = pIter->pRead;
152685  sqlite3_int64 iRead;
152686  int rc = 0;
152687
152688  pRead += sqlite3Fts3GetVarint(pRead, &iRead);
152689  if( iRead==0 || iRead==1 ){
152690    pRead = 0;
152691    rc = 1;
152692  }else{
152693    pIter->iPos += (int)(iRead-2);
152694  }
152695
152696  pIter->pRead = pRead;
152697  return rc;
152698}
152699
152700/*
152701** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
152702**
152703** If the call is successful, the longest-common-substring lengths for each
152704** column are written into the first nCol elements of the pInfo->aMatchinfo[]
152705** array before returning. SQLITE_OK is returned in this case.
152706**
152707** Otherwise, if an error occurs, an SQLite error code is returned and the
152708** data written to the first nCol elements of pInfo->aMatchinfo[] is
152709** undefined.
152710*/
152711static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
152712  LcsIterator *aIter;
152713  int i;
152714  int iCol;
152715  int nToken = 0;
152716
152717  /* Allocate and populate the array of LcsIterator objects. The array
152718  ** contains one element for each matchable phrase in the query.
152719  **/
152720  aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
152721  if( !aIter ) return SQLITE_NOMEM;
152722  memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
152723  (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
152724
152725  for(i=0; i<pInfo->nPhrase; i++){
152726    LcsIterator *pIter = &aIter[i];
152727    nToken -= pIter->pExpr->pPhrase->nToken;
152728    pIter->iPosOffset = nToken;
152729  }
152730
152731  for(iCol=0; iCol<pInfo->nCol; iCol++){
152732    int nLcs = 0;                 /* LCS value for this column */
152733    int nLive = 0;                /* Number of iterators in aIter not at EOF */
152734
152735    for(i=0; i<pInfo->nPhrase; i++){
152736      int rc;
152737      LcsIterator *pIt = &aIter[i];
152738      rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
152739      if( rc!=SQLITE_OK ) return rc;
152740      if( pIt->pRead ){
152741        pIt->iPos = pIt->iPosOffset;
152742        fts3LcsIteratorAdvance(&aIter[i]);
152743        nLive++;
152744      }
152745    }
152746
152747    while( nLive>0 ){
152748      LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
152749      int nThisLcs = 0;           /* LCS for the current iterator positions */
152750
152751      for(i=0; i<pInfo->nPhrase; i++){
152752        LcsIterator *pIter = &aIter[i];
152753        if( pIter->pRead==0 ){
152754          /* This iterator is already at EOF for this column. */
152755          nThisLcs = 0;
152756        }else{
152757          if( pAdv==0 || pIter->iPos<pAdv->iPos ){
152758            pAdv = pIter;
152759          }
152760          if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
152761            nThisLcs++;
152762          }else{
152763            nThisLcs = 1;
152764          }
152765          if( nThisLcs>nLcs ) nLcs = nThisLcs;
152766        }
152767      }
152768      if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
152769    }
152770
152771    pInfo->aMatchinfo[iCol] = nLcs;
152772  }
152773
152774  sqlite3_free(aIter);
152775  return SQLITE_OK;
152776}
152777
152778/*
152779** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
152780** be returned by the matchinfo() function. Argument zArg contains the
152781** format string passed as the second argument to matchinfo (or the
152782** default value "pcx" if no second argument was specified). The format
152783** string has already been validated and the pInfo->aMatchinfo[] array
152784** is guaranteed to be large enough for the output.
152785**
152786** If bGlobal is true, then populate all fields of the matchinfo() output.
152787** If it is false, then assume that those fields that do not change between
152788** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
152789** have already been populated.
152790**
152791** Return SQLITE_OK if successful, or an SQLite error code if an error
152792** occurs. If a value other than SQLITE_OK is returned, the state the
152793** pInfo->aMatchinfo[] buffer is left in is undefined.
152794*/
152795static int fts3MatchinfoValues(
152796  Fts3Cursor *pCsr,               /* FTS3 cursor object */
152797  int bGlobal,                    /* True to grab the global stats */
152798  MatchInfo *pInfo,               /* Matchinfo context object */
152799  const char *zArg                /* Matchinfo format string */
152800){
152801  int rc = SQLITE_OK;
152802  int i;
152803  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
152804  sqlite3_stmt *pSelect = 0;
152805
152806  for(i=0; rc==SQLITE_OK && zArg[i]; i++){
152807    pInfo->flag = zArg[i];
152808    switch( zArg[i] ){
152809      case FTS3_MATCHINFO_NPHRASE:
152810        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
152811        break;
152812
152813      case FTS3_MATCHINFO_NCOL:
152814        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
152815        break;
152816
152817      case FTS3_MATCHINFO_NDOC:
152818        if( bGlobal ){
152819          sqlite3_int64 nDoc = 0;
152820          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
152821          pInfo->aMatchinfo[0] = (u32)nDoc;
152822        }
152823        break;
152824
152825      case FTS3_MATCHINFO_AVGLENGTH:
152826        if( bGlobal ){
152827          sqlite3_int64 nDoc;     /* Number of rows in table */
152828          const char *a;          /* Aggregate column length array */
152829
152830          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
152831          if( rc==SQLITE_OK ){
152832            int iCol;
152833            for(iCol=0; iCol<pInfo->nCol; iCol++){
152834              u32 iVal;
152835              sqlite3_int64 nToken;
152836              a += sqlite3Fts3GetVarint(a, &nToken);
152837              iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
152838              pInfo->aMatchinfo[iCol] = iVal;
152839            }
152840          }
152841        }
152842        break;
152843
152844      case FTS3_MATCHINFO_LENGTH: {
152845        sqlite3_stmt *pSelectDocsize = 0;
152846        rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
152847        if( rc==SQLITE_OK ){
152848          int iCol;
152849          const char *a = sqlite3_column_blob(pSelectDocsize, 0);
152850          for(iCol=0; iCol<pInfo->nCol; iCol++){
152851            sqlite3_int64 nToken;
152852            a += sqlite3Fts3GetVarint(a, &nToken);
152853            pInfo->aMatchinfo[iCol] = (u32)nToken;
152854          }
152855        }
152856        sqlite3_reset(pSelectDocsize);
152857        break;
152858      }
152859
152860      case FTS3_MATCHINFO_LCS:
152861        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
152862        if( rc==SQLITE_OK ){
152863          rc = fts3MatchinfoLcs(pCsr, pInfo);
152864        }
152865        break;
152866
152867      case FTS3_MATCHINFO_LHITS_BM:
152868      case FTS3_MATCHINFO_LHITS: {
152869        int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
152870        memset(pInfo->aMatchinfo, 0, nZero);
152871        fts3ExprLHitGather(pCsr->pExpr, pInfo);
152872        break;
152873      }
152874
152875      default: {
152876        Fts3Expr *pExpr;
152877        assert( zArg[i]==FTS3_MATCHINFO_HITS );
152878        pExpr = pCsr->pExpr;
152879        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
152880        if( rc!=SQLITE_OK ) break;
152881        if( bGlobal ){
152882          if( pCsr->pDeferred ){
152883            rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
152884            if( rc!=SQLITE_OK ) break;
152885          }
152886          rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
152887          sqlite3Fts3EvalTestDeferred(pCsr, &rc);
152888          if( rc!=SQLITE_OK ) break;
152889        }
152890        (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
152891        break;
152892      }
152893    }
152894
152895    pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
152896  }
152897
152898  sqlite3_reset(pSelect);
152899  return rc;
152900}
152901
152902
152903/*
152904** Populate pCsr->aMatchinfo[] with data for the current row. The
152905** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
152906*/
152907static void fts3GetMatchinfo(
152908  sqlite3_context *pCtx,        /* Return results here */
152909  Fts3Cursor *pCsr,               /* FTS3 Cursor object */
152910  const char *zArg                /* Second argument to matchinfo() function */
152911){
152912  MatchInfo sInfo;
152913  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
152914  int rc = SQLITE_OK;
152915  int bGlobal = 0;                /* Collect 'global' stats as well as local */
152916
152917  u32 *aOut = 0;
152918  void (*xDestroyOut)(void*) = 0;
152919
152920  memset(&sInfo, 0, sizeof(MatchInfo));
152921  sInfo.pCursor = pCsr;
152922  sInfo.nCol = pTab->nColumn;
152923
152924  /* If there is cached matchinfo() data, but the format string for the
152925  ** cache does not match the format string for this request, discard
152926  ** the cached data. */
152927  if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
152928    sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
152929    pCsr->pMIBuffer = 0;
152930  }
152931
152932  /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
152933  ** matchinfo function has been called for this query. In this case
152934  ** allocate the array used to accumulate the matchinfo data and
152935  ** initialize those elements that are constant for every row.
152936  */
152937  if( pCsr->pMIBuffer==0 ){
152938    int nMatchinfo = 0;           /* Number of u32 elements in match-info */
152939    int i;                        /* Used to iterate through zArg */
152940
152941    /* Determine the number of phrases in the query */
152942    pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
152943    sInfo.nPhrase = pCsr->nPhrase;
152944
152945    /* Determine the number of integers in the buffer returned by this call. */
152946    for(i=0; zArg[i]; i++){
152947      char *zErr = 0;
152948      if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
152949        sqlite3_result_error(pCtx, zErr, -1);
152950        sqlite3_free(zErr);
152951        return;
152952      }
152953      nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
152954    }
152955
152956    /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
152957    pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
152958    if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
152959
152960    pCsr->isMatchinfoNeeded = 1;
152961    bGlobal = 1;
152962  }
152963
152964  if( rc==SQLITE_OK ){
152965    xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
152966    if( xDestroyOut==0 ){
152967      rc = SQLITE_NOMEM;
152968    }
152969  }
152970
152971  if( rc==SQLITE_OK ){
152972    sInfo.aMatchinfo = aOut;
152973    sInfo.nPhrase = pCsr->nPhrase;
152974    rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
152975    if( bGlobal ){
152976      fts3MIBufferSetGlobal(pCsr->pMIBuffer);
152977    }
152978  }
152979
152980  if( rc!=SQLITE_OK ){
152981    sqlite3_result_error_code(pCtx, rc);
152982    if( xDestroyOut ) xDestroyOut(aOut);
152983  }else{
152984    int n = pCsr->pMIBuffer->nElem * sizeof(u32);
152985    sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
152986  }
152987}
152988
152989/*
152990** Implementation of snippet() function.
152991*/
152992SQLITE_PRIVATE void sqlite3Fts3Snippet(
152993  sqlite3_context *pCtx,          /* SQLite function call context */
152994  Fts3Cursor *pCsr,               /* Cursor object */
152995  const char *zStart,             /* Snippet start text - "<b>" */
152996  const char *zEnd,               /* Snippet end text - "</b>" */
152997  const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
152998  int iCol,                       /* Extract snippet from this column */
152999  int nToken                      /* Approximate number of tokens in snippet */
153000){
153001  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
153002  int rc = SQLITE_OK;
153003  int i;
153004  StrBuffer res = {0, 0, 0};
153005
153006  /* The returned text includes up to four fragments of text extracted from
153007  ** the data in the current row. The first iteration of the for(...) loop
153008  ** below attempts to locate a single fragment of text nToken tokens in
153009  ** size that contains at least one instance of all phrases in the query
153010  ** expression that appear in the current row. If such a fragment of text
153011  ** cannot be found, the second iteration of the loop attempts to locate
153012  ** a pair of fragments, and so on.
153013  */
153014  int nSnippet = 0;               /* Number of fragments in this snippet */
153015  SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
153016  int nFToken = -1;               /* Number of tokens in each fragment */
153017
153018  if( !pCsr->pExpr ){
153019    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
153020    return;
153021  }
153022
153023  for(nSnippet=1; 1; nSnippet++){
153024
153025    int iSnip;                    /* Loop counter 0..nSnippet-1 */
153026    u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
153027    u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
153028
153029    if( nToken>=0 ){
153030      nFToken = (nToken+nSnippet-1) / nSnippet;
153031    }else{
153032      nFToken = -1 * nToken;
153033    }
153034
153035    for(iSnip=0; iSnip<nSnippet; iSnip++){
153036      int iBestScore = -1;        /* Best score of columns checked so far */
153037      int iRead;                  /* Used to iterate through columns */
153038      SnippetFragment *pFragment = &aSnippet[iSnip];
153039
153040      memset(pFragment, 0, sizeof(*pFragment));
153041
153042      /* Loop through all columns of the table being considered for snippets.
153043      ** If the iCol argument to this function was negative, this means all
153044      ** columns of the FTS3 table. Otherwise, only column iCol is considered.
153045      */
153046      for(iRead=0; iRead<pTab->nColumn; iRead++){
153047        SnippetFragment sF = {0, 0, 0, 0};
153048        int iS = 0;
153049        if( iCol>=0 && iRead!=iCol ) continue;
153050
153051        /* Find the best snippet of nFToken tokens in column iRead. */
153052        rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
153053        if( rc!=SQLITE_OK ){
153054          goto snippet_out;
153055        }
153056        if( iS>iBestScore ){
153057          *pFragment = sF;
153058          iBestScore = iS;
153059        }
153060      }
153061
153062      mCovered |= pFragment->covered;
153063    }
153064
153065    /* If all query phrases seen by fts3BestSnippet() are present in at least
153066    ** one of the nSnippet snippet fragments, break out of the loop.
153067    */
153068    assert( (mCovered&mSeen)==mCovered );
153069    if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
153070  }
153071
153072  assert( nFToken>0 );
153073
153074  for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
153075    rc = fts3SnippetText(pCsr, &aSnippet[i],
153076        i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
153077    );
153078  }
153079
153080 snippet_out:
153081  sqlite3Fts3SegmentsClose(pTab);
153082  if( rc!=SQLITE_OK ){
153083    sqlite3_result_error_code(pCtx, rc);
153084    sqlite3_free(res.z);
153085  }else{
153086    sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
153087  }
153088}
153089
153090
153091typedef struct TermOffset TermOffset;
153092typedef struct TermOffsetCtx TermOffsetCtx;
153093
153094struct TermOffset {
153095  char *pList;                    /* Position-list */
153096  int iPos;                       /* Position just read from pList */
153097  int iOff;                       /* Offset of this term from read positions */
153098};
153099
153100struct TermOffsetCtx {
153101  Fts3Cursor *pCsr;
153102  int iCol;                       /* Column of table to populate aTerm for */
153103  int iTerm;
153104  sqlite3_int64 iDocid;
153105  TermOffset *aTerm;
153106};
153107
153108/*
153109** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
153110*/
153111static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
153112  TermOffsetCtx *p = (TermOffsetCtx *)ctx;
153113  int nTerm;                      /* Number of tokens in phrase */
153114  int iTerm;                      /* For looping through nTerm phrase terms */
153115  char *pList;                    /* Pointer to position list for phrase */
153116  int iPos = 0;                   /* First position in position-list */
153117  int rc;
153118
153119  UNUSED_PARAMETER(iPhrase);
153120  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
153121  nTerm = pExpr->pPhrase->nToken;
153122  if( pList ){
153123    fts3GetDeltaPosition(&pList, &iPos);
153124    assert( iPos>=0 );
153125  }
153126
153127  for(iTerm=0; iTerm<nTerm; iTerm++){
153128    TermOffset *pT = &p->aTerm[p->iTerm++];
153129    pT->iOff = nTerm-iTerm-1;
153130    pT->pList = pList;
153131    pT->iPos = iPos;
153132  }
153133
153134  return rc;
153135}
153136
153137/*
153138** Implementation of offsets() function.
153139*/
153140SQLITE_PRIVATE void sqlite3Fts3Offsets(
153141  sqlite3_context *pCtx,          /* SQLite function call context */
153142  Fts3Cursor *pCsr                /* Cursor object */
153143){
153144  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
153145  sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
153146  int rc;                         /* Return Code */
153147  int nToken;                     /* Number of tokens in query */
153148  int iCol;                       /* Column currently being processed */
153149  StrBuffer res = {0, 0, 0};      /* Result string */
153150  TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
153151
153152  if( !pCsr->pExpr ){
153153    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
153154    return;
153155  }
153156
153157  memset(&sCtx, 0, sizeof(sCtx));
153158  assert( pCsr->isRequireSeek==0 );
153159
153160  /* Count the number of terms in the query */
153161  rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
153162  if( rc!=SQLITE_OK ) goto offsets_out;
153163
153164  /* Allocate the array of TermOffset iterators. */
153165  sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
153166  if( 0==sCtx.aTerm ){
153167    rc = SQLITE_NOMEM;
153168    goto offsets_out;
153169  }
153170  sCtx.iDocid = pCsr->iPrevId;
153171  sCtx.pCsr = pCsr;
153172
153173  /* Loop through the table columns, appending offset information to
153174  ** string-buffer res for each column.
153175  */
153176  for(iCol=0; iCol<pTab->nColumn; iCol++){
153177    sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
153178    const char *ZDUMMY;           /* Dummy argument used with xNext() */
153179    int NDUMMY = 0;               /* Dummy argument used with xNext() */
153180    int iStart = 0;
153181    int iEnd = 0;
153182    int iCurrent = 0;
153183    const char *zDoc;
153184    int nDoc;
153185
153186    /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
153187    ** no way that this operation can fail, so the return code from
153188    ** fts3ExprIterate() can be discarded.
153189    */
153190    sCtx.iCol = iCol;
153191    sCtx.iTerm = 0;
153192    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
153193
153194    /* Retreive the text stored in column iCol. If an SQL NULL is stored
153195    ** in column iCol, jump immediately to the next iteration of the loop.
153196    ** If an OOM occurs while retrieving the data (this can happen if SQLite
153197    ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
153198    ** to the caller.
153199    */
153200    zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
153201    nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
153202    if( zDoc==0 ){
153203      if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
153204        continue;
153205      }
153206      rc = SQLITE_NOMEM;
153207      goto offsets_out;
153208    }
153209
153210    /* Initialize a tokenizer iterator to iterate through column iCol. */
153211    rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
153212        zDoc, nDoc, &pC
153213    );
153214    if( rc!=SQLITE_OK ) goto offsets_out;
153215
153216    rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
153217    while( rc==SQLITE_OK ){
153218      int i;                      /* Used to loop through terms */
153219      int iMinPos = 0x7FFFFFFF;   /* Position of next token */
153220      TermOffset *pTerm = 0;      /* TermOffset associated with next token */
153221
153222      for(i=0; i<nToken; i++){
153223        TermOffset *pT = &sCtx.aTerm[i];
153224        if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
153225          iMinPos = pT->iPos-pT->iOff;
153226          pTerm = pT;
153227        }
153228      }
153229
153230      if( !pTerm ){
153231        /* All offsets for this column have been gathered. */
153232        rc = SQLITE_DONE;
153233      }else{
153234        assert( iCurrent<=iMinPos );
153235        if( 0==(0xFE&*pTerm->pList) ){
153236          pTerm->pList = 0;
153237        }else{
153238          fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
153239        }
153240        while( rc==SQLITE_OK && iCurrent<iMinPos ){
153241          rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
153242        }
153243        if( rc==SQLITE_OK ){
153244          char aBuffer[64];
153245          sqlite3_snprintf(sizeof(aBuffer), aBuffer,
153246              "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
153247          );
153248          rc = fts3StringAppend(&res, aBuffer, -1);
153249        }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
153250          rc = FTS_CORRUPT_VTAB;
153251        }
153252      }
153253    }
153254    if( rc==SQLITE_DONE ){
153255      rc = SQLITE_OK;
153256    }
153257
153258    pMod->xClose(pC);
153259    if( rc!=SQLITE_OK ) goto offsets_out;
153260  }
153261
153262 offsets_out:
153263  sqlite3_free(sCtx.aTerm);
153264  assert( rc!=SQLITE_DONE );
153265  sqlite3Fts3SegmentsClose(pTab);
153266  if( rc!=SQLITE_OK ){
153267    sqlite3_result_error_code(pCtx,  rc);
153268    sqlite3_free(res.z);
153269  }else{
153270    sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
153271  }
153272  return;
153273}
153274
153275/*
153276** Implementation of matchinfo() function.
153277*/
153278SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
153279  sqlite3_context *pContext,      /* Function call context */
153280  Fts3Cursor *pCsr,               /* FTS3 table cursor */
153281  const char *zArg                /* Second arg to matchinfo() function */
153282){
153283  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
153284  const char *zFormat;
153285
153286  if( zArg ){
153287    zFormat = zArg;
153288  }else{
153289    zFormat = FTS3_MATCHINFO_DEFAULT;
153290  }
153291
153292  if( !pCsr->pExpr ){
153293    sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
153294    return;
153295  }else{
153296    /* Retrieve matchinfo() data. */
153297    fts3GetMatchinfo(pContext, pCsr, zFormat);
153298    sqlite3Fts3SegmentsClose(pTab);
153299  }
153300}
153301
153302#endif
153303
153304/************** End of fts3_snippet.c ****************************************/
153305/************** Begin file fts3_unicode.c ************************************/
153306/*
153307** 2012 May 24
153308**
153309** The author disclaims copyright to this source code.  In place of
153310** a legal notice, here is a blessing:
153311**
153312**    May you do good and not evil.
153313**    May you find forgiveness for yourself and forgive others.
153314**    May you share freely, never taking more than you give.
153315**
153316******************************************************************************
153317**
153318** Implementation of the "unicode" full-text-search tokenizer.
153319*/
153320
153321#ifndef SQLITE_DISABLE_FTS3_UNICODE
153322
153323/* #include "fts3Int.h" */
153324#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
153325
153326/* #include <assert.h> */
153327/* #include <stdlib.h> */
153328/* #include <stdio.h> */
153329/* #include <string.h> */
153330
153331/* #include "fts3_tokenizer.h" */
153332
153333/*
153334** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
153335** from the sqlite3 source file utf.c. If this file is compiled as part
153336** of the amalgamation, they are not required.
153337*/
153338#ifndef SQLITE_AMALGAMATION
153339
153340static const unsigned char sqlite3Utf8Trans1[] = {
153341  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
153342  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
153343  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
153344  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
153345  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
153346  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
153347  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
153348  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
153349};
153350
153351#define READ_UTF8(zIn, zTerm, c)                           \
153352  c = *(zIn++);                                            \
153353  if( c>=0xc0 ){                                           \
153354    c = sqlite3Utf8Trans1[c-0xc0];                         \
153355    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
153356      c = (c<<6) + (0x3f & *(zIn++));                      \
153357    }                                                      \
153358    if( c<0x80                                             \
153359        || (c&0xFFFFF800)==0xD800                          \
153360        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
153361  }
153362
153363#define WRITE_UTF8(zOut, c) {                          \
153364  if( c<0x00080 ){                                     \
153365    *zOut++ = (u8)(c&0xFF);                            \
153366  }                                                    \
153367  else if( c<0x00800 ){                                \
153368    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
153369    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
153370  }                                                    \
153371  else if( c<0x10000 ){                                \
153372    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
153373    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
153374    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
153375  }else{                                               \
153376    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
153377    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
153378    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
153379    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
153380  }                                                    \
153381}
153382
153383#endif /* ifndef SQLITE_AMALGAMATION */
153384
153385typedef struct unicode_tokenizer unicode_tokenizer;
153386typedef struct unicode_cursor unicode_cursor;
153387
153388struct unicode_tokenizer {
153389  sqlite3_tokenizer base;
153390  int bRemoveDiacritic;
153391  int nException;
153392  int *aiException;
153393};
153394
153395struct unicode_cursor {
153396  sqlite3_tokenizer_cursor base;
153397  const unsigned char *aInput;    /* Input text being tokenized */
153398  int nInput;                     /* Size of aInput[] in bytes */
153399  int iOff;                       /* Current offset within aInput[] */
153400  int iToken;                     /* Index of next token to be returned */
153401  char *zToken;                   /* storage for current token */
153402  int nAlloc;                     /* space allocated at zToken */
153403};
153404
153405
153406/*
153407** Destroy a tokenizer allocated by unicodeCreate().
153408*/
153409static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
153410  if( pTokenizer ){
153411    unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
153412    sqlite3_free(p->aiException);
153413    sqlite3_free(p);
153414  }
153415  return SQLITE_OK;
153416}
153417
153418/*
153419** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
153420** statement has specified that the tokenizer for this table shall consider
153421** all characters in string zIn/nIn to be separators (if bAlnum==0) or
153422** token characters (if bAlnum==1).
153423**
153424** For each codepoint in the zIn/nIn string, this function checks if the
153425** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
153426** If so, no action is taken. Otherwise, the codepoint is added to the
153427** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
153428** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
153429** codepoints in the aiException[] array.
153430**
153431** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
153432** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
153433** It is not possible to change the behavior of the tokenizer with respect
153434** to these codepoints.
153435*/
153436static int unicodeAddExceptions(
153437  unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
153438  int bAlnum,                     /* Replace Isalnum() return value with this */
153439  const char *zIn,                /* Array of characters to make exceptions */
153440  int nIn                         /* Length of z in bytes */
153441){
153442  const unsigned char *z = (const unsigned char *)zIn;
153443  const unsigned char *zTerm = &z[nIn];
153444  int iCode;
153445  int nEntry = 0;
153446
153447  assert( bAlnum==0 || bAlnum==1 );
153448
153449  while( z<zTerm ){
153450    READ_UTF8(z, zTerm, iCode);
153451    assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
153452    if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
153453     && sqlite3FtsUnicodeIsdiacritic(iCode)==0
153454    ){
153455      nEntry++;
153456    }
153457  }
153458
153459  if( nEntry ){
153460    int *aNew;                    /* New aiException[] array */
153461    int nNew;                     /* Number of valid entries in array aNew[] */
153462
153463    aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
153464    if( aNew==0 ) return SQLITE_NOMEM;
153465    nNew = p->nException;
153466
153467    z = (const unsigned char *)zIn;
153468    while( z<zTerm ){
153469      READ_UTF8(z, zTerm, iCode);
153470      if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
153471       && sqlite3FtsUnicodeIsdiacritic(iCode)==0
153472      ){
153473        int i, j;
153474        for(i=0; i<nNew && aNew[i]<iCode; i++);
153475        for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
153476        aNew[i] = iCode;
153477        nNew++;
153478      }
153479    }
153480    p->aiException = aNew;
153481    p->nException = nNew;
153482  }
153483
153484  return SQLITE_OK;
153485}
153486
153487/*
153488** Return true if the p->aiException[] array contains the value iCode.
153489*/
153490static int unicodeIsException(unicode_tokenizer *p, int iCode){
153491  if( p->nException>0 ){
153492    int *a = p->aiException;
153493    int iLo = 0;
153494    int iHi = p->nException-1;
153495
153496    while( iHi>=iLo ){
153497      int iTest = (iHi + iLo) / 2;
153498      if( iCode==a[iTest] ){
153499        return 1;
153500      }else if( iCode>a[iTest] ){
153501        iLo = iTest+1;
153502      }else{
153503        iHi = iTest-1;
153504      }
153505    }
153506  }
153507
153508  return 0;
153509}
153510
153511/*
153512** Return true if, for the purposes of tokenization, codepoint iCode is
153513** considered a token character (not a separator).
153514*/
153515static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
153516  assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
153517  return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
153518}
153519
153520/*
153521** Create a new tokenizer instance.
153522*/
153523static int unicodeCreate(
153524  int nArg,                       /* Size of array argv[] */
153525  const char * const *azArg,      /* Tokenizer creation arguments */
153526  sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
153527){
153528  unicode_tokenizer *pNew;        /* New tokenizer object */
153529  int i;
153530  int rc = SQLITE_OK;
153531
153532  pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
153533  if( pNew==NULL ) return SQLITE_NOMEM;
153534  memset(pNew, 0, sizeof(unicode_tokenizer));
153535  pNew->bRemoveDiacritic = 1;
153536
153537  for(i=0; rc==SQLITE_OK && i<nArg; i++){
153538    const char *z = azArg[i];
153539    int n = (int)strlen(z);
153540
153541    if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
153542      pNew->bRemoveDiacritic = 1;
153543    }
153544    else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
153545      pNew->bRemoveDiacritic = 0;
153546    }
153547    else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
153548      rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
153549    }
153550    else if( n>=11 && memcmp("separators=", z, 11)==0 ){
153551      rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
153552    }
153553    else{
153554      /* Unrecognized argument */
153555      rc  = SQLITE_ERROR;
153556    }
153557  }
153558
153559  if( rc!=SQLITE_OK ){
153560    unicodeDestroy((sqlite3_tokenizer *)pNew);
153561    pNew = 0;
153562  }
153563  *pp = (sqlite3_tokenizer *)pNew;
153564  return rc;
153565}
153566
153567/*
153568** Prepare to begin tokenizing a particular string.  The input
153569** string to be tokenized is pInput[0..nBytes-1].  A cursor
153570** used to incrementally tokenize this string is returned in
153571** *ppCursor.
153572*/
153573static int unicodeOpen(
153574  sqlite3_tokenizer *p,           /* The tokenizer */
153575  const char *aInput,             /* Input string */
153576  int nInput,                     /* Size of string aInput in bytes */
153577  sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
153578){
153579  unicode_cursor *pCsr;
153580
153581  pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
153582  if( pCsr==0 ){
153583    return SQLITE_NOMEM;
153584  }
153585  memset(pCsr, 0, sizeof(unicode_cursor));
153586
153587  pCsr->aInput = (const unsigned char *)aInput;
153588  if( aInput==0 ){
153589    pCsr->nInput = 0;
153590  }else if( nInput<0 ){
153591    pCsr->nInput = (int)strlen(aInput);
153592  }else{
153593    pCsr->nInput = nInput;
153594  }
153595
153596  *pp = &pCsr->base;
153597  UNUSED_PARAMETER(p);
153598  return SQLITE_OK;
153599}
153600
153601/*
153602** Close a tokenization cursor previously opened by a call to
153603** simpleOpen() above.
153604*/
153605static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
153606  unicode_cursor *pCsr = (unicode_cursor *) pCursor;
153607  sqlite3_free(pCsr->zToken);
153608  sqlite3_free(pCsr);
153609  return SQLITE_OK;
153610}
153611
153612/*
153613** Extract the next token from a tokenization cursor.  The cursor must
153614** have been opened by a prior call to simpleOpen().
153615*/
153616static int unicodeNext(
153617  sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
153618  const char **paToken,           /* OUT: Token text */
153619  int *pnToken,                   /* OUT: Number of bytes at *paToken */
153620  int *piStart,                   /* OUT: Starting offset of token */
153621  int *piEnd,                     /* OUT: Ending offset of token */
153622  int *piPos                      /* OUT: Position integer of token */
153623){
153624  unicode_cursor *pCsr = (unicode_cursor *)pC;
153625  unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
153626  int iCode = 0;
153627  char *zOut;
153628  const unsigned char *z = &pCsr->aInput[pCsr->iOff];
153629  const unsigned char *zStart = z;
153630  const unsigned char *zEnd;
153631  const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
153632
153633  /* Scan past any delimiter characters before the start of the next token.
153634  ** Return SQLITE_DONE early if this takes us all the way to the end of
153635  ** the input.  */
153636  while( z<zTerm ){
153637    READ_UTF8(z, zTerm, iCode);
153638    if( unicodeIsAlnum(p, iCode) ) break;
153639    zStart = z;
153640  }
153641  if( zStart>=zTerm ) return SQLITE_DONE;
153642
153643  zOut = pCsr->zToken;
153644  do {
153645    int iOut;
153646
153647    /* Grow the output buffer if required. */
153648    if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
153649      char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
153650      if( !zNew ) return SQLITE_NOMEM;
153651      zOut = &zNew[zOut - pCsr->zToken];
153652      pCsr->zToken = zNew;
153653      pCsr->nAlloc += 64;
153654    }
153655
153656    /* Write the folded case of the last character read to the output */
153657    zEnd = z;
153658    iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
153659    if( iOut ){
153660      WRITE_UTF8(zOut, iOut);
153661    }
153662
153663    /* If the cursor is not at EOF, read the next character */
153664    if( z>=zTerm ) break;
153665    READ_UTF8(z, zTerm, iCode);
153666  }while( unicodeIsAlnum(p, iCode)
153667       || sqlite3FtsUnicodeIsdiacritic(iCode)
153668  );
153669
153670  /* Set the output variables and return. */
153671  pCsr->iOff = (int)(z - pCsr->aInput);
153672  *paToken = pCsr->zToken;
153673  *pnToken = (int)(zOut - pCsr->zToken);
153674  *piStart = (int)(zStart - pCsr->aInput);
153675  *piEnd = (int)(zEnd - pCsr->aInput);
153676  *piPos = pCsr->iToken++;
153677  return SQLITE_OK;
153678}
153679
153680/*
153681** Set *ppModule to a pointer to the sqlite3_tokenizer_module
153682** structure for the unicode tokenizer.
153683*/
153684SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
153685  static const sqlite3_tokenizer_module module = {
153686    0,
153687    unicodeCreate,
153688    unicodeDestroy,
153689    unicodeOpen,
153690    unicodeClose,
153691    unicodeNext,
153692    0,
153693  };
153694  *ppModule = &module;
153695}
153696
153697#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
153698#endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
153699
153700/************** End of fts3_unicode.c ****************************************/
153701/************** Begin file fts3_unicode2.c ***********************************/
153702/*
153703** 2012 May 25
153704**
153705** The author disclaims copyright to this source code.  In place of
153706** a legal notice, here is a blessing:
153707**
153708**    May you do good and not evil.
153709**    May you find forgiveness for yourself and forgive others.
153710**    May you share freely, never taking more than you give.
153711**
153712******************************************************************************
153713*/
153714
153715/*
153716** DO NOT EDIT THIS MACHINE GENERATED FILE.
153717*/
153718
153719#ifndef SQLITE_DISABLE_FTS3_UNICODE
153720#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
153721
153722/* #include <assert.h> */
153723
153724/*
153725** Return true if the argument corresponds to a unicode codepoint
153726** classified as either a letter or a number. Otherwise false.
153727**
153728** The results are undefined if the value passed to this function
153729** is less than zero.
153730*/
153731SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
153732  /* Each unsigned integer in the following array corresponds to a contiguous
153733  ** range of unicode codepoints that are not either letters or numbers (i.e.
153734  ** codepoints for which this function should return 0).
153735  **
153736  ** The most significant 22 bits in each 32-bit value contain the first
153737  ** codepoint in the range. The least significant 10 bits are used to store
153738  ** the size of the range (always at least 1). In other words, the value
153739  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
153740  ** C. It is not possible to represent a range larger than 1023 codepoints
153741  ** using this format.
153742  */
153743  static const unsigned int aEntry[] = {
153744    0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
153745    0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
153746    0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
153747    0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
153748    0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
153749    0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
153750    0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
153751    0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
153752    0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
153753    0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
153754    0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
153755    0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
153756    0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
153757    0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
153758    0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
153759    0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
153760    0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
153761    0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
153762    0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
153763    0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
153764    0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
153765    0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
153766    0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
153767    0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
153768    0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
153769    0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
153770    0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
153771    0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
153772    0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
153773    0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
153774    0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
153775    0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
153776    0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
153777    0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
153778    0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
153779    0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
153780    0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
153781    0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
153782    0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
153783    0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
153784    0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
153785    0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
153786    0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
153787    0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
153788    0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
153789    0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
153790    0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
153791    0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
153792    0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
153793    0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
153794    0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
153795    0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
153796    0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
153797    0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
153798    0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
153799    0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
153800    0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
153801    0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
153802    0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
153803    0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
153804    0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
153805    0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
153806    0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
153807    0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
153808    0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
153809    0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
153810    0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
153811    0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
153812    0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
153813    0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
153814    0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
153815    0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
153816    0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
153817    0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
153818    0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
153819    0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
153820    0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
153821    0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
153822    0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
153823    0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
153824    0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
153825    0x380400F0,
153826  };
153827  static const unsigned int aAscii[4] = {
153828    0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
153829  };
153830
153831  if( c<128 ){
153832    return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
153833  }else if( c<(1<<22) ){
153834    unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
153835    int iRes = 0;
153836    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
153837    int iLo = 0;
153838    while( iHi>=iLo ){
153839      int iTest = (iHi + iLo) / 2;
153840      if( key >= aEntry[iTest] ){
153841        iRes = iTest;
153842        iLo = iTest+1;
153843      }else{
153844        iHi = iTest-1;
153845      }
153846    }
153847    assert( aEntry[0]<key );
153848    assert( key>=aEntry[iRes] );
153849    return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
153850  }
153851  return 1;
153852}
153853
153854
153855/*
153856** If the argument is a codepoint corresponding to a lowercase letter
153857** in the ASCII range with a diacritic added, return the codepoint
153858** of the ASCII letter only. For example, if passed 235 - "LATIN
153859** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
153860** E"). The resuls of passing a codepoint that corresponds to an
153861** uppercase letter are undefined.
153862*/
153863static int remove_diacritic(int c){
153864  unsigned short aDia[] = {
153865        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
153866     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
153867     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
153868     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
153869     3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
153870     3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
153871     4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
153872     6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
153873    61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
153874    61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
153875    62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
153876    62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
153877    62924, 63050, 63082, 63274, 63390,
153878  };
153879  char aChar[] = {
153880    '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
153881    'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
153882    's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
153883    'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
153884    'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
153885    '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
153886    'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
153887    'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
153888    'e',  'i',  'o',  'u',  'y',
153889  };
153890
153891  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
153892  int iRes = 0;
153893  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
153894  int iLo = 0;
153895  while( iHi>=iLo ){
153896    int iTest = (iHi + iLo) / 2;
153897    if( key >= aDia[iTest] ){
153898      iRes = iTest;
153899      iLo = iTest+1;
153900    }else{
153901      iHi = iTest-1;
153902    }
153903  }
153904  assert( key>=aDia[iRes] );
153905  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
153906}
153907
153908
153909/*
153910** Return true if the argument interpreted as a unicode codepoint
153911** is a diacritical modifier character.
153912*/
153913SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
153914  unsigned int mask0 = 0x08029FDF;
153915  unsigned int mask1 = 0x000361F8;
153916  if( c<768 || c>817 ) return 0;
153917  return (c < 768+32) ?
153918      (mask0 & (1 << (c-768))) :
153919      (mask1 & (1 << (c-768-32)));
153920}
153921
153922
153923/*
153924** Interpret the argument as a unicode codepoint. If the codepoint
153925** is an upper case character that has a lower case equivalent,
153926** return the codepoint corresponding to the lower case version.
153927** Otherwise, return a copy of the argument.
153928**
153929** The results are undefined if the value passed to this function
153930** is less than zero.
153931*/
153932SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
153933  /* Each entry in the following array defines a rule for folding a range
153934  ** of codepoints to lower case. The rule applies to a range of nRange
153935  ** codepoints starting at codepoint iCode.
153936  **
153937  ** If the least significant bit in flags is clear, then the rule applies
153938  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
153939  ** need to be folded). Or, if it is set, then the rule only applies to
153940  ** every second codepoint in the range, starting with codepoint C.
153941  **
153942  ** The 7 most significant bits in flags are an index into the aiOff[]
153943  ** array. If a specific codepoint C does require folding, then its lower
153944  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
153945  **
153946  ** The contents of this array are generated by parsing the CaseFolding.txt
153947  ** file distributed as part of the "Unicode Character Database". See
153948  ** http://www.unicode.org for details.
153949  */
153950  static const struct TableEntry {
153951    unsigned short iCode;
153952    unsigned char flags;
153953    unsigned char nRange;
153954  } aEntry[] = {
153955    {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
153956    {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
153957    {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
153958    {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
153959    {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
153960    {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
153961    {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
153962    {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
153963    {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
153964    {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
153965    {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
153966    {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
153967    {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
153968    {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
153969    {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
153970    {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
153971    {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
153972    {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
153973    {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
153974    {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
153975    {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
153976    {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
153977    {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
153978    {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
153979    {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
153980    {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
153981    {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
153982    {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
153983    {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
153984    {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
153985    {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
153986    {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
153987    {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
153988    {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
153989    {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
153990    {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
153991    {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
153992    {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
153993    {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
153994    {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
153995    {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
153996    {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
153997    {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
153998    {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
153999    {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
154000    {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
154001    {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
154002    {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
154003    {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
154004    {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
154005    {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
154006    {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
154007    {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
154008    {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
154009    {65313, 14, 26},
154010  };
154011  static const unsigned short aiOff[] = {
154012   1,     2,     8,     15,    16,    26,    28,    32,
154013   37,    38,    40,    48,    63,    64,    69,    71,
154014   79,    80,    116,   202,   203,   205,   206,   207,
154015   209,   210,   211,   213,   214,   217,   218,   219,
154016   775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
154017   54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
154018   57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
154019   65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
154020   65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
154021   65514, 65521, 65527, 65528, 65529,
154022  };
154023
154024  int ret = c;
154025
154026  assert( c>=0 );
154027  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
154028
154029  if( c<128 ){
154030    if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
154031  }else if( c<65536 ){
154032    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
154033    int iLo = 0;
154034    int iRes = -1;
154035
154036    while( iHi>=iLo ){
154037      int iTest = (iHi + iLo) / 2;
154038      int cmp = (c - aEntry[iTest].iCode);
154039      if( cmp>=0 ){
154040        iRes = iTest;
154041        iLo = iTest+1;
154042      }else{
154043        iHi = iTest-1;
154044      }
154045    }
154046    assert( iRes<0 || c>=aEntry[iRes].iCode );
154047
154048    if( iRes>=0 ){
154049      const struct TableEntry *p = &aEntry[iRes];
154050      if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
154051        ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
154052        assert( ret>0 );
154053      }
154054    }
154055
154056    if( bRemoveDiacritic ) ret = remove_diacritic(ret);
154057  }
154058
154059  else if( c>=66560 && c<66600 ){
154060    ret = c + 40;
154061  }
154062
154063  return ret;
154064}
154065#endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
154066#endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
154067
154068/************** End of fts3_unicode2.c ***************************************/
154069/************** Begin file rtree.c *******************************************/
154070/*
154071** 2001 September 15
154072**
154073** The author disclaims copyright to this source code.  In place of
154074** a legal notice, here is a blessing:
154075**
154076**    May you do good and not evil.
154077**    May you find forgiveness for yourself and forgive others.
154078**    May you share freely, never taking more than you give.
154079**
154080*************************************************************************
154081** This file contains code for implementations of the r-tree and r*-tree
154082** algorithms packaged as an SQLite virtual table module.
154083*/
154084
154085/*
154086** Database Format of R-Tree Tables
154087** --------------------------------
154088**
154089** The data structure for a single virtual r-tree table is stored in three
154090** native SQLite tables declared as follows. In each case, the '%' character
154091** in the table name is replaced with the user-supplied name of the r-tree
154092** table.
154093**
154094**   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
154095**   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
154096**   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
154097**
154098** The data for each node of the r-tree structure is stored in the %_node
154099** table. For each node that is not the root node of the r-tree, there is
154100** an entry in the %_parent table associating the node with its parent.
154101** And for each row of data in the table, there is an entry in the %_rowid
154102** table that maps from the entries rowid to the id of the node that it
154103** is stored on.
154104**
154105** The root node of an r-tree always exists, even if the r-tree table is
154106** empty. The nodeno of the root node is always 1. All other nodes in the
154107** table must be the same size as the root node. The content of each node
154108** is formatted as follows:
154109**
154110**   1. If the node is the root node (node 1), then the first 2 bytes
154111**      of the node contain the tree depth as a big-endian integer.
154112**      For non-root nodes, the first 2 bytes are left unused.
154113**
154114**   2. The next 2 bytes contain the number of entries currently
154115**      stored in the node.
154116**
154117**   3. The remainder of the node contains the node entries. Each entry
154118**      consists of a single 8-byte integer followed by an even number
154119**      of 4-byte coordinates. For leaf nodes the integer is the rowid
154120**      of a record. For internal nodes it is the node number of a
154121**      child page.
154122*/
154123
154124#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
154125
154126#ifndef SQLITE_CORE
154127/*   #include "sqlite3ext.h" */
154128  SQLITE_EXTENSION_INIT1
154129#else
154130/*   #include "sqlite3.h" */
154131#endif
154132
154133/* #include <string.h> */
154134/* #include <assert.h> */
154135/* #include <stdio.h> */
154136
154137#ifndef SQLITE_AMALGAMATION
154138#include "sqlite3rtree.h"
154139typedef sqlite3_int64 i64;
154140typedef unsigned char u8;
154141typedef unsigned short u16;
154142typedef unsigned int u32;
154143#endif
154144
154145/*  The following macro is used to suppress compiler warnings.
154146*/
154147#ifndef UNUSED_PARAMETER
154148# define UNUSED_PARAMETER(x) (void)(x)
154149#endif
154150
154151typedef struct Rtree Rtree;
154152typedef struct RtreeCursor RtreeCursor;
154153typedef struct RtreeNode RtreeNode;
154154typedef struct RtreeCell RtreeCell;
154155typedef struct RtreeConstraint RtreeConstraint;
154156typedef struct RtreeMatchArg RtreeMatchArg;
154157typedef struct RtreeGeomCallback RtreeGeomCallback;
154158typedef union RtreeCoord RtreeCoord;
154159typedef struct RtreeSearchPoint RtreeSearchPoint;
154160
154161/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
154162#define RTREE_MAX_DIMENSIONS 5
154163
154164/* Size of hash table Rtree.aHash. This hash table is not expected to
154165** ever contain very many entries, so a fixed number of buckets is
154166** used.
154167*/
154168#define HASHSIZE 97
154169
154170/* The xBestIndex method of this virtual table requires an estimate of
154171** the number of rows in the virtual table to calculate the costs of
154172** various strategies. If possible, this estimate is loaded from the
154173** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
154174** Otherwise, if no sqlite_stat1 entry is available, use
154175** RTREE_DEFAULT_ROWEST.
154176*/
154177#define RTREE_DEFAULT_ROWEST 1048576
154178#define RTREE_MIN_ROWEST         100
154179
154180/*
154181** An rtree virtual-table object.
154182*/
154183struct Rtree {
154184  sqlite3_vtab base;          /* Base class.  Must be first */
154185  sqlite3 *db;                /* Host database connection */
154186  int iNodeSize;              /* Size in bytes of each node in the node table */
154187  u8 nDim;                    /* Number of dimensions */
154188  u8 eCoordType;              /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
154189  u8 nBytesPerCell;           /* Bytes consumed per cell */
154190  int iDepth;                 /* Current depth of the r-tree structure */
154191  char *zDb;                  /* Name of database containing r-tree table */
154192  char *zName;                /* Name of r-tree table */
154193  int nBusy;                  /* Current number of users of this structure */
154194  i64 nRowEst;                /* Estimated number of rows in this table */
154195
154196  /* List of nodes removed during a CondenseTree operation. List is
154197  ** linked together via the pointer normally used for hash chains -
154198  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
154199  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
154200  */
154201  RtreeNode *pDeleted;
154202  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
154203
154204  /* Statements to read/write/delete a record from xxx_node */
154205  sqlite3_stmt *pReadNode;
154206  sqlite3_stmt *pWriteNode;
154207  sqlite3_stmt *pDeleteNode;
154208
154209  /* Statements to read/write/delete a record from xxx_rowid */
154210  sqlite3_stmt *pReadRowid;
154211  sqlite3_stmt *pWriteRowid;
154212  sqlite3_stmt *pDeleteRowid;
154213
154214  /* Statements to read/write/delete a record from xxx_parent */
154215  sqlite3_stmt *pReadParent;
154216  sqlite3_stmt *pWriteParent;
154217  sqlite3_stmt *pDeleteParent;
154218
154219  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
154220};
154221
154222/* Possible values for Rtree.eCoordType: */
154223#define RTREE_COORD_REAL32 0
154224#define RTREE_COORD_INT32  1
154225
154226/*
154227** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
154228** only deal with integer coordinates.  No floating point operations
154229** will be done.
154230*/
154231#ifdef SQLITE_RTREE_INT_ONLY
154232  typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
154233  typedef int RtreeValue;                  /* Low accuracy coordinate */
154234# define RTREE_ZERO 0
154235#else
154236  typedef double RtreeDValue;              /* High accuracy coordinate */
154237  typedef float RtreeValue;                /* Low accuracy coordinate */
154238# define RTREE_ZERO 0.0
154239#endif
154240
154241/*
154242** When doing a search of an r-tree, instances of the following structure
154243** record intermediate results from the tree walk.
154244**
154245** The id is always a node-id.  For iLevel>=1 the id is the node-id of
154246** the node that the RtreeSearchPoint represents.  When iLevel==0, however,
154247** the id is of the parent node and the cell that RtreeSearchPoint
154248** represents is the iCell-th entry in the parent node.
154249*/
154250struct RtreeSearchPoint {
154251  RtreeDValue rScore;    /* The score for this node.  Smallest goes first. */
154252  sqlite3_int64 id;      /* Node ID */
154253  u8 iLevel;             /* 0=entries.  1=leaf node.  2+ for higher */
154254  u8 eWithin;            /* PARTLY_WITHIN or FULLY_WITHIN */
154255  u8 iCell;              /* Cell index within the node */
154256};
154257
154258/*
154259** The minimum number of cells allowed for a node is a third of the
154260** maximum. In Gutman's notation:
154261**
154262**     m = M/3
154263**
154264** If an R*-tree "Reinsert" operation is required, the same number of
154265** cells are removed from the overfull node and reinserted into the tree.
154266*/
154267#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
154268#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
154269#define RTREE_MAXCELLS 51
154270
154271/*
154272** The smallest possible node-size is (512-64)==448 bytes. And the largest
154273** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
154274** Therefore all non-root nodes must contain at least 3 entries. Since
154275** 2^40 is greater than 2^64, an r-tree structure always has a depth of
154276** 40 or less.
154277*/
154278#define RTREE_MAX_DEPTH 40
154279
154280
154281/*
154282** Number of entries in the cursor RtreeNode cache.  The first entry is
154283** used to cache the RtreeNode for RtreeCursor.sPoint.  The remaining
154284** entries cache the RtreeNode for the first elements of the priority queue.
154285*/
154286#define RTREE_CACHE_SZ  5
154287
154288/*
154289** An rtree cursor object.
154290*/
154291struct RtreeCursor {
154292  sqlite3_vtab_cursor base;         /* Base class.  Must be first */
154293  u8 atEOF;                         /* True if at end of search */
154294  u8 bPoint;                        /* True if sPoint is valid */
154295  int iStrategy;                    /* Copy of idxNum search parameter */
154296  int nConstraint;                  /* Number of entries in aConstraint */
154297  RtreeConstraint *aConstraint;     /* Search constraints. */
154298  int nPointAlloc;                  /* Number of slots allocated for aPoint[] */
154299  int nPoint;                       /* Number of slots used in aPoint[] */
154300  int mxLevel;                      /* iLevel value for root of the tree */
154301  RtreeSearchPoint *aPoint;         /* Priority queue for search points */
154302  RtreeSearchPoint sPoint;          /* Cached next search point */
154303  RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
154304  u32 anQueue[RTREE_MAX_DEPTH+1];   /* Number of queued entries by iLevel */
154305};
154306
154307/* Return the Rtree of a RtreeCursor */
154308#define RTREE_OF_CURSOR(X)   ((Rtree*)((X)->base.pVtab))
154309
154310/*
154311** A coordinate can be either a floating point number or a integer.  All
154312** coordinates within a single R-Tree are always of the same time.
154313*/
154314union RtreeCoord {
154315  RtreeValue f;      /* Floating point value */
154316  int i;             /* Integer value */
154317  u32 u;             /* Unsigned for byte-order conversions */
154318};
154319
154320/*
154321** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
154322** formatted as a RtreeDValue (double or int64). This macro assumes that local
154323** variable pRtree points to the Rtree structure associated with the
154324** RtreeCoord.
154325*/
154326#ifdef SQLITE_RTREE_INT_ONLY
154327# define DCOORD(coord) ((RtreeDValue)coord.i)
154328#else
154329# define DCOORD(coord) (                           \
154330    (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
154331      ((double)coord.f) :                           \
154332      ((double)coord.i)                             \
154333  )
154334#endif
154335
154336/*
154337** A search constraint.
154338*/
154339struct RtreeConstraint {
154340  int iCoord;                     /* Index of constrained coordinate */
154341  int op;                         /* Constraining operation */
154342  union {
154343    RtreeDValue rValue;             /* Constraint value. */
154344    int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
154345    int (*xQueryFunc)(sqlite3_rtree_query_info*);
154346  } u;
154347  sqlite3_rtree_query_info *pInfo;  /* xGeom and xQueryFunc argument */
154348};
154349
154350/* Possible values for RtreeConstraint.op */
154351#define RTREE_EQ    0x41  /* A */
154352#define RTREE_LE    0x42  /* B */
154353#define RTREE_LT    0x43  /* C */
154354#define RTREE_GE    0x44  /* D */
154355#define RTREE_GT    0x45  /* E */
154356#define RTREE_MATCH 0x46  /* F: Old-style sqlite3_rtree_geometry_callback() */
154357#define RTREE_QUERY 0x47  /* G: New-style sqlite3_rtree_query_callback() */
154358
154359
154360/*
154361** An rtree structure node.
154362*/
154363struct RtreeNode {
154364  RtreeNode *pParent;         /* Parent node */
154365  i64 iNode;                  /* The node number */
154366  int nRef;                   /* Number of references to this node */
154367  int isDirty;                /* True if the node needs to be written to disk */
154368  u8 *zData;                  /* Content of the node, as should be on disk */
154369  RtreeNode *pNext;           /* Next node in this hash collision chain */
154370};
154371
154372/* Return the number of cells in a node  */
154373#define NCELL(pNode) readInt16(&(pNode)->zData[2])
154374
154375/*
154376** A single cell from a node, deserialized
154377*/
154378struct RtreeCell {
154379  i64 iRowid;                                 /* Node or entry ID */
154380  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];  /* Bounding box coordinates */
154381};
154382
154383
154384/*
154385** This object becomes the sqlite3_user_data() for the SQL functions
154386** that are created by sqlite3_rtree_geometry_callback() and
154387** sqlite3_rtree_query_callback() and which appear on the right of MATCH
154388** operators in order to constrain a search.
154389**
154390** xGeom and xQueryFunc are the callback functions.  Exactly one of
154391** xGeom and xQueryFunc fields is non-NULL, depending on whether the
154392** SQL function was created using sqlite3_rtree_geometry_callback() or
154393** sqlite3_rtree_query_callback().
154394**
154395** This object is deleted automatically by the destructor mechanism in
154396** sqlite3_create_function_v2().
154397*/
154398struct RtreeGeomCallback {
154399  int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
154400  int (*xQueryFunc)(sqlite3_rtree_query_info*);
154401  void (*xDestructor)(void*);
154402  void *pContext;
154403};
154404
154405
154406/*
154407** Value for the first field of every RtreeMatchArg object. The MATCH
154408** operator tests that the first field of a blob operand matches this
154409** value to avoid operating on invalid blobs (which could cause a segfault).
154410*/
154411#define RTREE_GEOMETRY_MAGIC 0x891245AB
154412
154413/*
154414** An instance of this structure (in the form of a BLOB) is returned by
154415** the SQL functions that sqlite3_rtree_geometry_callback() and
154416** sqlite3_rtree_query_callback() create, and is read as the right-hand
154417** operand to the MATCH operator of an R-Tree.
154418*/
154419struct RtreeMatchArg {
154420  u32 magic;                  /* Always RTREE_GEOMETRY_MAGIC */
154421  RtreeGeomCallback cb;       /* Info about the callback functions */
154422  int nParam;                 /* Number of parameters to the SQL function */
154423  sqlite3_value **apSqlParam; /* Original SQL parameter values */
154424  RtreeDValue aParam[1];      /* Values for parameters to the SQL function */
154425};
154426
154427#ifndef MAX
154428# define MAX(x,y) ((x) < (y) ? (y) : (x))
154429#endif
154430#ifndef MIN
154431# define MIN(x,y) ((x) > (y) ? (y) : (x))
154432#endif
154433
154434/*
154435** Functions to deserialize a 16 bit integer, 32 bit real number and
154436** 64 bit integer. The deserialized value is returned.
154437*/
154438static int readInt16(u8 *p){
154439  return (p[0]<<8) + p[1];
154440}
154441static void readCoord(u8 *p, RtreeCoord *pCoord){
154442  pCoord->u = (
154443    (((u32)p[0]) << 24) +
154444    (((u32)p[1]) << 16) +
154445    (((u32)p[2]) <<  8) +
154446    (((u32)p[3]) <<  0)
154447  );
154448}
154449static i64 readInt64(u8 *p){
154450  return (
154451    (((i64)p[0]) << 56) +
154452    (((i64)p[1]) << 48) +
154453    (((i64)p[2]) << 40) +
154454    (((i64)p[3]) << 32) +
154455    (((i64)p[4]) << 24) +
154456    (((i64)p[5]) << 16) +
154457    (((i64)p[6]) <<  8) +
154458    (((i64)p[7]) <<  0)
154459  );
154460}
154461
154462/*
154463** Functions to serialize a 16 bit integer, 32 bit real number and
154464** 64 bit integer. The value returned is the number of bytes written
154465** to the argument buffer (always 2, 4 and 8 respectively).
154466*/
154467static int writeInt16(u8 *p, int i){
154468  p[0] = (i>> 8)&0xFF;
154469  p[1] = (i>> 0)&0xFF;
154470  return 2;
154471}
154472static int writeCoord(u8 *p, RtreeCoord *pCoord){
154473  u32 i;
154474  assert( sizeof(RtreeCoord)==4 );
154475  assert( sizeof(u32)==4 );
154476  i = pCoord->u;
154477  p[0] = (i>>24)&0xFF;
154478  p[1] = (i>>16)&0xFF;
154479  p[2] = (i>> 8)&0xFF;
154480  p[3] = (i>> 0)&0xFF;
154481  return 4;
154482}
154483static int writeInt64(u8 *p, i64 i){
154484  p[0] = (i>>56)&0xFF;
154485  p[1] = (i>>48)&0xFF;
154486  p[2] = (i>>40)&0xFF;
154487  p[3] = (i>>32)&0xFF;
154488  p[4] = (i>>24)&0xFF;
154489  p[5] = (i>>16)&0xFF;
154490  p[6] = (i>> 8)&0xFF;
154491  p[7] = (i>> 0)&0xFF;
154492  return 8;
154493}
154494
154495/*
154496** Increment the reference count of node p.
154497*/
154498static void nodeReference(RtreeNode *p){
154499  if( p ){
154500    p->nRef++;
154501  }
154502}
154503
154504/*
154505** Clear the content of node p (set all bytes to 0x00).
154506*/
154507static void nodeZero(Rtree *pRtree, RtreeNode *p){
154508  memset(&p->zData[2], 0, pRtree->iNodeSize-2);
154509  p->isDirty = 1;
154510}
154511
154512/*
154513** Given a node number iNode, return the corresponding key to use
154514** in the Rtree.aHash table.
154515*/
154516static int nodeHash(i64 iNode){
154517  return iNode % HASHSIZE;
154518}
154519
154520/*
154521** Search the node hash table for node iNode. If found, return a pointer
154522** to it. Otherwise, return 0.
154523*/
154524static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
154525  RtreeNode *p;
154526  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
154527  return p;
154528}
154529
154530/*
154531** Add node pNode to the node hash table.
154532*/
154533static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
154534  int iHash;
154535  assert( pNode->pNext==0 );
154536  iHash = nodeHash(pNode->iNode);
154537  pNode->pNext = pRtree->aHash[iHash];
154538  pRtree->aHash[iHash] = pNode;
154539}
154540
154541/*
154542** Remove node pNode from the node hash table.
154543*/
154544static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
154545  RtreeNode **pp;
154546  if( pNode->iNode!=0 ){
154547    pp = &pRtree->aHash[nodeHash(pNode->iNode)];
154548    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
154549    *pp = pNode->pNext;
154550    pNode->pNext = 0;
154551  }
154552}
154553
154554/*
154555** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
154556** indicating that node has not yet been assigned a node number. It is
154557** assigned a node number when nodeWrite() is called to write the
154558** node contents out to the database.
154559*/
154560static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
154561  RtreeNode *pNode;
154562  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
154563  if( pNode ){
154564    memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
154565    pNode->zData = (u8 *)&pNode[1];
154566    pNode->nRef = 1;
154567    pNode->pParent = pParent;
154568    pNode->isDirty = 1;
154569    nodeReference(pParent);
154570  }
154571  return pNode;
154572}
154573
154574/*
154575** Obtain a reference to an r-tree node.
154576*/
154577static int nodeAcquire(
154578  Rtree *pRtree,             /* R-tree structure */
154579  i64 iNode,                 /* Node number to load */
154580  RtreeNode *pParent,        /* Either the parent node or NULL */
154581  RtreeNode **ppNode         /* OUT: Acquired node */
154582){
154583  int rc;
154584  int rc2 = SQLITE_OK;
154585  RtreeNode *pNode;
154586
154587  /* Check if the requested node is already in the hash table. If so,
154588  ** increase its reference count and return it.
154589  */
154590  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
154591    assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
154592    if( pParent && !pNode->pParent ){
154593      nodeReference(pParent);
154594      pNode->pParent = pParent;
154595    }
154596    pNode->nRef++;
154597    *ppNode = pNode;
154598    return SQLITE_OK;
154599  }
154600
154601  sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
154602  rc = sqlite3_step(pRtree->pReadNode);
154603  if( rc==SQLITE_ROW ){
154604    const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
154605    if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
154606      pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
154607      if( !pNode ){
154608        rc2 = SQLITE_NOMEM;
154609      }else{
154610        pNode->pParent = pParent;
154611        pNode->zData = (u8 *)&pNode[1];
154612        pNode->nRef = 1;
154613        pNode->iNode = iNode;
154614        pNode->isDirty = 0;
154615        pNode->pNext = 0;
154616        memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
154617        nodeReference(pParent);
154618      }
154619    }
154620  }
154621  rc = sqlite3_reset(pRtree->pReadNode);
154622  if( rc==SQLITE_OK ) rc = rc2;
154623
154624  /* If the root node was just loaded, set pRtree->iDepth to the height
154625  ** of the r-tree structure. A height of zero means all data is stored on
154626  ** the root node. A height of one means the children of the root node
154627  ** are the leaves, and so on. If the depth as specified on the root node
154628  ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
154629  */
154630  if( pNode && iNode==1 ){
154631    pRtree->iDepth = readInt16(pNode->zData);
154632    if( pRtree->iDepth>RTREE_MAX_DEPTH ){
154633      rc = SQLITE_CORRUPT_VTAB;
154634    }
154635  }
154636
154637  /* If no error has occurred so far, check if the "number of entries"
154638  ** field on the node is too large. If so, set the return code to
154639  ** SQLITE_CORRUPT_VTAB.
154640  */
154641  if( pNode && rc==SQLITE_OK ){
154642    if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
154643      rc = SQLITE_CORRUPT_VTAB;
154644    }
154645  }
154646
154647  if( rc==SQLITE_OK ){
154648    if( pNode!=0 ){
154649      nodeHashInsert(pRtree, pNode);
154650    }else{
154651      rc = SQLITE_CORRUPT_VTAB;
154652    }
154653    *ppNode = pNode;
154654  }else{
154655    sqlite3_free(pNode);
154656    *ppNode = 0;
154657  }
154658
154659  return rc;
154660}
154661
154662/*
154663** Overwrite cell iCell of node pNode with the contents of pCell.
154664*/
154665static void nodeOverwriteCell(
154666  Rtree *pRtree,             /* The overall R-Tree */
154667  RtreeNode *pNode,          /* The node into which the cell is to be written */
154668  RtreeCell *pCell,          /* The cell to write */
154669  int iCell                  /* Index into pNode into which pCell is written */
154670){
154671  int ii;
154672  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
154673  p += writeInt64(p, pCell->iRowid);
154674  for(ii=0; ii<(pRtree->nDim*2); ii++){
154675    p += writeCoord(p, &pCell->aCoord[ii]);
154676  }
154677  pNode->isDirty = 1;
154678}
154679
154680/*
154681** Remove the cell with index iCell from node pNode.
154682*/
154683static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
154684  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
154685  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
154686  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
154687  memmove(pDst, pSrc, nByte);
154688  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
154689  pNode->isDirty = 1;
154690}
154691
154692/*
154693** Insert the contents of cell pCell into node pNode. If the insert
154694** is successful, return SQLITE_OK.
154695**
154696** If there is not enough free space in pNode, return SQLITE_FULL.
154697*/
154698static int nodeInsertCell(
154699  Rtree *pRtree,                /* The overall R-Tree */
154700  RtreeNode *pNode,             /* Write new cell into this node */
154701  RtreeCell *pCell              /* The cell to be inserted */
154702){
154703  int nCell;                    /* Current number of cells in pNode */
154704  int nMaxCell;                 /* Maximum number of cells for pNode */
154705
154706  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
154707  nCell = NCELL(pNode);
154708
154709  assert( nCell<=nMaxCell );
154710  if( nCell<nMaxCell ){
154711    nodeOverwriteCell(pRtree, pNode, pCell, nCell);
154712    writeInt16(&pNode->zData[2], nCell+1);
154713    pNode->isDirty = 1;
154714  }
154715
154716  return (nCell==nMaxCell);
154717}
154718
154719/*
154720** If the node is dirty, write it out to the database.
154721*/
154722static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
154723  int rc = SQLITE_OK;
154724  if( pNode->isDirty ){
154725    sqlite3_stmt *p = pRtree->pWriteNode;
154726    if( pNode->iNode ){
154727      sqlite3_bind_int64(p, 1, pNode->iNode);
154728    }else{
154729      sqlite3_bind_null(p, 1);
154730    }
154731    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
154732    sqlite3_step(p);
154733    pNode->isDirty = 0;
154734    rc = sqlite3_reset(p);
154735    if( pNode->iNode==0 && rc==SQLITE_OK ){
154736      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
154737      nodeHashInsert(pRtree, pNode);
154738    }
154739  }
154740  return rc;
154741}
154742
154743/*
154744** Release a reference to a node. If the node is dirty and the reference
154745** count drops to zero, the node data is written to the database.
154746*/
154747static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
154748  int rc = SQLITE_OK;
154749  if( pNode ){
154750    assert( pNode->nRef>0 );
154751    pNode->nRef--;
154752    if( pNode->nRef==0 ){
154753      if( pNode->iNode==1 ){
154754        pRtree->iDepth = -1;
154755      }
154756      if( pNode->pParent ){
154757        rc = nodeRelease(pRtree, pNode->pParent);
154758      }
154759      if( rc==SQLITE_OK ){
154760        rc = nodeWrite(pRtree, pNode);
154761      }
154762      nodeHashDelete(pRtree, pNode);
154763      sqlite3_free(pNode);
154764    }
154765  }
154766  return rc;
154767}
154768
154769/*
154770** Return the 64-bit integer value associated with cell iCell of
154771** node pNode. If pNode is a leaf node, this is a rowid. If it is
154772** an internal node, then the 64-bit integer is a child page number.
154773*/
154774static i64 nodeGetRowid(
154775  Rtree *pRtree,       /* The overall R-Tree */
154776  RtreeNode *pNode,    /* The node from which to extract the ID */
154777  int iCell            /* The cell index from which to extract the ID */
154778){
154779  assert( iCell<NCELL(pNode) );
154780  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
154781}
154782
154783/*
154784** Return coordinate iCoord from cell iCell in node pNode.
154785*/
154786static void nodeGetCoord(
154787  Rtree *pRtree,               /* The overall R-Tree */
154788  RtreeNode *pNode,            /* The node from which to extract a coordinate */
154789  int iCell,                   /* The index of the cell within the node */
154790  int iCoord,                  /* Which coordinate to extract */
154791  RtreeCoord *pCoord           /* OUT: Space to write result to */
154792){
154793  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
154794}
154795
154796/*
154797** Deserialize cell iCell of node pNode. Populate the structure pointed
154798** to by pCell with the results.
154799*/
154800static void nodeGetCell(
154801  Rtree *pRtree,               /* The overall R-Tree */
154802  RtreeNode *pNode,            /* The node containing the cell to be read */
154803  int iCell,                   /* Index of the cell within the node */
154804  RtreeCell *pCell             /* OUT: Write the cell contents here */
154805){
154806  u8 *pData;
154807  RtreeCoord *pCoord;
154808  int ii;
154809  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
154810  pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
154811  pCoord = pCell->aCoord;
154812  for(ii=0; ii<pRtree->nDim*2; ii++){
154813    readCoord(&pData[ii*4], &pCoord[ii]);
154814  }
154815}
154816
154817
154818/* Forward declaration for the function that does the work of
154819** the virtual table module xCreate() and xConnect() methods.
154820*/
154821static int rtreeInit(
154822  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
154823);
154824
154825/*
154826** Rtree virtual table module xCreate method.
154827*/
154828static int rtreeCreate(
154829  sqlite3 *db,
154830  void *pAux,
154831  int argc, const char *const*argv,
154832  sqlite3_vtab **ppVtab,
154833  char **pzErr
154834){
154835  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
154836}
154837
154838/*
154839** Rtree virtual table module xConnect method.
154840*/
154841static int rtreeConnect(
154842  sqlite3 *db,
154843  void *pAux,
154844  int argc, const char *const*argv,
154845  sqlite3_vtab **ppVtab,
154846  char **pzErr
154847){
154848  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
154849}
154850
154851/*
154852** Increment the r-tree reference count.
154853*/
154854static void rtreeReference(Rtree *pRtree){
154855  pRtree->nBusy++;
154856}
154857
154858/*
154859** Decrement the r-tree reference count. When the reference count reaches
154860** zero the structure is deleted.
154861*/
154862static void rtreeRelease(Rtree *pRtree){
154863  pRtree->nBusy--;
154864  if( pRtree->nBusy==0 ){
154865    sqlite3_finalize(pRtree->pReadNode);
154866    sqlite3_finalize(pRtree->pWriteNode);
154867    sqlite3_finalize(pRtree->pDeleteNode);
154868    sqlite3_finalize(pRtree->pReadRowid);
154869    sqlite3_finalize(pRtree->pWriteRowid);
154870    sqlite3_finalize(pRtree->pDeleteRowid);
154871    sqlite3_finalize(pRtree->pReadParent);
154872    sqlite3_finalize(pRtree->pWriteParent);
154873    sqlite3_finalize(pRtree->pDeleteParent);
154874    sqlite3_free(pRtree);
154875  }
154876}
154877
154878/*
154879** Rtree virtual table module xDisconnect method.
154880*/
154881static int rtreeDisconnect(sqlite3_vtab *pVtab){
154882  rtreeRelease((Rtree *)pVtab);
154883  return SQLITE_OK;
154884}
154885
154886/*
154887** Rtree virtual table module xDestroy method.
154888*/
154889static int rtreeDestroy(sqlite3_vtab *pVtab){
154890  Rtree *pRtree = (Rtree *)pVtab;
154891  int rc;
154892  char *zCreate = sqlite3_mprintf(
154893    "DROP TABLE '%q'.'%q_node';"
154894    "DROP TABLE '%q'.'%q_rowid';"
154895    "DROP TABLE '%q'.'%q_parent';",
154896    pRtree->zDb, pRtree->zName,
154897    pRtree->zDb, pRtree->zName,
154898    pRtree->zDb, pRtree->zName
154899  );
154900  if( !zCreate ){
154901    rc = SQLITE_NOMEM;
154902  }else{
154903    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
154904    sqlite3_free(zCreate);
154905  }
154906  if( rc==SQLITE_OK ){
154907    rtreeRelease(pRtree);
154908  }
154909
154910  return rc;
154911}
154912
154913/*
154914** Rtree virtual table module xOpen method.
154915*/
154916static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
154917  int rc = SQLITE_NOMEM;
154918  RtreeCursor *pCsr;
154919
154920  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
154921  if( pCsr ){
154922    memset(pCsr, 0, sizeof(RtreeCursor));
154923    pCsr->base.pVtab = pVTab;
154924    rc = SQLITE_OK;
154925  }
154926  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
154927
154928  return rc;
154929}
154930
154931
154932/*
154933** Free the RtreeCursor.aConstraint[] array and its contents.
154934*/
154935static void freeCursorConstraints(RtreeCursor *pCsr){
154936  if( pCsr->aConstraint ){
154937    int i;                        /* Used to iterate through constraint array */
154938    for(i=0; i<pCsr->nConstraint; i++){
154939      sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
154940      if( pInfo ){
154941        if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
154942        sqlite3_free(pInfo);
154943      }
154944    }
154945    sqlite3_free(pCsr->aConstraint);
154946    pCsr->aConstraint = 0;
154947  }
154948}
154949
154950/*
154951** Rtree virtual table module xClose method.
154952*/
154953static int rtreeClose(sqlite3_vtab_cursor *cur){
154954  Rtree *pRtree = (Rtree *)(cur->pVtab);
154955  int ii;
154956  RtreeCursor *pCsr = (RtreeCursor *)cur;
154957  freeCursorConstraints(pCsr);
154958  sqlite3_free(pCsr->aPoint);
154959  for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
154960  sqlite3_free(pCsr);
154961  return SQLITE_OK;
154962}
154963
154964/*
154965** Rtree virtual table module xEof method.
154966**
154967** Return non-zero if the cursor does not currently point to a valid
154968** record (i.e if the scan has finished), or zero otherwise.
154969*/
154970static int rtreeEof(sqlite3_vtab_cursor *cur){
154971  RtreeCursor *pCsr = (RtreeCursor *)cur;
154972  return pCsr->atEOF;
154973}
154974
154975/*
154976** Convert raw bits from the on-disk RTree record into a coordinate value.
154977** The on-disk format is big-endian and needs to be converted for little-
154978** endian platforms.  The on-disk record stores integer coordinates if
154979** eInt is true and it stores 32-bit floating point records if eInt is
154980** false.  a[] is the four bytes of the on-disk record to be decoded.
154981** Store the results in "r".
154982**
154983** There are three versions of this macro, one each for little-endian and
154984** big-endian processors and a third generic implementation.  The endian-
154985** specific implementations are much faster and are preferred if the
154986** processor endianness is known at compile-time.  The SQLITE_BYTEORDER
154987** macro is part of sqliteInt.h and hence the endian-specific
154988** implementation will only be used if this module is compiled as part
154989** of the amalgamation.
154990*/
154991#if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
154992#define RTREE_DECODE_COORD(eInt, a, r) {                        \
154993    RtreeCoord c;    /* Coordinate decoded */                   \
154994    memcpy(&c.u,a,4);                                           \
154995    c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)|                   \
154996          ((c.u&0xff)<<24)|((c.u&0xff00)<<8);                   \
154997    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
154998}
154999#elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
155000#define RTREE_DECODE_COORD(eInt, a, r) {                        \
155001    RtreeCoord c;    /* Coordinate decoded */                   \
155002    memcpy(&c.u,a,4);                                           \
155003    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
155004}
155005#else
155006#define RTREE_DECODE_COORD(eInt, a, r) {                        \
155007    RtreeCoord c;    /* Coordinate decoded */                   \
155008    c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16)                     \
155009           +((u32)a[2]<<8) + a[3];                              \
155010    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
155011}
155012#endif
155013
155014/*
155015** Check the RTree node or entry given by pCellData and p against the MATCH
155016** constraint pConstraint.
155017*/
155018static int rtreeCallbackConstraint(
155019  RtreeConstraint *pConstraint,  /* The constraint to test */
155020  int eInt,                      /* True if RTree holding integer coordinates */
155021  u8 *pCellData,                 /* Raw cell content */
155022  RtreeSearchPoint *pSearch,     /* Container of this cell */
155023  sqlite3_rtree_dbl *prScore,    /* OUT: score for the cell */
155024  int *peWithin                  /* OUT: visibility of the cell */
155025){
155026  int i;                                                /* Loop counter */
155027  sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
155028  int nCoord = pInfo->nCoord;                           /* No. of coordinates */
155029  int rc;                                             /* Callback return code */
155030  sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2];   /* Decoded coordinates */
155031
155032  assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
155033  assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
155034
155035  if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
155036    pInfo->iRowid = readInt64(pCellData);
155037  }
155038  pCellData += 8;
155039  for(i=0; i<nCoord; i++, pCellData += 4){
155040    RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
155041  }
155042  if( pConstraint->op==RTREE_MATCH ){
155043    rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
155044                              nCoord, aCoord, &i);
155045    if( i==0 ) *peWithin = NOT_WITHIN;
155046    *prScore = RTREE_ZERO;
155047  }else{
155048    pInfo->aCoord = aCoord;
155049    pInfo->iLevel = pSearch->iLevel - 1;
155050    pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
155051    pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
155052    rc = pConstraint->u.xQueryFunc(pInfo);
155053    if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
155054    if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
155055      *prScore = pInfo->rScore;
155056    }
155057  }
155058  return rc;
155059}
155060
155061/*
155062** Check the internal RTree node given by pCellData against constraint p.
155063** If this constraint cannot be satisfied by any child within the node,
155064** set *peWithin to NOT_WITHIN.
155065*/
155066static void rtreeNonleafConstraint(
155067  RtreeConstraint *p,        /* The constraint to test */
155068  int eInt,                  /* True if RTree holds integer coordinates */
155069  u8 *pCellData,             /* Raw cell content as appears on disk */
155070  int *peWithin              /* Adjust downward, as appropriate */
155071){
155072  sqlite3_rtree_dbl val;     /* Coordinate value convert to a double */
155073
155074  /* p->iCoord might point to either a lower or upper bound coordinate
155075  ** in a coordinate pair.  But make pCellData point to the lower bound.
155076  */
155077  pCellData += 8 + 4*(p->iCoord&0xfe);
155078
155079  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
155080      || p->op==RTREE_GT || p->op==RTREE_EQ );
155081  switch( p->op ){
155082    case RTREE_LE:
155083    case RTREE_LT:
155084    case RTREE_EQ:
155085      RTREE_DECODE_COORD(eInt, pCellData, val);
155086      /* val now holds the lower bound of the coordinate pair */
155087      if( p->u.rValue>=val ) return;
155088      if( p->op!=RTREE_EQ ) break;  /* RTREE_LE and RTREE_LT end here */
155089      /* Fall through for the RTREE_EQ case */
155090
155091    default: /* RTREE_GT or RTREE_GE,  or fallthrough of RTREE_EQ */
155092      pCellData += 4;
155093      RTREE_DECODE_COORD(eInt, pCellData, val);
155094      /* val now holds the upper bound of the coordinate pair */
155095      if( p->u.rValue<=val ) return;
155096  }
155097  *peWithin = NOT_WITHIN;
155098}
155099
155100/*
155101** Check the leaf RTree cell given by pCellData against constraint p.
155102** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
155103** If the constraint is satisfied, leave *peWithin unchanged.
155104**
155105** The constraint is of the form:  xN op $val
155106**
155107** The op is given by p->op.  The xN is p->iCoord-th coordinate in
155108** pCellData.  $val is given by p->u.rValue.
155109*/
155110static void rtreeLeafConstraint(
155111  RtreeConstraint *p,        /* The constraint to test */
155112  int eInt,                  /* True if RTree holds integer coordinates */
155113  u8 *pCellData,             /* Raw cell content as appears on disk */
155114  int *peWithin              /* Adjust downward, as appropriate */
155115){
155116  RtreeDValue xN;      /* Coordinate value converted to a double */
155117
155118  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
155119      || p->op==RTREE_GT || p->op==RTREE_EQ );
155120  pCellData += 8 + p->iCoord*4;
155121  RTREE_DECODE_COORD(eInt, pCellData, xN);
155122  switch( p->op ){
155123    case RTREE_LE: if( xN <= p->u.rValue ) return;  break;
155124    case RTREE_LT: if( xN <  p->u.rValue ) return;  break;
155125    case RTREE_GE: if( xN >= p->u.rValue ) return;  break;
155126    case RTREE_GT: if( xN >  p->u.rValue ) return;  break;
155127    default:       if( xN == p->u.rValue ) return;  break;
155128  }
155129  *peWithin = NOT_WITHIN;
155130}
155131
155132/*
155133** One of the cells in node pNode is guaranteed to have a 64-bit
155134** integer value equal to iRowid. Return the index of this cell.
155135*/
155136static int nodeRowidIndex(
155137  Rtree *pRtree,
155138  RtreeNode *pNode,
155139  i64 iRowid,
155140  int *piIndex
155141){
155142  int ii;
155143  int nCell = NCELL(pNode);
155144  assert( nCell<200 );
155145  for(ii=0; ii<nCell; ii++){
155146    if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
155147      *piIndex = ii;
155148      return SQLITE_OK;
155149    }
155150  }
155151  return SQLITE_CORRUPT_VTAB;
155152}
155153
155154/*
155155** Return the index of the cell containing a pointer to node pNode
155156** in its parent. If pNode is the root node, return -1.
155157*/
155158static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
155159  RtreeNode *pParent = pNode->pParent;
155160  if( pParent ){
155161    return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
155162  }
155163  *piIndex = -1;
155164  return SQLITE_OK;
155165}
155166
155167/*
155168** Compare two search points.  Return negative, zero, or positive if the first
155169** is less than, equal to, or greater than the second.
155170**
155171** The rScore is the primary key.  Smaller rScore values come first.
155172** If the rScore is a tie, then use iLevel as the tie breaker with smaller
155173** iLevel values coming first.  In this way, if rScore is the same for all
155174** SearchPoints, then iLevel becomes the deciding factor and the result
155175** is a depth-first search, which is the desired default behavior.
155176*/
155177static int rtreeSearchPointCompare(
155178  const RtreeSearchPoint *pA,
155179  const RtreeSearchPoint *pB
155180){
155181  if( pA->rScore<pB->rScore ) return -1;
155182  if( pA->rScore>pB->rScore ) return +1;
155183  if( pA->iLevel<pB->iLevel ) return -1;
155184  if( pA->iLevel>pB->iLevel ) return +1;
155185  return 0;
155186}
155187
155188/*
155189** Interchange to search points in a cursor.
155190*/
155191static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
155192  RtreeSearchPoint t = p->aPoint[i];
155193  assert( i<j );
155194  p->aPoint[i] = p->aPoint[j];
155195  p->aPoint[j] = t;
155196  i++; j++;
155197  if( i<RTREE_CACHE_SZ ){
155198    if( j>=RTREE_CACHE_SZ ){
155199      nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
155200      p->aNode[i] = 0;
155201    }else{
155202      RtreeNode *pTemp = p->aNode[i];
155203      p->aNode[i] = p->aNode[j];
155204      p->aNode[j] = pTemp;
155205    }
155206  }
155207}
155208
155209/*
155210** Return the search point with the lowest current score.
155211*/
155212static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
155213  return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
155214}
155215
155216/*
155217** Get the RtreeNode for the search point with the lowest score.
155218*/
155219static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
155220  sqlite3_int64 id;
155221  int ii = 1 - pCur->bPoint;
155222  assert( ii==0 || ii==1 );
155223  assert( pCur->bPoint || pCur->nPoint );
155224  if( pCur->aNode[ii]==0 ){
155225    assert( pRC!=0 );
155226    id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
155227    *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
155228  }
155229  return pCur->aNode[ii];
155230}
155231
155232/*
155233** Push a new element onto the priority queue
155234*/
155235static RtreeSearchPoint *rtreeEnqueue(
155236  RtreeCursor *pCur,    /* The cursor */
155237  RtreeDValue rScore,   /* Score for the new search point */
155238  u8 iLevel             /* Level for the new search point */
155239){
155240  int i, j;
155241  RtreeSearchPoint *pNew;
155242  if( pCur->nPoint>=pCur->nPointAlloc ){
155243    int nNew = pCur->nPointAlloc*2 + 8;
155244    pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
155245    if( pNew==0 ) return 0;
155246    pCur->aPoint = pNew;
155247    pCur->nPointAlloc = nNew;
155248  }
155249  i = pCur->nPoint++;
155250  pNew = pCur->aPoint + i;
155251  pNew->rScore = rScore;
155252  pNew->iLevel = iLevel;
155253  assert( iLevel<=RTREE_MAX_DEPTH );
155254  while( i>0 ){
155255    RtreeSearchPoint *pParent;
155256    j = (i-1)/2;
155257    pParent = pCur->aPoint + j;
155258    if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
155259    rtreeSearchPointSwap(pCur, j, i);
155260    i = j;
155261    pNew = pParent;
155262  }
155263  return pNew;
155264}
155265
155266/*
155267** Allocate a new RtreeSearchPoint and return a pointer to it.  Return
155268** NULL if malloc fails.
155269*/
155270static RtreeSearchPoint *rtreeSearchPointNew(
155271  RtreeCursor *pCur,    /* The cursor */
155272  RtreeDValue rScore,   /* Score for the new search point */
155273  u8 iLevel             /* Level for the new search point */
155274){
155275  RtreeSearchPoint *pNew, *pFirst;
155276  pFirst = rtreeSearchPointFirst(pCur);
155277  pCur->anQueue[iLevel]++;
155278  if( pFirst==0
155279   || pFirst->rScore>rScore
155280   || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
155281  ){
155282    if( pCur->bPoint ){
155283      int ii;
155284      pNew = rtreeEnqueue(pCur, rScore, iLevel);
155285      if( pNew==0 ) return 0;
155286      ii = (int)(pNew - pCur->aPoint) + 1;
155287      if( ii<RTREE_CACHE_SZ ){
155288        assert( pCur->aNode[ii]==0 );
155289        pCur->aNode[ii] = pCur->aNode[0];
155290       }else{
155291        nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
155292      }
155293      pCur->aNode[0] = 0;
155294      *pNew = pCur->sPoint;
155295    }
155296    pCur->sPoint.rScore = rScore;
155297    pCur->sPoint.iLevel = iLevel;
155298    pCur->bPoint = 1;
155299    return &pCur->sPoint;
155300  }else{
155301    return rtreeEnqueue(pCur, rScore, iLevel);
155302  }
155303}
155304
155305#if 0
155306/* Tracing routines for the RtreeSearchPoint queue */
155307static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
155308  if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
155309  printf(" %d.%05lld.%02d %g %d",
155310    p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
155311  );
155312  idx++;
155313  if( idx<RTREE_CACHE_SZ ){
155314    printf(" %p\n", pCur->aNode[idx]);
155315  }else{
155316    printf("\n");
155317  }
155318}
155319static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
155320  int ii;
155321  printf("=== %9s ", zPrefix);
155322  if( pCur->bPoint ){
155323    tracePoint(&pCur->sPoint, -1, pCur);
155324  }
155325  for(ii=0; ii<pCur->nPoint; ii++){
155326    if( ii>0 || pCur->bPoint ) printf("              ");
155327    tracePoint(&pCur->aPoint[ii], ii, pCur);
155328  }
155329}
155330# define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
155331#else
155332# define RTREE_QUEUE_TRACE(A,B)   /* no-op */
155333#endif
155334
155335/* Remove the search point with the lowest current score.
155336*/
155337static void rtreeSearchPointPop(RtreeCursor *p){
155338  int i, j, k, n;
155339  i = 1 - p->bPoint;
155340  assert( i==0 || i==1 );
155341  if( p->aNode[i] ){
155342    nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
155343    p->aNode[i] = 0;
155344  }
155345  if( p->bPoint ){
155346    p->anQueue[p->sPoint.iLevel]--;
155347    p->bPoint = 0;
155348  }else if( p->nPoint ){
155349    p->anQueue[p->aPoint[0].iLevel]--;
155350    n = --p->nPoint;
155351    p->aPoint[0] = p->aPoint[n];
155352    if( n<RTREE_CACHE_SZ-1 ){
155353      p->aNode[1] = p->aNode[n+1];
155354      p->aNode[n+1] = 0;
155355    }
155356    i = 0;
155357    while( (j = i*2+1)<n ){
155358      k = j+1;
155359      if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
155360        if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
155361          rtreeSearchPointSwap(p, i, k);
155362          i = k;
155363        }else{
155364          break;
155365        }
155366      }else{
155367        if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
155368          rtreeSearchPointSwap(p, i, j);
155369          i = j;
155370        }else{
155371          break;
155372        }
155373      }
155374    }
155375  }
155376}
155377
155378
155379/*
155380** Continue the search on cursor pCur until the front of the queue
155381** contains an entry suitable for returning as a result-set row,
155382** or until the RtreeSearchPoint queue is empty, indicating that the
155383** query has completed.
155384*/
155385static int rtreeStepToLeaf(RtreeCursor *pCur){
155386  RtreeSearchPoint *p;
155387  Rtree *pRtree = RTREE_OF_CURSOR(pCur);
155388  RtreeNode *pNode;
155389  int eWithin;
155390  int rc = SQLITE_OK;
155391  int nCell;
155392  int nConstraint = pCur->nConstraint;
155393  int ii;
155394  int eInt;
155395  RtreeSearchPoint x;
155396
155397  eInt = pRtree->eCoordType==RTREE_COORD_INT32;
155398  while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
155399    pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
155400    if( rc ) return rc;
155401    nCell = NCELL(pNode);
155402    assert( nCell<200 );
155403    while( p->iCell<nCell ){
155404      sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
155405      u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
155406      eWithin = FULLY_WITHIN;
155407      for(ii=0; ii<nConstraint; ii++){
155408        RtreeConstraint *pConstraint = pCur->aConstraint + ii;
155409        if( pConstraint->op>=RTREE_MATCH ){
155410          rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
155411                                       &rScore, &eWithin);
155412          if( rc ) return rc;
155413        }else if( p->iLevel==1 ){
155414          rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
155415        }else{
155416          rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
155417        }
155418        if( eWithin==NOT_WITHIN ) break;
155419      }
155420      p->iCell++;
155421      if( eWithin==NOT_WITHIN ) continue;
155422      x.iLevel = p->iLevel - 1;
155423      if( x.iLevel ){
155424        x.id = readInt64(pCellData);
155425        x.iCell = 0;
155426      }else{
155427        x.id = p->id;
155428        x.iCell = p->iCell - 1;
155429      }
155430      if( p->iCell>=nCell ){
155431        RTREE_QUEUE_TRACE(pCur, "POP-S:");
155432        rtreeSearchPointPop(pCur);
155433      }
155434      if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
155435      p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
155436      if( p==0 ) return SQLITE_NOMEM;
155437      p->eWithin = eWithin;
155438      p->id = x.id;
155439      p->iCell = x.iCell;
155440      RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
155441      break;
155442    }
155443    if( p->iCell>=nCell ){
155444      RTREE_QUEUE_TRACE(pCur, "POP-Se:");
155445      rtreeSearchPointPop(pCur);
155446    }
155447  }
155448  pCur->atEOF = p==0;
155449  return SQLITE_OK;
155450}
155451
155452/*
155453** Rtree virtual table module xNext method.
155454*/
155455static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
155456  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
155457  int rc = SQLITE_OK;
155458
155459  /* Move to the next entry that matches the configured constraints. */
155460  RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
155461  rtreeSearchPointPop(pCsr);
155462  rc = rtreeStepToLeaf(pCsr);
155463  return rc;
155464}
155465
155466/*
155467** Rtree virtual table module xRowid method.
155468*/
155469static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
155470  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
155471  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
155472  int rc = SQLITE_OK;
155473  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
155474  if( rc==SQLITE_OK && p ){
155475    *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
155476  }
155477  return rc;
155478}
155479
155480/*
155481** Rtree virtual table module xColumn method.
155482*/
155483static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
155484  Rtree *pRtree = (Rtree *)cur->pVtab;
155485  RtreeCursor *pCsr = (RtreeCursor *)cur;
155486  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
155487  RtreeCoord c;
155488  int rc = SQLITE_OK;
155489  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
155490
155491  if( rc ) return rc;
155492  if( p==0 ) return SQLITE_OK;
155493  if( i==0 ){
155494    sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
155495  }else{
155496    if( rc ) return rc;
155497    nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
155498#ifndef SQLITE_RTREE_INT_ONLY
155499    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
155500      sqlite3_result_double(ctx, c.f);
155501    }else
155502#endif
155503    {
155504      assert( pRtree->eCoordType==RTREE_COORD_INT32 );
155505      sqlite3_result_int(ctx, c.i);
155506    }
155507  }
155508  return SQLITE_OK;
155509}
155510
155511/*
155512** Use nodeAcquire() to obtain the leaf node containing the record with
155513** rowid iRowid. If successful, set *ppLeaf to point to the node and
155514** return SQLITE_OK. If there is no such record in the table, set
155515** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
155516** to zero and return an SQLite error code.
155517*/
155518static int findLeafNode(
155519  Rtree *pRtree,              /* RTree to search */
155520  i64 iRowid,                 /* The rowid searching for */
155521  RtreeNode **ppLeaf,         /* Write the node here */
155522  sqlite3_int64 *piNode       /* Write the node-id here */
155523){
155524  int rc;
155525  *ppLeaf = 0;
155526  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
155527  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
155528    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
155529    if( piNode ) *piNode = iNode;
155530    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
155531    sqlite3_reset(pRtree->pReadRowid);
155532  }else{
155533    rc = sqlite3_reset(pRtree->pReadRowid);
155534  }
155535  return rc;
155536}
155537
155538/*
155539** This function is called to configure the RtreeConstraint object passed
155540** as the second argument for a MATCH constraint. The value passed as the
155541** first argument to this function is the right-hand operand to the MATCH
155542** operator.
155543*/
155544static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
155545  RtreeMatchArg *pBlob;              /* BLOB returned by geometry function */
155546  sqlite3_rtree_query_info *pInfo;   /* Callback information */
155547  int nBlob;                         /* Size of the geometry function blob */
155548  int nExpected;                     /* Expected size of the BLOB */
155549
155550  /* Check that value is actually a blob. */
155551  if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
155552
155553  /* Check that the blob is roughly the right size. */
155554  nBlob = sqlite3_value_bytes(pValue);
155555  if( nBlob<(int)sizeof(RtreeMatchArg) ){
155556    return SQLITE_ERROR;
155557  }
155558
155559  pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
155560  if( !pInfo ) return SQLITE_NOMEM;
155561  memset(pInfo, 0, sizeof(*pInfo));
155562  pBlob = (RtreeMatchArg*)&pInfo[1];
155563
155564  memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
155565  nExpected = (int)(sizeof(RtreeMatchArg) +
155566                    pBlob->nParam*sizeof(sqlite3_value*) +
155567                    (pBlob->nParam-1)*sizeof(RtreeDValue));
155568  if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
155569    sqlite3_free(pInfo);
155570    return SQLITE_ERROR;
155571  }
155572  pInfo->pContext = pBlob->cb.pContext;
155573  pInfo->nParam = pBlob->nParam;
155574  pInfo->aParam = pBlob->aParam;
155575  pInfo->apSqlParam = pBlob->apSqlParam;
155576
155577  if( pBlob->cb.xGeom ){
155578    pCons->u.xGeom = pBlob->cb.xGeom;
155579  }else{
155580    pCons->op = RTREE_QUERY;
155581    pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
155582  }
155583  pCons->pInfo = pInfo;
155584  return SQLITE_OK;
155585}
155586
155587/*
155588** Rtree virtual table module xFilter method.
155589*/
155590static int rtreeFilter(
155591  sqlite3_vtab_cursor *pVtabCursor,
155592  int idxNum, const char *idxStr,
155593  int argc, sqlite3_value **argv
155594){
155595  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
155596  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
155597  RtreeNode *pRoot = 0;
155598  int ii;
155599  int rc = SQLITE_OK;
155600  int iCell = 0;
155601
155602  rtreeReference(pRtree);
155603
155604  /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
155605  freeCursorConstraints(pCsr);
155606  sqlite3_free(pCsr->aPoint);
155607  memset(pCsr, 0, sizeof(RtreeCursor));
155608  pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
155609
155610  pCsr->iStrategy = idxNum;
155611  if( idxNum==1 ){
155612    /* Special case - lookup by rowid. */
155613    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
155614    RtreeSearchPoint *p;     /* Search point for the the leaf */
155615    i64 iRowid = sqlite3_value_int64(argv[0]);
155616    i64 iNode = 0;
155617    rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
155618    if( rc==SQLITE_OK && pLeaf!=0 ){
155619      p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
155620      assert( p!=0 );  /* Always returns pCsr->sPoint */
155621      pCsr->aNode[0] = pLeaf;
155622      p->id = iNode;
155623      p->eWithin = PARTLY_WITHIN;
155624      rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
155625      p->iCell = iCell;
155626      RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
155627    }else{
155628      pCsr->atEOF = 1;
155629    }
155630  }else{
155631    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
155632    ** with the configured constraints.
155633    */
155634    rc = nodeAcquire(pRtree, 1, 0, &pRoot);
155635    if( rc==SQLITE_OK && argc>0 ){
155636      pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
155637      pCsr->nConstraint = argc;
155638      if( !pCsr->aConstraint ){
155639        rc = SQLITE_NOMEM;
155640      }else{
155641        memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
155642        memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
155643        assert( (idxStr==0 && argc==0)
155644                || (idxStr && (int)strlen(idxStr)==argc*2) );
155645        for(ii=0; ii<argc; ii++){
155646          RtreeConstraint *p = &pCsr->aConstraint[ii];
155647          p->op = idxStr[ii*2];
155648          p->iCoord = idxStr[ii*2+1]-'0';
155649          if( p->op>=RTREE_MATCH ){
155650            /* A MATCH operator. The right-hand-side must be a blob that
155651            ** can be cast into an RtreeMatchArg object. One created using
155652            ** an sqlite3_rtree_geometry_callback() SQL user function.
155653            */
155654            rc = deserializeGeometry(argv[ii], p);
155655            if( rc!=SQLITE_OK ){
155656              break;
155657            }
155658            p->pInfo->nCoord = pRtree->nDim*2;
155659            p->pInfo->anQueue = pCsr->anQueue;
155660            p->pInfo->mxLevel = pRtree->iDepth + 1;
155661          }else{
155662#ifdef SQLITE_RTREE_INT_ONLY
155663            p->u.rValue = sqlite3_value_int64(argv[ii]);
155664#else
155665            p->u.rValue = sqlite3_value_double(argv[ii]);
155666#endif
155667          }
155668        }
155669      }
155670    }
155671    if( rc==SQLITE_OK ){
155672      RtreeSearchPoint *pNew;
155673      pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
155674      if( pNew==0 ) return SQLITE_NOMEM;
155675      pNew->id = 1;
155676      pNew->iCell = 0;
155677      pNew->eWithin = PARTLY_WITHIN;
155678      assert( pCsr->bPoint==1 );
155679      pCsr->aNode[0] = pRoot;
155680      pRoot = 0;
155681      RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
155682      rc = rtreeStepToLeaf(pCsr);
155683    }
155684  }
155685
155686  nodeRelease(pRtree, pRoot);
155687  rtreeRelease(pRtree);
155688  return rc;
155689}
155690
155691/*
155692** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
155693** extension is currently being used by a version of SQLite too old to
155694** support estimatedRows. In that case this function is a no-op.
155695*/
155696static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
155697#if SQLITE_VERSION_NUMBER>=3008002
155698  if( sqlite3_libversion_number()>=3008002 ){
155699    pIdxInfo->estimatedRows = nRow;
155700  }
155701#endif
155702}
155703
155704/*
155705** Rtree virtual table module xBestIndex method. There are three
155706** table scan strategies to choose from (in order from most to
155707** least desirable):
155708**
155709**   idxNum     idxStr        Strategy
155710**   ------------------------------------------------
155711**     1        Unused        Direct lookup by rowid.
155712**     2        See below     R-tree query or full-table scan.
155713**   ------------------------------------------------
155714**
155715** If strategy 1 is used, then idxStr is not meaningful. If strategy
155716** 2 is used, idxStr is formatted to contain 2 bytes for each
155717** constraint used. The first two bytes of idxStr correspond to
155718** the constraint in sqlite3_index_info.aConstraintUsage[] with
155719** (argvIndex==1) etc.
155720**
155721** The first of each pair of bytes in idxStr identifies the constraint
155722** operator as follows:
155723**
155724**   Operator    Byte Value
155725**   ----------------------
155726**      =        0x41 ('A')
155727**     <=        0x42 ('B')
155728**      <        0x43 ('C')
155729**     >=        0x44 ('D')
155730**      >        0x45 ('E')
155731**   MATCH       0x46 ('F')
155732**   ----------------------
155733**
155734** The second of each pair of bytes identifies the coordinate column
155735** to which the constraint applies. The leftmost coordinate column
155736** is 'a', the second from the left 'b' etc.
155737*/
155738static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
155739  Rtree *pRtree = (Rtree*)tab;
155740  int rc = SQLITE_OK;
155741  int ii;
155742  int bMatch = 0;                 /* True if there exists a MATCH constraint */
155743  i64 nRow;                       /* Estimated rows returned by this scan */
155744
155745  int iIdx = 0;
155746  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
155747  memset(zIdxStr, 0, sizeof(zIdxStr));
155748
155749  /* Check if there exists a MATCH constraint - even an unusable one. If there
155750  ** is, do not consider the lookup-by-rowid plan as using such a plan would
155751  ** require the VDBE to evaluate the MATCH constraint, which is not currently
155752  ** possible. */
155753  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
155754    if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
155755      bMatch = 1;
155756    }
155757  }
155758
155759  assert( pIdxInfo->idxStr==0 );
155760  for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
155761    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
155762
155763    if( bMatch==0 && p->usable
155764     && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
155765    ){
155766      /* We have an equality constraint on the rowid. Use strategy 1. */
155767      int jj;
155768      for(jj=0; jj<ii; jj++){
155769        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
155770        pIdxInfo->aConstraintUsage[jj].omit = 0;
155771      }
155772      pIdxInfo->idxNum = 1;
155773      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
155774      pIdxInfo->aConstraintUsage[jj].omit = 1;
155775
155776      /* This strategy involves a two rowid lookups on an B-Tree structures
155777      ** and then a linear search of an R-Tree node. This should be
155778      ** considered almost as quick as a direct rowid lookup (for which
155779      ** sqlite uses an internal cost of 0.0). It is expected to return
155780      ** a single row.
155781      */
155782      pIdxInfo->estimatedCost = 30.0;
155783      setEstimatedRows(pIdxInfo, 1);
155784      return SQLITE_OK;
155785    }
155786
155787    if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
155788      u8 op;
155789      switch( p->op ){
155790        case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
155791        case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
155792        case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
155793        case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
155794        case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
155795        default:
155796          assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
155797          op = RTREE_MATCH;
155798          break;
155799      }
155800      zIdxStr[iIdx++] = op;
155801      zIdxStr[iIdx++] = p->iColumn - 1 + '0';
155802      pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
155803      pIdxInfo->aConstraintUsage[ii].omit = 1;
155804    }
155805  }
155806
155807  pIdxInfo->idxNum = 2;
155808  pIdxInfo->needToFreeIdxStr = 1;
155809  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
155810    return SQLITE_NOMEM;
155811  }
155812
155813  nRow = pRtree->nRowEst / (iIdx + 1);
155814  pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
155815  setEstimatedRows(pIdxInfo, nRow);
155816
155817  return rc;
155818}
155819
155820/*
155821** Return the N-dimensional volumn of the cell stored in *p.
155822*/
155823static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
155824  RtreeDValue area = (RtreeDValue)1;
155825  int ii;
155826  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
155827    area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
155828  }
155829  return area;
155830}
155831
155832/*
155833** Return the margin length of cell p. The margin length is the sum
155834** of the objects size in each dimension.
155835*/
155836static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
155837  RtreeDValue margin = (RtreeDValue)0;
155838  int ii;
155839  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
155840    margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
155841  }
155842  return margin;
155843}
155844
155845/*
155846** Store the union of cells p1 and p2 in p1.
155847*/
155848static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
155849  int ii;
155850  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
155851    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
155852      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
155853      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
155854    }
155855  }else{
155856    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
155857      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
155858      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
155859    }
155860  }
155861}
155862
155863/*
155864** Return true if the area covered by p2 is a subset of the area covered
155865** by p1. False otherwise.
155866*/
155867static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
155868  int ii;
155869  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
155870  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
155871    RtreeCoord *a1 = &p1->aCoord[ii];
155872    RtreeCoord *a2 = &p2->aCoord[ii];
155873    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
155874     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
155875    ){
155876      return 0;
155877    }
155878  }
155879  return 1;
155880}
155881
155882/*
155883** Return the amount cell p would grow by if it were unioned with pCell.
155884*/
155885static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
155886  RtreeDValue area;
155887  RtreeCell cell;
155888  memcpy(&cell, p, sizeof(RtreeCell));
155889  area = cellArea(pRtree, &cell);
155890  cellUnion(pRtree, &cell, pCell);
155891  return (cellArea(pRtree, &cell)-area);
155892}
155893
155894static RtreeDValue cellOverlap(
155895  Rtree *pRtree,
155896  RtreeCell *p,
155897  RtreeCell *aCell,
155898  int nCell
155899){
155900  int ii;
155901  RtreeDValue overlap = RTREE_ZERO;
155902  for(ii=0; ii<nCell; ii++){
155903    int jj;
155904    RtreeDValue o = (RtreeDValue)1;
155905    for(jj=0; jj<(pRtree->nDim*2); jj+=2){
155906      RtreeDValue x1, x2;
155907      x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
155908      x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
155909      if( x2<x1 ){
155910        o = (RtreeDValue)0;
155911        break;
155912      }else{
155913        o = o * (x2-x1);
155914      }
155915    }
155916    overlap += o;
155917  }
155918  return overlap;
155919}
155920
155921
155922/*
155923** This function implements the ChooseLeaf algorithm from Gutman[84].
155924** ChooseSubTree in r*tree terminology.
155925*/
155926static int ChooseLeaf(
155927  Rtree *pRtree,               /* Rtree table */
155928  RtreeCell *pCell,            /* Cell to insert into rtree */
155929  int iHeight,                 /* Height of sub-tree rooted at pCell */
155930  RtreeNode **ppLeaf           /* OUT: Selected leaf page */
155931){
155932  int rc;
155933  int ii;
155934  RtreeNode *pNode;
155935  rc = nodeAcquire(pRtree, 1, 0, &pNode);
155936
155937  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
155938    int iCell;
155939    sqlite3_int64 iBest = 0;
155940
155941    RtreeDValue fMinGrowth = RTREE_ZERO;
155942    RtreeDValue fMinArea = RTREE_ZERO;
155943
155944    int nCell = NCELL(pNode);
155945    RtreeCell cell;
155946    RtreeNode *pChild;
155947
155948    RtreeCell *aCell = 0;
155949
155950    /* Select the child node which will be enlarged the least if pCell
155951    ** is inserted into it. Resolve ties by choosing the entry with
155952    ** the smallest area.
155953    */
155954    for(iCell=0; iCell<nCell; iCell++){
155955      int bBest = 0;
155956      RtreeDValue growth;
155957      RtreeDValue area;
155958      nodeGetCell(pRtree, pNode, iCell, &cell);
155959      growth = cellGrowth(pRtree, &cell, pCell);
155960      area = cellArea(pRtree, &cell);
155961      if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
155962        bBest = 1;
155963      }
155964      if( bBest ){
155965        fMinGrowth = growth;
155966        fMinArea = area;
155967        iBest = cell.iRowid;
155968      }
155969    }
155970
155971    sqlite3_free(aCell);
155972    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
155973    nodeRelease(pRtree, pNode);
155974    pNode = pChild;
155975  }
155976
155977  *ppLeaf = pNode;
155978  return rc;
155979}
155980
155981/*
155982** A cell with the same content as pCell has just been inserted into
155983** the node pNode. This function updates the bounding box cells in
155984** all ancestor elements.
155985*/
155986static int AdjustTree(
155987  Rtree *pRtree,                    /* Rtree table */
155988  RtreeNode *pNode,                 /* Adjust ancestry of this node. */
155989  RtreeCell *pCell                  /* This cell was just inserted */
155990){
155991  RtreeNode *p = pNode;
155992  while( p->pParent ){
155993    RtreeNode *pParent = p->pParent;
155994    RtreeCell cell;
155995    int iCell;
155996
155997    if( nodeParentIndex(pRtree, p, &iCell) ){
155998      return SQLITE_CORRUPT_VTAB;
155999    }
156000
156001    nodeGetCell(pRtree, pParent, iCell, &cell);
156002    if( !cellContains(pRtree, &cell, pCell) ){
156003      cellUnion(pRtree, &cell, pCell);
156004      nodeOverwriteCell(pRtree, pParent, &cell, iCell);
156005    }
156006
156007    p = pParent;
156008  }
156009  return SQLITE_OK;
156010}
156011
156012/*
156013** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
156014*/
156015static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
156016  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
156017  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
156018  sqlite3_step(pRtree->pWriteRowid);
156019  return sqlite3_reset(pRtree->pWriteRowid);
156020}
156021
156022/*
156023** Write mapping (iNode->iPar) to the <rtree>_parent table.
156024*/
156025static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
156026  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
156027  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
156028  sqlite3_step(pRtree->pWriteParent);
156029  return sqlite3_reset(pRtree->pWriteParent);
156030}
156031
156032static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
156033
156034
156035/*
156036** Arguments aIdx, aDistance and aSpare all point to arrays of size
156037** nIdx. The aIdx array contains the set of integers from 0 to
156038** (nIdx-1) in no particular order. This function sorts the values
156039** in aIdx according to the indexed values in aDistance. For
156040** example, assuming the inputs:
156041**
156042**   aIdx      = { 0,   1,   2,   3 }
156043**   aDistance = { 5.0, 2.0, 7.0, 6.0 }
156044**
156045** this function sets the aIdx array to contain:
156046**
156047**   aIdx      = { 0,   1,   2,   3 }
156048**
156049** The aSpare array is used as temporary working space by the
156050** sorting algorithm.
156051*/
156052static void SortByDistance(
156053  int *aIdx,
156054  int nIdx,
156055  RtreeDValue *aDistance,
156056  int *aSpare
156057){
156058  if( nIdx>1 ){
156059    int iLeft = 0;
156060    int iRight = 0;
156061
156062    int nLeft = nIdx/2;
156063    int nRight = nIdx-nLeft;
156064    int *aLeft = aIdx;
156065    int *aRight = &aIdx[nLeft];
156066
156067    SortByDistance(aLeft, nLeft, aDistance, aSpare);
156068    SortByDistance(aRight, nRight, aDistance, aSpare);
156069
156070    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
156071    aLeft = aSpare;
156072
156073    while( iLeft<nLeft || iRight<nRight ){
156074      if( iLeft==nLeft ){
156075        aIdx[iLeft+iRight] = aRight[iRight];
156076        iRight++;
156077      }else if( iRight==nRight ){
156078        aIdx[iLeft+iRight] = aLeft[iLeft];
156079        iLeft++;
156080      }else{
156081        RtreeDValue fLeft = aDistance[aLeft[iLeft]];
156082        RtreeDValue fRight = aDistance[aRight[iRight]];
156083        if( fLeft<fRight ){
156084          aIdx[iLeft+iRight] = aLeft[iLeft];
156085          iLeft++;
156086        }else{
156087          aIdx[iLeft+iRight] = aRight[iRight];
156088          iRight++;
156089        }
156090      }
156091    }
156092
156093#if 0
156094    /* Check that the sort worked */
156095    {
156096      int jj;
156097      for(jj=1; jj<nIdx; jj++){
156098        RtreeDValue left = aDistance[aIdx[jj-1]];
156099        RtreeDValue right = aDistance[aIdx[jj]];
156100        assert( left<=right );
156101      }
156102    }
156103#endif
156104  }
156105}
156106
156107/*
156108** Arguments aIdx, aCell and aSpare all point to arrays of size
156109** nIdx. The aIdx array contains the set of integers from 0 to
156110** (nIdx-1) in no particular order. This function sorts the values
156111** in aIdx according to dimension iDim of the cells in aCell. The
156112** minimum value of dimension iDim is considered first, the
156113** maximum used to break ties.
156114**
156115** The aSpare array is used as temporary working space by the
156116** sorting algorithm.
156117*/
156118static void SortByDimension(
156119  Rtree *pRtree,
156120  int *aIdx,
156121  int nIdx,
156122  int iDim,
156123  RtreeCell *aCell,
156124  int *aSpare
156125){
156126  if( nIdx>1 ){
156127
156128    int iLeft = 0;
156129    int iRight = 0;
156130
156131    int nLeft = nIdx/2;
156132    int nRight = nIdx-nLeft;
156133    int *aLeft = aIdx;
156134    int *aRight = &aIdx[nLeft];
156135
156136    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
156137    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
156138
156139    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
156140    aLeft = aSpare;
156141    while( iLeft<nLeft || iRight<nRight ){
156142      RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
156143      RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
156144      RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
156145      RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
156146      if( (iLeft!=nLeft) && ((iRight==nRight)
156147       || (xleft1<xright1)
156148       || (xleft1==xright1 && xleft2<xright2)
156149      )){
156150        aIdx[iLeft+iRight] = aLeft[iLeft];
156151        iLeft++;
156152      }else{
156153        aIdx[iLeft+iRight] = aRight[iRight];
156154        iRight++;
156155      }
156156    }
156157
156158#if 0
156159    /* Check that the sort worked */
156160    {
156161      int jj;
156162      for(jj=1; jj<nIdx; jj++){
156163        RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
156164        RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
156165        RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
156166        RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
156167        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
156168      }
156169    }
156170#endif
156171  }
156172}
156173
156174/*
156175** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
156176*/
156177static int splitNodeStartree(
156178  Rtree *pRtree,
156179  RtreeCell *aCell,
156180  int nCell,
156181  RtreeNode *pLeft,
156182  RtreeNode *pRight,
156183  RtreeCell *pBboxLeft,
156184  RtreeCell *pBboxRight
156185){
156186  int **aaSorted;
156187  int *aSpare;
156188  int ii;
156189
156190  int iBestDim = 0;
156191  int iBestSplit = 0;
156192  RtreeDValue fBestMargin = RTREE_ZERO;
156193
156194  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
156195
156196  aaSorted = (int **)sqlite3_malloc(nByte);
156197  if( !aaSorted ){
156198    return SQLITE_NOMEM;
156199  }
156200
156201  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
156202  memset(aaSorted, 0, nByte);
156203  for(ii=0; ii<pRtree->nDim; ii++){
156204    int jj;
156205    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
156206    for(jj=0; jj<nCell; jj++){
156207      aaSorted[ii][jj] = jj;
156208    }
156209    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
156210  }
156211
156212  for(ii=0; ii<pRtree->nDim; ii++){
156213    RtreeDValue margin = RTREE_ZERO;
156214    RtreeDValue fBestOverlap = RTREE_ZERO;
156215    RtreeDValue fBestArea = RTREE_ZERO;
156216    int iBestLeft = 0;
156217    int nLeft;
156218
156219    for(
156220      nLeft=RTREE_MINCELLS(pRtree);
156221      nLeft<=(nCell-RTREE_MINCELLS(pRtree));
156222      nLeft++
156223    ){
156224      RtreeCell left;
156225      RtreeCell right;
156226      int kk;
156227      RtreeDValue overlap;
156228      RtreeDValue area;
156229
156230      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
156231      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
156232      for(kk=1; kk<(nCell-1); kk++){
156233        if( kk<nLeft ){
156234          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
156235        }else{
156236          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
156237        }
156238      }
156239      margin += cellMargin(pRtree, &left);
156240      margin += cellMargin(pRtree, &right);
156241      overlap = cellOverlap(pRtree, &left, &right, 1);
156242      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
156243      if( (nLeft==RTREE_MINCELLS(pRtree))
156244       || (overlap<fBestOverlap)
156245       || (overlap==fBestOverlap && area<fBestArea)
156246      ){
156247        iBestLeft = nLeft;
156248        fBestOverlap = overlap;
156249        fBestArea = area;
156250      }
156251    }
156252
156253    if( ii==0 || margin<fBestMargin ){
156254      iBestDim = ii;
156255      fBestMargin = margin;
156256      iBestSplit = iBestLeft;
156257    }
156258  }
156259
156260  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
156261  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
156262  for(ii=0; ii<nCell; ii++){
156263    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
156264    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
156265    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
156266    nodeInsertCell(pRtree, pTarget, pCell);
156267    cellUnion(pRtree, pBbox, pCell);
156268  }
156269
156270  sqlite3_free(aaSorted);
156271  return SQLITE_OK;
156272}
156273
156274
156275static int updateMapping(
156276  Rtree *pRtree,
156277  i64 iRowid,
156278  RtreeNode *pNode,
156279  int iHeight
156280){
156281  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
156282  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
156283  if( iHeight>0 ){
156284    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
156285    if( pChild ){
156286      nodeRelease(pRtree, pChild->pParent);
156287      nodeReference(pNode);
156288      pChild->pParent = pNode;
156289    }
156290  }
156291  return xSetMapping(pRtree, iRowid, pNode->iNode);
156292}
156293
156294static int SplitNode(
156295  Rtree *pRtree,
156296  RtreeNode *pNode,
156297  RtreeCell *pCell,
156298  int iHeight
156299){
156300  int i;
156301  int newCellIsRight = 0;
156302
156303  int rc = SQLITE_OK;
156304  int nCell = NCELL(pNode);
156305  RtreeCell *aCell;
156306  int *aiUsed;
156307
156308  RtreeNode *pLeft = 0;
156309  RtreeNode *pRight = 0;
156310
156311  RtreeCell leftbbox;
156312  RtreeCell rightbbox;
156313
156314  /* Allocate an array and populate it with a copy of pCell and
156315  ** all cells from node pLeft. Then zero the original node.
156316  */
156317  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
156318  if( !aCell ){
156319    rc = SQLITE_NOMEM;
156320    goto splitnode_out;
156321  }
156322  aiUsed = (int *)&aCell[nCell+1];
156323  memset(aiUsed, 0, sizeof(int)*(nCell+1));
156324  for(i=0; i<nCell; i++){
156325    nodeGetCell(pRtree, pNode, i, &aCell[i]);
156326  }
156327  nodeZero(pRtree, pNode);
156328  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
156329  nCell++;
156330
156331  if( pNode->iNode==1 ){
156332    pRight = nodeNew(pRtree, pNode);
156333    pLeft = nodeNew(pRtree, pNode);
156334    pRtree->iDepth++;
156335    pNode->isDirty = 1;
156336    writeInt16(pNode->zData, pRtree->iDepth);
156337  }else{
156338    pLeft = pNode;
156339    pRight = nodeNew(pRtree, pLeft->pParent);
156340    nodeReference(pLeft);
156341  }
156342
156343  if( !pLeft || !pRight ){
156344    rc = SQLITE_NOMEM;
156345    goto splitnode_out;
156346  }
156347
156348  memset(pLeft->zData, 0, pRtree->iNodeSize);
156349  memset(pRight->zData, 0, pRtree->iNodeSize);
156350
156351  rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
156352                         &leftbbox, &rightbbox);
156353  if( rc!=SQLITE_OK ){
156354    goto splitnode_out;
156355  }
156356
156357  /* Ensure both child nodes have node numbers assigned to them by calling
156358  ** nodeWrite(). Node pRight always needs a node number, as it was created
156359  ** by nodeNew() above. But node pLeft sometimes already has a node number.
156360  ** In this case avoid the all to nodeWrite().
156361  */
156362  if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
156363   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
156364  ){
156365    goto splitnode_out;
156366  }
156367
156368  rightbbox.iRowid = pRight->iNode;
156369  leftbbox.iRowid = pLeft->iNode;
156370
156371  if( pNode->iNode==1 ){
156372    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
156373    if( rc!=SQLITE_OK ){
156374      goto splitnode_out;
156375    }
156376  }else{
156377    RtreeNode *pParent = pLeft->pParent;
156378    int iCell;
156379    rc = nodeParentIndex(pRtree, pLeft, &iCell);
156380    if( rc==SQLITE_OK ){
156381      nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
156382      rc = AdjustTree(pRtree, pParent, &leftbbox);
156383    }
156384    if( rc!=SQLITE_OK ){
156385      goto splitnode_out;
156386    }
156387  }
156388  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
156389    goto splitnode_out;
156390  }
156391
156392  for(i=0; i<NCELL(pRight); i++){
156393    i64 iRowid = nodeGetRowid(pRtree, pRight, i);
156394    rc = updateMapping(pRtree, iRowid, pRight, iHeight);
156395    if( iRowid==pCell->iRowid ){
156396      newCellIsRight = 1;
156397    }
156398    if( rc!=SQLITE_OK ){
156399      goto splitnode_out;
156400    }
156401  }
156402  if( pNode->iNode==1 ){
156403    for(i=0; i<NCELL(pLeft); i++){
156404      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
156405      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
156406      if( rc!=SQLITE_OK ){
156407        goto splitnode_out;
156408      }
156409    }
156410  }else if( newCellIsRight==0 ){
156411    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
156412  }
156413
156414  if( rc==SQLITE_OK ){
156415    rc = nodeRelease(pRtree, pRight);
156416    pRight = 0;
156417  }
156418  if( rc==SQLITE_OK ){
156419    rc = nodeRelease(pRtree, pLeft);
156420    pLeft = 0;
156421  }
156422
156423splitnode_out:
156424  nodeRelease(pRtree, pRight);
156425  nodeRelease(pRtree, pLeft);
156426  sqlite3_free(aCell);
156427  return rc;
156428}
156429
156430/*
156431** If node pLeaf is not the root of the r-tree and its pParent pointer is
156432** still NULL, load all ancestor nodes of pLeaf into memory and populate
156433** the pLeaf->pParent chain all the way up to the root node.
156434**
156435** This operation is required when a row is deleted (or updated - an update
156436** is implemented as a delete followed by an insert). SQLite provides the
156437** rowid of the row to delete, which can be used to find the leaf on which
156438** the entry resides (argument pLeaf). Once the leaf is located, this
156439** function is called to determine its ancestry.
156440*/
156441static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
156442  int rc = SQLITE_OK;
156443  RtreeNode *pChild = pLeaf;
156444  while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
156445    int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
156446    sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
156447    rc = sqlite3_step(pRtree->pReadParent);
156448    if( rc==SQLITE_ROW ){
156449      RtreeNode *pTest;           /* Used to test for reference loops */
156450      i64 iNode;                  /* Node number of parent node */
156451
156452      /* Before setting pChild->pParent, test that we are not creating a
156453      ** loop of references (as we would if, say, pChild==pParent). We don't
156454      ** want to do this as it leads to a memory leak when trying to delete
156455      ** the referenced counted node structures.
156456      */
156457      iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
156458      for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
156459      if( !pTest ){
156460        rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
156461      }
156462    }
156463    rc = sqlite3_reset(pRtree->pReadParent);
156464    if( rc==SQLITE_OK ) rc = rc2;
156465    if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
156466    pChild = pChild->pParent;
156467  }
156468  return rc;
156469}
156470
156471static int deleteCell(Rtree *, RtreeNode *, int, int);
156472
156473static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
156474  int rc;
156475  int rc2;
156476  RtreeNode *pParent = 0;
156477  int iCell;
156478
156479  assert( pNode->nRef==1 );
156480
156481  /* Remove the entry in the parent cell. */
156482  rc = nodeParentIndex(pRtree, pNode, &iCell);
156483  if( rc==SQLITE_OK ){
156484    pParent = pNode->pParent;
156485    pNode->pParent = 0;
156486    rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
156487  }
156488  rc2 = nodeRelease(pRtree, pParent);
156489  if( rc==SQLITE_OK ){
156490    rc = rc2;
156491  }
156492  if( rc!=SQLITE_OK ){
156493    return rc;
156494  }
156495
156496  /* Remove the xxx_node entry. */
156497  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
156498  sqlite3_step(pRtree->pDeleteNode);
156499  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
156500    return rc;
156501  }
156502
156503  /* Remove the xxx_parent entry. */
156504  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
156505  sqlite3_step(pRtree->pDeleteParent);
156506  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
156507    return rc;
156508  }
156509
156510  /* Remove the node from the in-memory hash table and link it into
156511  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
156512  */
156513  nodeHashDelete(pRtree, pNode);
156514  pNode->iNode = iHeight;
156515  pNode->pNext = pRtree->pDeleted;
156516  pNode->nRef++;
156517  pRtree->pDeleted = pNode;
156518
156519  return SQLITE_OK;
156520}
156521
156522static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
156523  RtreeNode *pParent = pNode->pParent;
156524  int rc = SQLITE_OK;
156525  if( pParent ){
156526    int ii;
156527    int nCell = NCELL(pNode);
156528    RtreeCell box;                            /* Bounding box for pNode */
156529    nodeGetCell(pRtree, pNode, 0, &box);
156530    for(ii=1; ii<nCell; ii++){
156531      RtreeCell cell;
156532      nodeGetCell(pRtree, pNode, ii, &cell);
156533      cellUnion(pRtree, &box, &cell);
156534    }
156535    box.iRowid = pNode->iNode;
156536    rc = nodeParentIndex(pRtree, pNode, &ii);
156537    if( rc==SQLITE_OK ){
156538      nodeOverwriteCell(pRtree, pParent, &box, ii);
156539      rc = fixBoundingBox(pRtree, pParent);
156540    }
156541  }
156542  return rc;
156543}
156544
156545/*
156546** Delete the cell at index iCell of node pNode. After removing the
156547** cell, adjust the r-tree data structure if required.
156548*/
156549static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
156550  RtreeNode *pParent;
156551  int rc;
156552
156553  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
156554    return rc;
156555  }
156556
156557  /* Remove the cell from the node. This call just moves bytes around
156558  ** the in-memory node image, so it cannot fail.
156559  */
156560  nodeDeleteCell(pRtree, pNode, iCell);
156561
156562  /* If the node is not the tree root and now has less than the minimum
156563  ** number of cells, remove it from the tree. Otherwise, update the
156564  ** cell in the parent node so that it tightly contains the updated
156565  ** node.
156566  */
156567  pParent = pNode->pParent;
156568  assert( pParent || pNode->iNode==1 );
156569  if( pParent ){
156570    if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
156571      rc = removeNode(pRtree, pNode, iHeight);
156572    }else{
156573      rc = fixBoundingBox(pRtree, pNode);
156574    }
156575  }
156576
156577  return rc;
156578}
156579
156580static int Reinsert(
156581  Rtree *pRtree,
156582  RtreeNode *pNode,
156583  RtreeCell *pCell,
156584  int iHeight
156585){
156586  int *aOrder;
156587  int *aSpare;
156588  RtreeCell *aCell;
156589  RtreeDValue *aDistance;
156590  int nCell;
156591  RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
156592  int iDim;
156593  int ii;
156594  int rc = SQLITE_OK;
156595  int n;
156596
156597  memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
156598
156599  nCell = NCELL(pNode)+1;
156600  n = (nCell+1)&(~1);
156601
156602  /* Allocate the buffers used by this operation. The allocation is
156603  ** relinquished before this function returns.
156604  */
156605  aCell = (RtreeCell *)sqlite3_malloc(n * (
156606    sizeof(RtreeCell)     +         /* aCell array */
156607    sizeof(int)           +         /* aOrder array */
156608    sizeof(int)           +         /* aSpare array */
156609    sizeof(RtreeDValue)             /* aDistance array */
156610  ));
156611  if( !aCell ){
156612    return SQLITE_NOMEM;
156613  }
156614  aOrder    = (int *)&aCell[n];
156615  aSpare    = (int *)&aOrder[n];
156616  aDistance = (RtreeDValue *)&aSpare[n];
156617
156618  for(ii=0; ii<nCell; ii++){
156619    if( ii==(nCell-1) ){
156620      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
156621    }else{
156622      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
156623    }
156624    aOrder[ii] = ii;
156625    for(iDim=0; iDim<pRtree->nDim; iDim++){
156626      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
156627      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
156628    }
156629  }
156630  for(iDim=0; iDim<pRtree->nDim; iDim++){
156631    aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
156632  }
156633
156634  for(ii=0; ii<nCell; ii++){
156635    aDistance[ii] = RTREE_ZERO;
156636    for(iDim=0; iDim<pRtree->nDim; iDim++){
156637      RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
156638                               DCOORD(aCell[ii].aCoord[iDim*2]));
156639      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
156640    }
156641  }
156642
156643  SortByDistance(aOrder, nCell, aDistance, aSpare);
156644  nodeZero(pRtree, pNode);
156645
156646  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
156647    RtreeCell *p = &aCell[aOrder[ii]];
156648    nodeInsertCell(pRtree, pNode, p);
156649    if( p->iRowid==pCell->iRowid ){
156650      if( iHeight==0 ){
156651        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
156652      }else{
156653        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
156654      }
156655    }
156656  }
156657  if( rc==SQLITE_OK ){
156658    rc = fixBoundingBox(pRtree, pNode);
156659  }
156660  for(; rc==SQLITE_OK && ii<nCell; ii++){
156661    /* Find a node to store this cell in. pNode->iNode currently contains
156662    ** the height of the sub-tree headed by the cell.
156663    */
156664    RtreeNode *pInsert;
156665    RtreeCell *p = &aCell[aOrder[ii]];
156666    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
156667    if( rc==SQLITE_OK ){
156668      int rc2;
156669      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
156670      rc2 = nodeRelease(pRtree, pInsert);
156671      if( rc==SQLITE_OK ){
156672        rc = rc2;
156673      }
156674    }
156675  }
156676
156677  sqlite3_free(aCell);
156678  return rc;
156679}
156680
156681/*
156682** Insert cell pCell into node pNode. Node pNode is the head of a
156683** subtree iHeight high (leaf nodes have iHeight==0).
156684*/
156685static int rtreeInsertCell(
156686  Rtree *pRtree,
156687  RtreeNode *pNode,
156688  RtreeCell *pCell,
156689  int iHeight
156690){
156691  int rc = SQLITE_OK;
156692  if( iHeight>0 ){
156693    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
156694    if( pChild ){
156695      nodeRelease(pRtree, pChild->pParent);
156696      nodeReference(pNode);
156697      pChild->pParent = pNode;
156698    }
156699  }
156700  if( nodeInsertCell(pRtree, pNode, pCell) ){
156701    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
156702      rc = SplitNode(pRtree, pNode, pCell, iHeight);
156703    }else{
156704      pRtree->iReinsertHeight = iHeight;
156705      rc = Reinsert(pRtree, pNode, pCell, iHeight);
156706    }
156707  }else{
156708    rc = AdjustTree(pRtree, pNode, pCell);
156709    if( rc==SQLITE_OK ){
156710      if( iHeight==0 ){
156711        rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
156712      }else{
156713        rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
156714      }
156715    }
156716  }
156717  return rc;
156718}
156719
156720static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
156721  int ii;
156722  int rc = SQLITE_OK;
156723  int nCell = NCELL(pNode);
156724
156725  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
156726    RtreeNode *pInsert;
156727    RtreeCell cell;
156728    nodeGetCell(pRtree, pNode, ii, &cell);
156729
156730    /* Find a node to store this cell in. pNode->iNode currently contains
156731    ** the height of the sub-tree headed by the cell.
156732    */
156733    rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
156734    if( rc==SQLITE_OK ){
156735      int rc2;
156736      rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
156737      rc2 = nodeRelease(pRtree, pInsert);
156738      if( rc==SQLITE_OK ){
156739        rc = rc2;
156740      }
156741    }
156742  }
156743  return rc;
156744}
156745
156746/*
156747** Select a currently unused rowid for a new r-tree record.
156748*/
156749static int newRowid(Rtree *pRtree, i64 *piRowid){
156750  int rc;
156751  sqlite3_bind_null(pRtree->pWriteRowid, 1);
156752  sqlite3_bind_null(pRtree->pWriteRowid, 2);
156753  sqlite3_step(pRtree->pWriteRowid);
156754  rc = sqlite3_reset(pRtree->pWriteRowid);
156755  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
156756  return rc;
156757}
156758
156759/*
156760** Remove the entry with rowid=iDelete from the r-tree structure.
156761*/
156762static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
156763  int rc;                         /* Return code */
156764  RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
156765  int iCell;                      /* Index of iDelete cell in pLeaf */
156766  RtreeNode *pRoot;               /* Root node of rtree structure */
156767
156768
156769  /* Obtain a reference to the root node to initialize Rtree.iDepth */
156770  rc = nodeAcquire(pRtree, 1, 0, &pRoot);
156771
156772  /* Obtain a reference to the leaf node that contains the entry
156773  ** about to be deleted.
156774  */
156775  if( rc==SQLITE_OK ){
156776    rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
156777  }
156778
156779  /* Delete the cell in question from the leaf node. */
156780  if( rc==SQLITE_OK ){
156781    int rc2;
156782    rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
156783    if( rc==SQLITE_OK ){
156784      rc = deleteCell(pRtree, pLeaf, iCell, 0);
156785    }
156786    rc2 = nodeRelease(pRtree, pLeaf);
156787    if( rc==SQLITE_OK ){
156788      rc = rc2;
156789    }
156790  }
156791
156792  /* Delete the corresponding entry in the <rtree>_rowid table. */
156793  if( rc==SQLITE_OK ){
156794    sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
156795    sqlite3_step(pRtree->pDeleteRowid);
156796    rc = sqlite3_reset(pRtree->pDeleteRowid);
156797  }
156798
156799  /* Check if the root node now has exactly one child. If so, remove
156800  ** it, schedule the contents of the child for reinsertion and
156801  ** reduce the tree height by one.
156802  **
156803  ** This is equivalent to copying the contents of the child into
156804  ** the root node (the operation that Gutman's paper says to perform
156805  ** in this scenario).
156806  */
156807  if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
156808    int rc2;
156809    RtreeNode *pChild;
156810    i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
156811    rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
156812    if( rc==SQLITE_OK ){
156813      rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
156814    }
156815    rc2 = nodeRelease(pRtree, pChild);
156816    if( rc==SQLITE_OK ) rc = rc2;
156817    if( rc==SQLITE_OK ){
156818      pRtree->iDepth--;
156819      writeInt16(pRoot->zData, pRtree->iDepth);
156820      pRoot->isDirty = 1;
156821    }
156822  }
156823
156824  /* Re-insert the contents of any underfull nodes removed from the tree. */
156825  for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
156826    if( rc==SQLITE_OK ){
156827      rc = reinsertNodeContent(pRtree, pLeaf);
156828    }
156829    pRtree->pDeleted = pLeaf->pNext;
156830    sqlite3_free(pLeaf);
156831  }
156832
156833  /* Release the reference to the root node. */
156834  if( rc==SQLITE_OK ){
156835    rc = nodeRelease(pRtree, pRoot);
156836  }else{
156837    nodeRelease(pRtree, pRoot);
156838  }
156839
156840  return rc;
156841}
156842
156843/*
156844** Rounding constants for float->double conversion.
156845*/
156846#define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
156847#define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
156848
156849#if !defined(SQLITE_RTREE_INT_ONLY)
156850/*
156851** Convert an sqlite3_value into an RtreeValue (presumably a float)
156852** while taking care to round toward negative or positive, respectively.
156853*/
156854static RtreeValue rtreeValueDown(sqlite3_value *v){
156855  double d = sqlite3_value_double(v);
156856  float f = (float)d;
156857  if( f>d ){
156858    f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
156859  }
156860  return f;
156861}
156862static RtreeValue rtreeValueUp(sqlite3_value *v){
156863  double d = sqlite3_value_double(v);
156864  float f = (float)d;
156865  if( f<d ){
156866    f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
156867  }
156868  return f;
156869}
156870#endif /* !defined(SQLITE_RTREE_INT_ONLY) */
156871
156872
156873/*
156874** The xUpdate method for rtree module virtual tables.
156875*/
156876static int rtreeUpdate(
156877  sqlite3_vtab *pVtab,
156878  int nData,
156879  sqlite3_value **azData,
156880  sqlite_int64 *pRowid
156881){
156882  Rtree *pRtree = (Rtree *)pVtab;
156883  int rc = SQLITE_OK;
156884  RtreeCell cell;                 /* New cell to insert if nData>1 */
156885  int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
156886
156887  rtreeReference(pRtree);
156888  assert(nData>=1);
156889
156890  cell.iRowid = 0;  /* Used only to suppress a compiler warning */
156891
156892  /* Constraint handling. A write operation on an r-tree table may return
156893  ** SQLITE_CONSTRAINT for two reasons:
156894  **
156895  **   1. A duplicate rowid value, or
156896  **   2. The supplied data violates the "x2>=x1" constraint.
156897  **
156898  ** In the first case, if the conflict-handling mode is REPLACE, then
156899  ** the conflicting row can be removed before proceeding. In the second
156900  ** case, SQLITE_CONSTRAINT must be returned regardless of the
156901  ** conflict-handling mode specified by the user.
156902  */
156903  if( nData>1 ){
156904    int ii;
156905
156906    /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
156907    **
156908    ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
156909    ** with "column" that are interpreted as table constraints.
156910    ** Example:  CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
156911    ** This problem was discovered after years of use, so we silently ignore
156912    ** these kinds of misdeclared tables to avoid breaking any legacy.
156913    */
156914    assert( nData<=(pRtree->nDim*2 + 3) );
156915
156916#ifndef SQLITE_RTREE_INT_ONLY
156917    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
156918      for(ii=0; ii<nData-4; ii+=2){
156919        cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
156920        cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
156921        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
156922          rc = SQLITE_CONSTRAINT;
156923          goto constraint;
156924        }
156925      }
156926    }else
156927#endif
156928    {
156929      for(ii=0; ii<nData-4; ii+=2){
156930        cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
156931        cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
156932        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
156933          rc = SQLITE_CONSTRAINT;
156934          goto constraint;
156935        }
156936      }
156937    }
156938
156939    /* If a rowid value was supplied, check if it is already present in
156940    ** the table. If so, the constraint has failed. */
156941    if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
156942      cell.iRowid = sqlite3_value_int64(azData[2]);
156943      if( sqlite3_value_type(azData[0])==SQLITE_NULL
156944       || sqlite3_value_int64(azData[0])!=cell.iRowid
156945      ){
156946        int steprc;
156947        sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
156948        steprc = sqlite3_step(pRtree->pReadRowid);
156949        rc = sqlite3_reset(pRtree->pReadRowid);
156950        if( SQLITE_ROW==steprc ){
156951          if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
156952            rc = rtreeDeleteRowid(pRtree, cell.iRowid);
156953          }else{
156954            rc = SQLITE_CONSTRAINT;
156955            goto constraint;
156956          }
156957        }
156958      }
156959      bHaveRowid = 1;
156960    }
156961  }
156962
156963  /* If azData[0] is not an SQL NULL value, it is the rowid of a
156964  ** record to delete from the r-tree table. The following block does
156965  ** just that.
156966  */
156967  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
156968    rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
156969  }
156970
156971  /* If the azData[] array contains more than one element, elements
156972  ** (azData[2]..azData[argc-1]) contain a new record to insert into
156973  ** the r-tree structure.
156974  */
156975  if( rc==SQLITE_OK && nData>1 ){
156976    /* Insert the new record into the r-tree */
156977    RtreeNode *pLeaf = 0;
156978
156979    /* Figure out the rowid of the new row. */
156980    if( bHaveRowid==0 ){
156981      rc = newRowid(pRtree, &cell.iRowid);
156982    }
156983    *pRowid = cell.iRowid;
156984
156985    if( rc==SQLITE_OK ){
156986      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
156987    }
156988    if( rc==SQLITE_OK ){
156989      int rc2;
156990      pRtree->iReinsertHeight = -1;
156991      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
156992      rc2 = nodeRelease(pRtree, pLeaf);
156993      if( rc==SQLITE_OK ){
156994        rc = rc2;
156995      }
156996    }
156997  }
156998
156999constraint:
157000  rtreeRelease(pRtree);
157001  return rc;
157002}
157003
157004/*
157005** The xRename method for rtree module virtual tables.
157006*/
157007static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
157008  Rtree *pRtree = (Rtree *)pVtab;
157009  int rc = SQLITE_NOMEM;
157010  char *zSql = sqlite3_mprintf(
157011    "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
157012    "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
157013    "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
157014    , pRtree->zDb, pRtree->zName, zNewName
157015    , pRtree->zDb, pRtree->zName, zNewName
157016    , pRtree->zDb, pRtree->zName, zNewName
157017  );
157018  if( zSql ){
157019    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
157020    sqlite3_free(zSql);
157021  }
157022  return rc;
157023}
157024
157025/*
157026** This function populates the pRtree->nRowEst variable with an estimate
157027** of the number of rows in the virtual table. If possible, this is based
157028** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
157029*/
157030static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
157031  const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
157032  char *zSql;
157033  sqlite3_stmt *p;
157034  int rc;
157035  i64 nRow = 0;
157036
157037  zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
157038  if( zSql==0 ){
157039    rc = SQLITE_NOMEM;
157040  }else{
157041    rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
157042    if( rc==SQLITE_OK ){
157043      if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
157044      rc = sqlite3_finalize(p);
157045    }else if( rc!=SQLITE_NOMEM ){
157046      rc = SQLITE_OK;
157047    }
157048
157049    if( rc==SQLITE_OK ){
157050      if( nRow==0 ){
157051        pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
157052      }else{
157053        pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
157054      }
157055    }
157056    sqlite3_free(zSql);
157057  }
157058
157059  return rc;
157060}
157061
157062static sqlite3_module rtreeModule = {
157063  0,                          /* iVersion */
157064  rtreeCreate,                /* xCreate - create a table */
157065  rtreeConnect,               /* xConnect - connect to an existing table */
157066  rtreeBestIndex,             /* xBestIndex - Determine search strategy */
157067  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
157068  rtreeDestroy,               /* xDestroy - Drop a table */
157069  rtreeOpen,                  /* xOpen - open a cursor */
157070  rtreeClose,                 /* xClose - close a cursor */
157071  rtreeFilter,                /* xFilter - configure scan constraints */
157072  rtreeNext,                  /* xNext - advance a cursor */
157073  rtreeEof,                   /* xEof */
157074  rtreeColumn,                /* xColumn - read data */
157075  rtreeRowid,                 /* xRowid - read data */
157076  rtreeUpdate,                /* xUpdate - write data */
157077  0,                          /* xBegin - begin transaction */
157078  0,                          /* xSync - sync transaction */
157079  0,                          /* xCommit - commit transaction */
157080  0,                          /* xRollback - rollback transaction */
157081  0,                          /* xFindFunction - function overloading */
157082  rtreeRename,                /* xRename - rename the table */
157083  0,                          /* xSavepoint */
157084  0,                          /* xRelease */
157085  0                           /* xRollbackTo */
157086};
157087
157088static int rtreeSqlInit(
157089  Rtree *pRtree,
157090  sqlite3 *db,
157091  const char *zDb,
157092  const char *zPrefix,
157093  int isCreate
157094){
157095  int rc = SQLITE_OK;
157096
157097  #define N_STATEMENT 9
157098  static const char *azSql[N_STATEMENT] = {
157099    /* Read and write the xxx_node table */
157100    "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
157101    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
157102    "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
157103
157104    /* Read and write the xxx_rowid table */
157105    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
157106    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
157107    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
157108
157109    /* Read and write the xxx_parent table */
157110    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
157111    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
157112    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
157113  };
157114  sqlite3_stmt **appStmt[N_STATEMENT];
157115  int i;
157116
157117  pRtree->db = db;
157118
157119  if( isCreate ){
157120    char *zCreate = sqlite3_mprintf(
157121"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
157122"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
157123"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
157124                                  " parentnode INTEGER);"
157125"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
157126      zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
157127    );
157128    if( !zCreate ){
157129      return SQLITE_NOMEM;
157130    }
157131    rc = sqlite3_exec(db, zCreate, 0, 0, 0);
157132    sqlite3_free(zCreate);
157133    if( rc!=SQLITE_OK ){
157134      return rc;
157135    }
157136  }
157137
157138  appStmt[0] = &pRtree->pReadNode;
157139  appStmt[1] = &pRtree->pWriteNode;
157140  appStmt[2] = &pRtree->pDeleteNode;
157141  appStmt[3] = &pRtree->pReadRowid;
157142  appStmt[4] = &pRtree->pWriteRowid;
157143  appStmt[5] = &pRtree->pDeleteRowid;
157144  appStmt[6] = &pRtree->pReadParent;
157145  appStmt[7] = &pRtree->pWriteParent;
157146  appStmt[8] = &pRtree->pDeleteParent;
157147
157148  rc = rtreeQueryStat1(db, pRtree);
157149  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
157150    char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
157151    if( zSql ){
157152      rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
157153    }else{
157154      rc = SQLITE_NOMEM;
157155    }
157156    sqlite3_free(zSql);
157157  }
157158
157159  return rc;
157160}
157161
157162/*
157163** The second argument to this function contains the text of an SQL statement
157164** that returns a single integer value. The statement is compiled and executed
157165** using database connection db. If successful, the integer value returned
157166** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
157167** code is returned and the value of *piVal after returning is not defined.
157168*/
157169static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
157170  int rc = SQLITE_NOMEM;
157171  if( zSql ){
157172    sqlite3_stmt *pStmt = 0;
157173    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
157174    if( rc==SQLITE_OK ){
157175      if( SQLITE_ROW==sqlite3_step(pStmt) ){
157176        *piVal = sqlite3_column_int(pStmt, 0);
157177      }
157178      rc = sqlite3_finalize(pStmt);
157179    }
157180  }
157181  return rc;
157182}
157183
157184/*
157185** This function is called from within the xConnect() or xCreate() method to
157186** determine the node-size used by the rtree table being created or connected
157187** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
157188** Otherwise, an SQLite error code is returned.
157189**
157190** If this function is being called as part of an xConnect(), then the rtree
157191** table already exists. In this case the node-size is determined by inspecting
157192** the root node of the tree.
157193**
157194** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
157195** This ensures that each node is stored on a single database page. If the
157196** database page-size is so large that more than RTREE_MAXCELLS entries
157197** would fit in a single node, use a smaller node-size.
157198*/
157199static int getNodeSize(
157200  sqlite3 *db,                    /* Database handle */
157201  Rtree *pRtree,                  /* Rtree handle */
157202  int isCreate,                   /* True for xCreate, false for xConnect */
157203  char **pzErr                    /* OUT: Error message, if any */
157204){
157205  int rc;
157206  char *zSql;
157207  if( isCreate ){
157208    int iPageSize = 0;
157209    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
157210    rc = getIntFromStmt(db, zSql, &iPageSize);
157211    if( rc==SQLITE_OK ){
157212      pRtree->iNodeSize = iPageSize-64;
157213      if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
157214        pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
157215      }
157216    }else{
157217      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
157218    }
157219  }else{
157220    zSql = sqlite3_mprintf(
157221        "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
157222        pRtree->zDb, pRtree->zName
157223    );
157224    rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
157225    if( rc!=SQLITE_OK ){
157226      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
157227    }
157228  }
157229
157230  sqlite3_free(zSql);
157231  return rc;
157232}
157233
157234/*
157235** This function is the implementation of both the xConnect and xCreate
157236** methods of the r-tree virtual table.
157237**
157238**   argv[0]   -> module name
157239**   argv[1]   -> database name
157240**   argv[2]   -> table name
157241**   argv[...] -> column names...
157242*/
157243static int rtreeInit(
157244  sqlite3 *db,                        /* Database connection */
157245  void *pAux,                         /* One of the RTREE_COORD_* constants */
157246  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
157247  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
157248  char **pzErr,                       /* OUT: Error message, if any */
157249  int isCreate                        /* True for xCreate, false for xConnect */
157250){
157251  int rc = SQLITE_OK;
157252  Rtree *pRtree;
157253  int nDb;              /* Length of string argv[1] */
157254  int nName;            /* Length of string argv[2] */
157255  int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
157256
157257  const char *aErrMsg[] = {
157258    0,                                                    /* 0 */
157259    "Wrong number of columns for an rtree table",         /* 1 */
157260    "Too few columns for an rtree table",                 /* 2 */
157261    "Too many columns for an rtree table"                 /* 3 */
157262  };
157263
157264  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
157265  if( aErrMsg[iErr] ){
157266    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
157267    return SQLITE_ERROR;
157268  }
157269
157270  sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
157271
157272  /* Allocate the sqlite3_vtab structure */
157273  nDb = (int)strlen(argv[1]);
157274  nName = (int)strlen(argv[2]);
157275  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
157276  if( !pRtree ){
157277    return SQLITE_NOMEM;
157278  }
157279  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
157280  pRtree->nBusy = 1;
157281  pRtree->base.pModule = &rtreeModule;
157282  pRtree->zDb = (char *)&pRtree[1];
157283  pRtree->zName = &pRtree->zDb[nDb+1];
157284  pRtree->nDim = (argc-4)/2;
157285  pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
157286  pRtree->eCoordType = eCoordType;
157287  memcpy(pRtree->zDb, argv[1], nDb);
157288  memcpy(pRtree->zName, argv[2], nName);
157289
157290  /* Figure out the node size to use. */
157291  rc = getNodeSize(db, pRtree, isCreate, pzErr);
157292
157293  /* Create/Connect to the underlying relational database schema. If
157294  ** that is successful, call sqlite3_declare_vtab() to configure
157295  ** the r-tree table schema.
157296  */
157297  if( rc==SQLITE_OK ){
157298    if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
157299      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
157300    }else{
157301      char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
157302      char *zTmp;
157303      int ii;
157304      for(ii=4; zSql && ii<argc; ii++){
157305        zTmp = zSql;
157306        zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
157307        sqlite3_free(zTmp);
157308      }
157309      if( zSql ){
157310        zTmp = zSql;
157311        zSql = sqlite3_mprintf("%s);", zTmp);
157312        sqlite3_free(zTmp);
157313      }
157314      if( !zSql ){
157315        rc = SQLITE_NOMEM;
157316      }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
157317        *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
157318      }
157319      sqlite3_free(zSql);
157320    }
157321  }
157322
157323  if( rc==SQLITE_OK ){
157324    *ppVtab = (sqlite3_vtab *)pRtree;
157325  }else{
157326    assert( *ppVtab==0 );
157327    assert( pRtree->nBusy==1 );
157328    rtreeRelease(pRtree);
157329  }
157330  return rc;
157331}
157332
157333
157334/*
157335** Implementation of a scalar function that decodes r-tree nodes to
157336** human readable strings. This can be used for debugging and analysis.
157337**
157338** The scalar function takes two arguments: (1) the number of dimensions
157339** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
157340** an r-tree node.  For a two-dimensional r-tree structure called "rt", to
157341** deserialize all nodes, a statement like:
157342**
157343**   SELECT rtreenode(2, data) FROM rt_node;
157344**
157345** The human readable string takes the form of a Tcl list with one
157346** entry for each cell in the r-tree node. Each entry is itself a
157347** list, containing the 8-byte rowid/pageno followed by the
157348** <num-dimension>*2 coordinates.
157349*/
157350static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
157351  char *zText = 0;
157352  RtreeNode node;
157353  Rtree tree;
157354  int ii;
157355
157356  UNUSED_PARAMETER(nArg);
157357  memset(&node, 0, sizeof(RtreeNode));
157358  memset(&tree, 0, sizeof(Rtree));
157359  tree.nDim = sqlite3_value_int(apArg[0]);
157360  tree.nBytesPerCell = 8 + 8 * tree.nDim;
157361  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
157362
157363  for(ii=0; ii<NCELL(&node); ii++){
157364    char zCell[512];
157365    int nCell = 0;
157366    RtreeCell cell;
157367    int jj;
157368
157369    nodeGetCell(&tree, &node, ii, &cell);
157370    sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
157371    nCell = (int)strlen(zCell);
157372    for(jj=0; jj<tree.nDim*2; jj++){
157373#ifndef SQLITE_RTREE_INT_ONLY
157374      sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
157375                       (double)cell.aCoord[jj].f);
157376#else
157377      sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
157378                       cell.aCoord[jj].i);
157379#endif
157380      nCell = (int)strlen(zCell);
157381    }
157382
157383    if( zText ){
157384      char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
157385      sqlite3_free(zText);
157386      zText = zTextNew;
157387    }else{
157388      zText = sqlite3_mprintf("{%s}", zCell);
157389    }
157390  }
157391
157392  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
157393}
157394
157395/* This routine implements an SQL function that returns the "depth" parameter
157396** from the front of a blob that is an r-tree node.  For example:
157397**
157398**     SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
157399**
157400** The depth value is 0 for all nodes other than the root node, and the root
157401** node always has nodeno=1, so the example above is the primary use for this
157402** routine.  This routine is intended for testing and analysis only.
157403*/
157404static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
157405  UNUSED_PARAMETER(nArg);
157406  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
157407   || sqlite3_value_bytes(apArg[0])<2
157408  ){
157409    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
157410  }else{
157411    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
157412    sqlite3_result_int(ctx, readInt16(zBlob));
157413  }
157414}
157415
157416/*
157417** Register the r-tree module with database handle db. This creates the
157418** virtual table module "rtree" and the debugging/analysis scalar
157419** function "rtreenode".
157420*/
157421SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
157422  const int utf8 = SQLITE_UTF8;
157423  int rc;
157424
157425  rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
157426  if( rc==SQLITE_OK ){
157427    rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
157428  }
157429  if( rc==SQLITE_OK ){
157430#ifdef SQLITE_RTREE_INT_ONLY
157431    void *c = (void *)RTREE_COORD_INT32;
157432#else
157433    void *c = (void *)RTREE_COORD_REAL32;
157434#endif
157435    rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
157436  }
157437  if( rc==SQLITE_OK ){
157438    void *c = (void *)RTREE_COORD_INT32;
157439    rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
157440  }
157441
157442  return rc;
157443}
157444
157445/*
157446** This routine deletes the RtreeGeomCallback object that was attached
157447** one of the SQL functions create by sqlite3_rtree_geometry_callback()
157448** or sqlite3_rtree_query_callback().  In other words, this routine is the
157449** destructor for an RtreeGeomCallback objecct.  This routine is called when
157450** the corresponding SQL function is deleted.
157451*/
157452static void rtreeFreeCallback(void *p){
157453  RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
157454  if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
157455  sqlite3_free(p);
157456}
157457
157458/*
157459** This routine frees the BLOB that is returned by geomCallback().
157460*/
157461static void rtreeMatchArgFree(void *pArg){
157462  int i;
157463  RtreeMatchArg *p = (RtreeMatchArg*)pArg;
157464  for(i=0; i<p->nParam; i++){
157465    sqlite3_value_free(p->apSqlParam[i]);
157466  }
157467  sqlite3_free(p);
157468}
157469
157470/*
157471** Each call to sqlite3_rtree_geometry_callback() or
157472** sqlite3_rtree_query_callback() creates an ordinary SQLite
157473** scalar function that is implemented by this routine.
157474**
157475** All this function does is construct an RtreeMatchArg object that
157476** contains the geometry-checking callback routines and a list of
157477** parameters to this function, then return that RtreeMatchArg object
157478** as a BLOB.
157479**
157480** The R-Tree MATCH operator will read the returned BLOB, deserialize
157481** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
157482** out which elements of the R-Tree should be returned by the query.
157483*/
157484static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
157485  RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
157486  RtreeMatchArg *pBlob;
157487  int nBlob;
157488  int memErr = 0;
157489
157490  nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
157491           + nArg*sizeof(sqlite3_value*);
157492  pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
157493  if( !pBlob ){
157494    sqlite3_result_error_nomem(ctx);
157495  }else{
157496    int i;
157497    pBlob->magic = RTREE_GEOMETRY_MAGIC;
157498    pBlob->cb = pGeomCtx[0];
157499    pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
157500    pBlob->nParam = nArg;
157501    for(i=0; i<nArg; i++){
157502      pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
157503      if( pBlob->apSqlParam[i]==0 ) memErr = 1;
157504#ifdef SQLITE_RTREE_INT_ONLY
157505      pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
157506#else
157507      pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
157508#endif
157509    }
157510    if( memErr ){
157511      sqlite3_result_error_nomem(ctx);
157512      rtreeMatchArgFree(pBlob);
157513    }else{
157514      sqlite3_result_blob(ctx, pBlob, nBlob, rtreeMatchArgFree);
157515    }
157516  }
157517}
157518
157519/*
157520** Register a new geometry function for use with the r-tree MATCH operator.
157521*/
157522SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
157523  sqlite3 *db,                  /* Register SQL function on this connection */
157524  const char *zGeom,            /* Name of the new SQL function */
157525  int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
157526  void *pContext                /* Extra data associated with the callback */
157527){
157528  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
157529
157530  /* Allocate and populate the context object. */
157531  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
157532  if( !pGeomCtx ) return SQLITE_NOMEM;
157533  pGeomCtx->xGeom = xGeom;
157534  pGeomCtx->xQueryFunc = 0;
157535  pGeomCtx->xDestructor = 0;
157536  pGeomCtx->pContext = pContext;
157537  return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
157538      (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
157539  );
157540}
157541
157542/*
157543** Register a new 2nd-generation geometry function for use with the
157544** r-tree MATCH operator.
157545*/
157546SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
157547  sqlite3 *db,                 /* Register SQL function on this connection */
157548  const char *zQueryFunc,      /* Name of new SQL function */
157549  int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
157550  void *pContext,              /* Extra data passed into the callback */
157551  void (*xDestructor)(void*)   /* Destructor for the extra data */
157552){
157553  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
157554
157555  /* Allocate and populate the context object. */
157556  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
157557  if( !pGeomCtx ) return SQLITE_NOMEM;
157558  pGeomCtx->xGeom = 0;
157559  pGeomCtx->xQueryFunc = xQueryFunc;
157560  pGeomCtx->xDestructor = xDestructor;
157561  pGeomCtx->pContext = pContext;
157562  return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
157563      (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
157564  );
157565}
157566
157567#if !SQLITE_CORE
157568#ifdef _WIN32
157569__declspec(dllexport)
157570#endif
157571SQLITE_API int SQLITE_STDCALL sqlite3_rtree_init(
157572  sqlite3 *db,
157573  char **pzErrMsg,
157574  const sqlite3_api_routines *pApi
157575){
157576  SQLITE_EXTENSION_INIT2(pApi)
157577  return sqlite3RtreeInit(db);
157578}
157579#endif
157580
157581#endif
157582
157583/************** End of rtree.c ***********************************************/
157584/************** Begin file icu.c *********************************************/
157585/*
157586** 2007 May 6
157587**
157588** The author disclaims copyright to this source code.  In place of
157589** a legal notice, here is a blessing:
157590**
157591**    May you do good and not evil.
157592**    May you find forgiveness for yourself and forgive others.
157593**    May you share freely, never taking more than you give.
157594**
157595*************************************************************************
157596** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
157597**
157598** This file implements an integration between the ICU library
157599** ("International Components for Unicode", an open-source library
157600** for handling unicode data) and SQLite. The integration uses
157601** ICU to provide the following to SQLite:
157602**
157603**   * An implementation of the SQL regexp() function (and hence REGEXP
157604**     operator) using the ICU uregex_XX() APIs.
157605**
157606**   * Implementations of the SQL scalar upper() and lower() functions
157607**     for case mapping.
157608**
157609**   * Integration of ICU and SQLite collation sequences.
157610**
157611**   * An implementation of the LIKE operator that uses ICU to
157612**     provide case-independent matching.
157613*/
157614
157615#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
157616
157617/* Include ICU headers */
157618#include <unicode/utypes.h>
157619#include <unicode/uregex.h>
157620#include <unicode/ustring.h>
157621#include <unicode/ucol.h>
157622
157623/* #include <assert.h> */
157624
157625#ifndef SQLITE_CORE
157626/*   #include "sqlite3ext.h" */
157627  SQLITE_EXTENSION_INIT1
157628#else
157629/*   #include "sqlite3.h" */
157630#endif
157631
157632/*
157633** Maximum length (in bytes) of the pattern in a LIKE or GLOB
157634** operator.
157635*/
157636#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
157637# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
157638#endif
157639
157640/*
157641** Version of sqlite3_free() that is always a function, never a macro.
157642*/
157643static void xFree(void *p){
157644  sqlite3_free(p);
157645}
157646
157647/*
157648** Compare two UTF-8 strings for equality where the first string is
157649** a "LIKE" expression. Return true (1) if they are the same and
157650** false (0) if they are different.
157651*/
157652static int icuLikeCompare(
157653  const uint8_t *zPattern,   /* LIKE pattern */
157654  const uint8_t *zString,    /* The UTF-8 string to compare against */
157655  const UChar32 uEsc         /* The escape character */
157656){
157657  static const int MATCH_ONE = (UChar32)'_';
157658  static const int MATCH_ALL = (UChar32)'%';
157659
157660  int iPattern = 0;       /* Current byte index in zPattern */
157661  int iString = 0;        /* Current byte index in zString */
157662
157663  int prevEscape = 0;     /* True if the previous character was uEsc */
157664
157665  while( zPattern[iPattern]!=0 ){
157666
157667    /* Read (and consume) the next character from the input pattern. */
157668    UChar32 uPattern;
157669    U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
157670
157671    /* There are now 4 possibilities:
157672    **
157673    **     1. uPattern is an unescaped match-all character "%",
157674    **     2. uPattern is an unescaped match-one character "_",
157675    **     3. uPattern is an unescaped escape character, or
157676    **     4. uPattern is to be handled as an ordinary character
157677    */
157678    if( !prevEscape && uPattern==MATCH_ALL ){
157679      /* Case 1. */
157680      uint8_t c;
157681
157682      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
157683      ** MATCH_ALL. For each MATCH_ONE, skip one character in the
157684      ** test string.
157685      */
157686      while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
157687        if( c==MATCH_ONE ){
157688          if( zString[iString]==0 ) return 0;
157689          U8_FWD_1_UNSAFE(zString, iString);
157690        }
157691        iPattern++;
157692      }
157693
157694      if( zPattern[iPattern]==0 ) return 1;
157695
157696      while( zString[iString] ){
157697        if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
157698          return 1;
157699        }
157700        U8_FWD_1_UNSAFE(zString, iString);
157701      }
157702      return 0;
157703
157704    }else if( !prevEscape && uPattern==MATCH_ONE ){
157705      /* Case 2. */
157706      if( zString[iString]==0 ) return 0;
157707      U8_FWD_1_UNSAFE(zString, iString);
157708
157709    }else if( !prevEscape && uPattern==uEsc){
157710      /* Case 3. */
157711      prevEscape = 1;
157712
157713    }else{
157714      /* Case 4. */
157715      UChar32 uString;
157716      U8_NEXT_UNSAFE(zString, iString, uString);
157717      uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
157718      uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
157719      if( uString!=uPattern ){
157720        return 0;
157721      }
157722      prevEscape = 0;
157723    }
157724  }
157725
157726  return zString[iString]==0;
157727}
157728
157729/*
157730** Implementation of the like() SQL function.  This function implements
157731** the build-in LIKE operator.  The first argument to the function is the
157732** pattern and the second argument is the string.  So, the SQL statements:
157733**
157734**       A LIKE B
157735**
157736** is implemented as like(B, A). If there is an escape character E,
157737**
157738**       A LIKE B ESCAPE E
157739**
157740** is mapped to like(B, A, E).
157741*/
157742static void icuLikeFunc(
157743  sqlite3_context *context,
157744  int argc,
157745  sqlite3_value **argv
157746){
157747  const unsigned char *zA = sqlite3_value_text(argv[0]);
157748  const unsigned char *zB = sqlite3_value_text(argv[1]);
157749  UChar32 uEsc = 0;
157750
157751  /* Limit the length of the LIKE or GLOB pattern to avoid problems
157752  ** of deep recursion and N*N behavior in patternCompare().
157753  */
157754  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
157755    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
157756    return;
157757  }
157758
157759
157760  if( argc==3 ){
157761    /* The escape character string must consist of a single UTF-8 character.
157762    ** Otherwise, return an error.
157763    */
157764    int nE= sqlite3_value_bytes(argv[2]);
157765    const unsigned char *zE = sqlite3_value_text(argv[2]);
157766    int i = 0;
157767    if( zE==0 ) return;
157768    U8_NEXT(zE, i, nE, uEsc);
157769    if( i!=nE){
157770      sqlite3_result_error(context,
157771          "ESCAPE expression must be a single character", -1);
157772      return;
157773    }
157774  }
157775
157776  if( zA && zB ){
157777    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
157778  }
157779}
157780
157781/*
157782** This function is called when an ICU function called from within
157783** the implementation of an SQL scalar function returns an error.
157784**
157785** The scalar function context passed as the first argument is
157786** loaded with an error message based on the following two args.
157787*/
157788static void icuFunctionError(
157789  sqlite3_context *pCtx,       /* SQLite scalar function context */
157790  const char *zName,           /* Name of ICU function that failed */
157791  UErrorCode e                 /* Error code returned by ICU function */
157792){
157793  char zBuf[128];
157794  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
157795  zBuf[127] = '\0';
157796  sqlite3_result_error(pCtx, zBuf, -1);
157797}
157798
157799/*
157800** Function to delete compiled regexp objects. Registered as
157801** a destructor function with sqlite3_set_auxdata().
157802*/
157803static void icuRegexpDelete(void *p){
157804  URegularExpression *pExpr = (URegularExpression *)p;
157805  uregex_close(pExpr);
157806}
157807
157808/*
157809** Implementation of SQLite REGEXP operator. This scalar function takes
157810** two arguments. The first is a regular expression pattern to compile
157811** the second is a string to match against that pattern. If either
157812** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
157813** is 1 if the string matches the pattern, or 0 otherwise.
157814**
157815** SQLite maps the regexp() function to the regexp() operator such
157816** that the following two are equivalent:
157817**
157818**     zString REGEXP zPattern
157819**     regexp(zPattern, zString)
157820**
157821** Uses the following ICU regexp APIs:
157822**
157823**     uregex_open()
157824**     uregex_matches()
157825**     uregex_close()
157826*/
157827static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
157828  UErrorCode status = U_ZERO_ERROR;
157829  URegularExpression *pExpr;
157830  UBool res;
157831  const UChar *zString = sqlite3_value_text16(apArg[1]);
157832
157833  (void)nArg;  /* Unused parameter */
157834
157835  /* If the left hand side of the regexp operator is NULL,
157836  ** then the result is also NULL.
157837  */
157838  if( !zString ){
157839    return;
157840  }
157841
157842  pExpr = sqlite3_get_auxdata(p, 0);
157843  if( !pExpr ){
157844    const UChar *zPattern = sqlite3_value_text16(apArg[0]);
157845    if( !zPattern ){
157846      return;
157847    }
157848    pExpr = uregex_open(zPattern, -1, 0, 0, &status);
157849
157850    if( U_SUCCESS(status) ){
157851      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
157852    }else{
157853      assert(!pExpr);
157854      icuFunctionError(p, "uregex_open", status);
157855      return;
157856    }
157857  }
157858
157859  /* Configure the text that the regular expression operates on. */
157860  uregex_setText(pExpr, zString, -1, &status);
157861  if( !U_SUCCESS(status) ){
157862    icuFunctionError(p, "uregex_setText", status);
157863    return;
157864  }
157865
157866  /* Attempt the match */
157867  res = uregex_matches(pExpr, 0, &status);
157868  if( !U_SUCCESS(status) ){
157869    icuFunctionError(p, "uregex_matches", status);
157870    return;
157871  }
157872
157873  /* Set the text that the regular expression operates on to a NULL
157874  ** pointer. This is not really necessary, but it is tidier than
157875  ** leaving the regular expression object configured with an invalid
157876  ** pointer after this function returns.
157877  */
157878  uregex_setText(pExpr, 0, 0, &status);
157879
157880  /* Return 1 or 0. */
157881  sqlite3_result_int(p, res ? 1 : 0);
157882}
157883
157884/*
157885** Implementations of scalar functions for case mapping - upper() and
157886** lower(). Function upper() converts its input to upper-case (ABC).
157887** Function lower() converts to lower-case (abc).
157888**
157889** ICU provides two types of case mapping, "general" case mapping and
157890** "language specific". Refer to ICU documentation for the differences
157891** between the two.
157892**
157893** To utilise "general" case mapping, the upper() or lower() scalar
157894** functions are invoked with one argument:
157895**
157896**     upper('ABC') -> 'abc'
157897**     lower('abc') -> 'ABC'
157898**
157899** To access ICU "language specific" case mapping, upper() or lower()
157900** should be invoked with two arguments. The second argument is the name
157901** of the locale to use. Passing an empty string ("") or SQL NULL value
157902** as the second argument is the same as invoking the 1 argument version
157903** of upper() or lower().
157904**
157905**     lower('I', 'en_us') -> 'i'
157906**     lower('I', 'tr_tr') -> 'ı' (small dotless i)
157907**
157908** http://www.icu-project.org/userguide/posix.html#case_mappings
157909*/
157910static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
157911  const UChar *zInput;
157912  UChar *zOutput;
157913  int nInput;
157914  int nOutput;
157915
157916  UErrorCode status = U_ZERO_ERROR;
157917  const char *zLocale = 0;
157918
157919  assert(nArg==1 || nArg==2);
157920  if( nArg==2 ){
157921    zLocale = (const char *)sqlite3_value_text(apArg[1]);
157922  }
157923
157924  zInput = sqlite3_value_text16(apArg[0]);
157925  if( !zInput ){
157926    return;
157927  }
157928  nInput = sqlite3_value_bytes16(apArg[0]);
157929
157930  nOutput = nInput * 2 + 2;
157931  zOutput = sqlite3_malloc(nOutput);
157932  if( !zOutput ){
157933    return;
157934  }
157935
157936  if( sqlite3_user_data(p) ){
157937    u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
157938  }else{
157939    u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
157940  }
157941
157942  if( !U_SUCCESS(status) ){
157943    icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
157944    return;
157945  }
157946
157947  sqlite3_result_text16(p, zOutput, -1, xFree);
157948}
157949
157950/*
157951** Collation sequence destructor function. The pCtx argument points to
157952** a UCollator structure previously allocated using ucol_open().
157953*/
157954static void icuCollationDel(void *pCtx){
157955  UCollator *p = (UCollator *)pCtx;
157956  ucol_close(p);
157957}
157958
157959/*
157960** Collation sequence comparison function. The pCtx argument points to
157961** a UCollator structure previously allocated using ucol_open().
157962*/
157963static int icuCollationColl(
157964  void *pCtx,
157965  int nLeft,
157966  const void *zLeft,
157967  int nRight,
157968  const void *zRight
157969){
157970  UCollationResult res;
157971  UCollator *p = (UCollator *)pCtx;
157972  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
157973  switch( res ){
157974    case UCOL_LESS:    return -1;
157975    case UCOL_GREATER: return +1;
157976    case UCOL_EQUAL:   return 0;
157977  }
157978  assert(!"Unexpected return value from ucol_strcoll()");
157979  return 0;
157980}
157981
157982/*
157983** Implementation of the scalar function icu_load_collation().
157984**
157985** This scalar function is used to add ICU collation based collation
157986** types to an SQLite database connection. It is intended to be called
157987** as follows:
157988**
157989**     SELECT icu_load_collation(<locale>, <collation-name>);
157990**
157991** Where <locale> is a string containing an ICU locale identifier (i.e.
157992** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
157993** collation sequence to create.
157994*/
157995static void icuLoadCollation(
157996  sqlite3_context *p,
157997  int nArg,
157998  sqlite3_value **apArg
157999){
158000  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
158001  UErrorCode status = U_ZERO_ERROR;
158002  const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
158003  const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
158004  UCollator *pUCollator;    /* ICU library collation object */
158005  int rc;                   /* Return code from sqlite3_create_collation_x() */
158006
158007  assert(nArg==2);
158008  (void)nArg; /* Unused parameter */
158009  zLocale = (const char *)sqlite3_value_text(apArg[0]);
158010  zName = (const char *)sqlite3_value_text(apArg[1]);
158011
158012  if( !zLocale || !zName ){
158013    return;
158014  }
158015
158016  pUCollator = ucol_open(zLocale, &status);
158017  if( !U_SUCCESS(status) ){
158018    icuFunctionError(p, "ucol_open", status);
158019    return;
158020  }
158021  assert(p);
158022
158023  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
158024      icuCollationColl, icuCollationDel
158025  );
158026  if( rc!=SQLITE_OK ){
158027    ucol_close(pUCollator);
158028    sqlite3_result_error(p, "Error registering collation function", -1);
158029  }
158030}
158031
158032/*
158033** Register the ICU extension functions with database db.
158034*/
158035SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
158036  struct IcuScalar {
158037    const char *zName;                        /* Function name */
158038    int nArg;                                 /* Number of arguments */
158039    int enc;                                  /* Optimal text encoding */
158040    void *pContext;                           /* sqlite3_user_data() context */
158041    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
158042  } scalars[] = {
158043    {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
158044
158045    {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
158046    {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
158047    {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
158048    {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
158049
158050    {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
158051    {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
158052    {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
158053    {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
158054
158055    {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
158056    {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
158057
158058    {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
158059  };
158060
158061  int rc = SQLITE_OK;
158062  int i;
158063
158064  for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
158065    struct IcuScalar *p = &scalars[i];
158066    rc = sqlite3_create_function(
158067        db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
158068    );
158069  }
158070
158071  return rc;
158072}
158073
158074#if !SQLITE_CORE
158075#ifdef _WIN32
158076__declspec(dllexport)
158077#endif
158078SQLITE_API int SQLITE_STDCALL sqlite3_icu_init(
158079  sqlite3 *db,
158080  char **pzErrMsg,
158081  const sqlite3_api_routines *pApi
158082){
158083  SQLITE_EXTENSION_INIT2(pApi)
158084  return sqlite3IcuInit(db);
158085}
158086#endif
158087
158088#endif
158089
158090/************** End of icu.c *************************************************/
158091/************** Begin file fts3_icu.c ****************************************/
158092/*
158093** 2007 June 22
158094**
158095** The author disclaims copyright to this source code.  In place of
158096** a legal notice, here is a blessing:
158097**
158098**    May you do good and not evil.
158099**    May you find forgiveness for yourself and forgive others.
158100**    May you share freely, never taking more than you give.
158101**
158102*************************************************************************
158103** This file implements a tokenizer for fts3 based on the ICU library.
158104*/
158105/* #include "fts3Int.h" */
158106#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
158107#ifdef SQLITE_ENABLE_ICU
158108
158109/* #include <assert.h> */
158110/* #include <string.h> */
158111/* #include "fts3_tokenizer.h" */
158112
158113#include <unicode/ubrk.h>
158114/* #include <unicode/ucol.h> */
158115/* #include <unicode/ustring.h> */
158116#include <unicode/utf16.h>
158117
158118typedef struct IcuTokenizer IcuTokenizer;
158119typedef struct IcuCursor IcuCursor;
158120
158121struct IcuTokenizer {
158122  sqlite3_tokenizer base;
158123  char *zLocale;
158124};
158125
158126struct IcuCursor {
158127  sqlite3_tokenizer_cursor base;
158128
158129  UBreakIterator *pIter;      /* ICU break-iterator object */
158130  int nChar;                  /* Number of UChar elements in pInput */
158131  UChar *aChar;               /* Copy of input using utf-16 encoding */
158132  int *aOffset;               /* Offsets of each character in utf-8 input */
158133
158134  int nBuffer;
158135  char *zBuffer;
158136
158137  int iToken;
158138};
158139
158140/*
158141** Create a new tokenizer instance.
158142*/
158143static int icuCreate(
158144  int argc,                            /* Number of entries in argv[] */
158145  const char * const *argv,            /* Tokenizer creation arguments */
158146  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
158147){
158148  IcuTokenizer *p;
158149  int n = 0;
158150
158151  if( argc>0 ){
158152    n = strlen(argv[0])+1;
158153  }
158154  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
158155  if( !p ){
158156    return SQLITE_NOMEM;
158157  }
158158  memset(p, 0, sizeof(IcuTokenizer));
158159
158160  if( n ){
158161    p->zLocale = (char *)&p[1];
158162    memcpy(p->zLocale, argv[0], n);
158163  }
158164
158165  *ppTokenizer = (sqlite3_tokenizer *)p;
158166
158167  return SQLITE_OK;
158168}
158169
158170/*
158171** Destroy a tokenizer
158172*/
158173static int icuDestroy(sqlite3_tokenizer *pTokenizer){
158174  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
158175  sqlite3_free(p);
158176  return SQLITE_OK;
158177}
158178
158179/*
158180** Prepare to begin tokenizing a particular string.  The input
158181** string to be tokenized is pInput[0..nBytes-1].  A cursor
158182** used to incrementally tokenize this string is returned in
158183** *ppCursor.
158184*/
158185static int icuOpen(
158186  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
158187  const char *zInput,                    /* Input string */
158188  int nInput,                            /* Length of zInput in bytes */
158189  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
158190){
158191  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
158192  IcuCursor *pCsr;
158193
158194  const int32_t opt = U_FOLD_CASE_DEFAULT;
158195  UErrorCode status = U_ZERO_ERROR;
158196  int nChar;
158197
158198  UChar32 c;
158199  int iInput = 0;
158200  int iOut = 0;
158201
158202  *ppCursor = 0;
158203
158204  if( zInput==0 ){
158205    nInput = 0;
158206    zInput = "";
158207  }else if( nInput<0 ){
158208    nInput = strlen(zInput);
158209  }
158210  nChar = nInput+1;
158211  pCsr = (IcuCursor *)sqlite3_malloc(
158212      sizeof(IcuCursor) +                /* IcuCursor */
158213      ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
158214      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
158215  );
158216  if( !pCsr ){
158217    return SQLITE_NOMEM;
158218  }
158219  memset(pCsr, 0, sizeof(IcuCursor));
158220  pCsr->aChar = (UChar *)&pCsr[1];
158221  pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
158222
158223  pCsr->aOffset[iOut] = iInput;
158224  U8_NEXT(zInput, iInput, nInput, c);
158225  while( c>0 ){
158226    int isError = 0;
158227    c = u_foldCase(c, opt);
158228    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
158229    if( isError ){
158230      sqlite3_free(pCsr);
158231      return SQLITE_ERROR;
158232    }
158233    pCsr->aOffset[iOut] = iInput;
158234
158235    if( iInput<nInput ){
158236      U8_NEXT(zInput, iInput, nInput, c);
158237    }else{
158238      c = 0;
158239    }
158240  }
158241
158242  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
158243  if( !U_SUCCESS(status) ){
158244    sqlite3_free(pCsr);
158245    return SQLITE_ERROR;
158246  }
158247  pCsr->nChar = iOut;
158248
158249  ubrk_first(pCsr->pIter);
158250  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
158251  return SQLITE_OK;
158252}
158253
158254/*
158255** Close a tokenization cursor previously opened by a call to icuOpen().
158256*/
158257static int icuClose(sqlite3_tokenizer_cursor *pCursor){
158258  IcuCursor *pCsr = (IcuCursor *)pCursor;
158259  ubrk_close(pCsr->pIter);
158260  sqlite3_free(pCsr->zBuffer);
158261  sqlite3_free(pCsr);
158262  return SQLITE_OK;
158263}
158264
158265/*
158266** Extract the next token from a tokenization cursor.
158267*/
158268static int icuNext(
158269  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
158270  const char **ppToken,               /* OUT: *ppToken is the token text */
158271  int *pnBytes,                       /* OUT: Number of bytes in token */
158272  int *piStartOffset,                 /* OUT: Starting offset of token */
158273  int *piEndOffset,                   /* OUT: Ending offset of token */
158274  int *piPosition                     /* OUT: Position integer of token */
158275){
158276  IcuCursor *pCsr = (IcuCursor *)pCursor;
158277
158278  int iStart = 0;
158279  int iEnd = 0;
158280  int nByte = 0;
158281
158282  while( iStart==iEnd ){
158283    UChar32 c;
158284
158285    iStart = ubrk_current(pCsr->pIter);
158286    iEnd = ubrk_next(pCsr->pIter);
158287    if( iEnd==UBRK_DONE ){
158288      return SQLITE_DONE;
158289    }
158290
158291    while( iStart<iEnd ){
158292      int iWhite = iStart;
158293      U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
158294      if( u_isspace(c) ){
158295        iStart = iWhite;
158296      }else{
158297        break;
158298      }
158299    }
158300    assert(iStart<=iEnd);
158301  }
158302
158303  do {
158304    UErrorCode status = U_ZERO_ERROR;
158305    if( nByte ){
158306      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
158307      if( !zNew ){
158308        return SQLITE_NOMEM;
158309      }
158310      pCsr->zBuffer = zNew;
158311      pCsr->nBuffer = nByte;
158312    }
158313
158314    u_strToUTF8(
158315        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
158316        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
158317        &status                                  /* Output success/failure */
158318    );
158319  } while( nByte>pCsr->nBuffer );
158320
158321  *ppToken = pCsr->zBuffer;
158322  *pnBytes = nByte;
158323  *piStartOffset = pCsr->aOffset[iStart];
158324  *piEndOffset = pCsr->aOffset[iEnd];
158325  *piPosition = pCsr->iToken++;
158326
158327  return SQLITE_OK;
158328}
158329
158330/*
158331** The set of routines that implement the simple tokenizer
158332*/
158333static const sqlite3_tokenizer_module icuTokenizerModule = {
158334  0,                           /* iVersion    */
158335  icuCreate,                   /* xCreate     */
158336  icuDestroy,                  /* xCreate     */
158337  icuOpen,                     /* xOpen       */
158338  icuClose,                    /* xClose      */
158339  icuNext,                     /* xNext       */
158340  0,                           /* xLanguageid */
158341};
158342
158343/*
158344** Set *ppModule to point at the implementation of the ICU tokenizer.
158345*/
158346SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
158347  sqlite3_tokenizer_module const**ppModule
158348){
158349  *ppModule = &icuTokenizerModule;
158350}
158351
158352#endif /* defined(SQLITE_ENABLE_ICU) */
158353#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
158354
158355/************** End of fts3_icu.c ********************************************/
158356/************** Begin file sqlite3rbu.c **************************************/
158357/*
158358** 2014 August 30
158359**
158360** The author disclaims copyright to this source code.  In place of
158361** a legal notice, here is a blessing:
158362**
158363**    May you do good and not evil.
158364**    May you find forgiveness for yourself and forgive others.
158365**    May you share freely, never taking more than you give.
158366**
158367*************************************************************************
158368**
158369**
158370** OVERVIEW
158371**
158372**  The RBU extension requires that the RBU update be packaged as an
158373**  SQLite database. The tables it expects to find are described in
158374**  sqlite3rbu.h.  Essentially, for each table xyz in the target database
158375**  that the user wishes to write to, a corresponding data_xyz table is
158376**  created in the RBU database and populated with one row for each row to
158377**  update, insert or delete from the target table.
158378**
158379**  The update proceeds in three stages:
158380**
158381**  1) The database is updated. The modified database pages are written
158382**     to a *-oal file. A *-oal file is just like a *-wal file, except
158383**     that it is named "<database>-oal" instead of "<database>-wal".
158384**     Because regular SQLite clients do not look for file named
158385**     "<database>-oal", they go on using the original database in
158386**     rollback mode while the *-oal file is being generated.
158387**
158388**     During this stage RBU does not update the database by writing
158389**     directly to the target tables. Instead it creates "imposter"
158390**     tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
158391**     to update each b-tree individually. All updates required by each
158392**     b-tree are completed before moving on to the next, and all
158393**     updates are done in sorted key order.
158394**
158395**  2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
158396**     location using a call to rename(2). Before doing this the RBU
158397**     module takes an EXCLUSIVE lock on the database file, ensuring
158398**     that there are no other active readers.
158399**
158400**     Once the EXCLUSIVE lock is released, any other database readers
158401**     detect the new *-wal file and read the database in wal mode. At
158402**     this point they see the new version of the database - including
158403**     the updates made as part of the RBU update.
158404**
158405**  3) The new *-wal file is checkpointed. This proceeds in the same way
158406**     as a regular database checkpoint, except that a single frame is
158407**     checkpointed each time sqlite3rbu_step() is called. If the RBU
158408**     handle is closed before the entire *-wal file is checkpointed,
158409**     the checkpoint progress is saved in the RBU database and the
158410**     checkpoint can be resumed by another RBU client at some point in
158411**     the future.
158412**
158413** POTENTIAL PROBLEMS
158414**
158415**  The rename() call might not be portable. And RBU is not currently
158416**  syncing the directory after renaming the file.
158417**
158418**  When state is saved, any commit to the *-oal file and the commit to
158419**  the RBU update database are not atomic. So if the power fails at the
158420**  wrong moment they might get out of sync. As the main database will be
158421**  committed before the RBU update database this will likely either just
158422**  pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
158423**  constraint violations).
158424**
158425**  If some client does modify the target database mid RBU update, or some
158426**  other error occurs, the RBU extension will keep throwing errors. It's
158427**  not really clear how to get out of this state. The system could just
158428**  by delete the RBU update database and *-oal file and have the device
158429**  download the update again and start over.
158430**
158431**  At present, for an UPDATE, both the new.* and old.* records are
158432**  collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
158433**  fields are collected.  This means we're probably writing a lot more
158434**  data to disk when saving the state of an ongoing update to the RBU
158435**  update database than is strictly necessary.
158436**
158437*/
158438
158439/* #include <assert.h> */
158440/* #include <string.h> */
158441/* #include <stdio.h> */
158442
158443/* #include "sqlite3.h" */
158444
158445#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
158446/************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
158447/************** Begin file sqlite3rbu.h **************************************/
158448/*
158449** 2014 August 30
158450**
158451** The author disclaims copyright to this source code.  In place of
158452** a legal notice, here is a blessing:
158453**
158454**    May you do good and not evil.
158455**    May you find forgiveness for yourself and forgive others.
158456**    May you share freely, never taking more than you give.
158457**
158458*************************************************************************
158459**
158460** This file contains the public interface for the RBU extension.
158461*/
158462
158463/*
158464** SUMMARY
158465**
158466** Writing a transaction containing a large number of operations on
158467** b-tree indexes that are collectively larger than the available cache
158468** memory can be very inefficient.
158469**
158470** The problem is that in order to update a b-tree, the leaf page (at least)
158471** containing the entry being inserted or deleted must be modified. If the
158472** working set of leaves is larger than the available cache memory, then a
158473** single leaf that is modified more than once as part of the transaction
158474** may be loaded from or written to the persistent media multiple times.
158475** Additionally, because the index updates are likely to be applied in
158476** random order, access to pages within the database is also likely to be in
158477** random order, which is itself quite inefficient.
158478**
158479** One way to improve the situation is to sort the operations on each index
158480** by index key before applying them to the b-tree. This leads to an IO
158481** pattern that resembles a single linear scan through the index b-tree,
158482** and all but guarantees each modified leaf page is loaded and stored
158483** exactly once. SQLite uses this trick to improve the performance of
158484** CREATE INDEX commands. This extension allows it to be used to improve
158485** the performance of large transactions on existing databases.
158486**
158487** Additionally, this extension allows the work involved in writing the
158488** large transaction to be broken down into sub-transactions performed
158489** sequentially by separate processes. This is useful if the system cannot
158490** guarantee that a single update process will run for long enough to apply
158491** the entire update, for example because the update is being applied on a
158492** mobile device that is frequently rebooted. Even after the writer process
158493** has committed one or more sub-transactions, other database clients continue
158494** to read from the original database snapshot. In other words, partially
158495** applied transactions are not visible to other clients.
158496**
158497** "RBU" stands for "Resumable Bulk Update". As in a large database update
158498** transmitted via a wireless network to a mobile device. A transaction
158499** applied using this extension is hence refered to as an "RBU update".
158500**
158501**
158502** LIMITATIONS
158503**
158504** An "RBU update" transaction is subject to the following limitations:
158505**
158506**   * The transaction must consist of INSERT, UPDATE and DELETE operations
158507**     only.
158508**
158509**   * INSERT statements may not use any default values.
158510**
158511**   * UPDATE and DELETE statements must identify their target rows by
158512**     non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
158513**     KEY fields may not be updated or deleted. If the table being written
158514**     has no PRIMARY KEY, affected rows must be identified by rowid.
158515**
158516**   * UPDATE statements may not modify PRIMARY KEY columns.
158517**
158518**   * No triggers will be fired.
158519**
158520**   * No foreign key violations are detected or reported.
158521**
158522**   * CHECK constraints are not enforced.
158523**
158524**   * No constraint handling mode except for "OR ROLLBACK" is supported.
158525**
158526**
158527** PREPARATION
158528**
158529** An "RBU update" is stored as a separate SQLite database. A database
158530** containing an RBU update is an "RBU database". For each table in the
158531** target database to be updated, the RBU database should contain a table
158532** named "data_<target name>" containing the same set of columns as the
158533** target table, and one more - "rbu_control". The data_% table should
158534** have no PRIMARY KEY or UNIQUE constraints, but each column should have
158535** the same type as the corresponding column in the target database.
158536** The "rbu_control" column should have no type at all. For example, if
158537** the target database contains:
158538**
158539**   CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
158540**
158541** Then the RBU database should contain:
158542**
158543**   CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
158544**
158545** The order of the columns in the data_% table does not matter.
158546**
158547** Instead of a regular table, the RBU database may also contain virtual
158548** tables or view named using the data_<target> naming scheme.
158549**
158550** Instead of the plain data_<target> naming scheme, RBU database tables
158551** may also be named data<integer>_<target>, where <integer> is any sequence
158552** of zero or more numeric characters (0-9). This can be significant because
158553** tables within the RBU database are always processed in order sorted by
158554** name. By judicious selection of the the <integer> portion of the names
158555** of the RBU tables the user can therefore control the order in which they
158556** are processed. This can be useful, for example, to ensure that "external
158557** content" FTS4 tables are updated before their underlying content tables.
158558**
158559** If the target database table is a virtual table or a table that has no
158560** PRIMARY KEY declaration, the data_% table must also contain a column
158561** named "rbu_rowid". This column is mapped to the tables implicit primary
158562** key column - "rowid". Virtual tables for which the "rowid" column does
158563** not function like a primary key value cannot be updated using RBU. For
158564** example, if the target db contains either of the following:
158565**
158566**   CREATE VIRTUAL TABLE x1 USING fts3(a, b);
158567**   CREATE TABLE x1(a, b)
158568**
158569** then the RBU database should contain:
158570**
158571**   CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
158572**
158573** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
158574** target table must be present in the input table. For virtual tables,
158575** hidden columns are optional - they are updated by RBU if present in
158576** the input table, or not otherwise. For example, to write to an fts4
158577** table with a hidden languageid column such as:
158578**
158579**   CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
158580**
158581** Either of the following input table schemas may be used:
158582**
158583**   CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
158584**   CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
158585**
158586** For each row to INSERT into the target database as part of the RBU
158587** update, the corresponding data_% table should contain a single record
158588** with the "rbu_control" column set to contain integer value 0. The
158589** other columns should be set to the values that make up the new record
158590** to insert.
158591**
158592** If the target database table has an INTEGER PRIMARY KEY, it is not
158593** possible to insert a NULL value into the IPK column. Attempting to
158594** do so results in an SQLITE_MISMATCH error.
158595**
158596** For each row to DELETE from the target database as part of the RBU
158597** update, the corresponding data_% table should contain a single record
158598** with the "rbu_control" column set to contain integer value 1. The
158599** real primary key values of the row to delete should be stored in the
158600** corresponding columns of the data_% table. The values stored in the
158601** other columns are not used.
158602**
158603** For each row to UPDATE from the target database as part of the RBU
158604** update, the corresponding data_% table should contain a single record
158605** with the "rbu_control" column set to contain a value of type text.
158606** The real primary key values identifying the row to update should be
158607** stored in the corresponding columns of the data_% table row, as should
158608** the new values of all columns being update. The text value in the
158609** "rbu_control" column must contain the same number of characters as
158610** there are columns in the target database table, and must consist entirely
158611** of 'x' and '.' characters (or in some special cases 'd' - see below). For
158612** each column that is being updated, the corresponding character is set to
158613** 'x'. For those that remain as they are, the corresponding character of the
158614** rbu_control value should be set to '.'. For example, given the tables
158615** above, the update statement:
158616**
158617**   UPDATE t1 SET c = 'usa' WHERE a = 4;
158618**
158619** is represented by the data_t1 row created by:
158620**
158621**   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
158622**
158623** Instead of an 'x' character, characters of the rbu_control value specified
158624** for UPDATEs may also be set to 'd'. In this case, instead of updating the
158625** target table with the value stored in the corresponding data_% column, the
158626** user-defined SQL function "rbu_delta()" is invoked and the result stored in
158627** the target table column. rbu_delta() is invoked with two arguments - the
158628** original value currently stored in the target table column and the
158629** value specified in the data_xxx table.
158630**
158631** For example, this row:
158632**
158633**   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
158634**
158635** is similar to an UPDATE statement such as:
158636**
158637**   UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
158638**
158639** Finally, if an 'f' character appears in place of a 'd' or 's' in an
158640** ota_control string, the contents of the data_xxx table column is assumed
158641** to be a "fossil delta" - a patch to be applied to a blob value in the
158642** format used by the fossil source-code management system. In this case
158643** the existing value within the target database table must be of type BLOB.
158644** It is replaced by the result of applying the specified fossil delta to
158645** itself.
158646**
158647** If the target database table is a virtual table or a table with no PRIMARY
158648** KEY, the rbu_control value should not include a character corresponding
158649** to the rbu_rowid value. For example, this:
158650**
158651**   INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
158652**       VALUES(NULL, 'usa', 12, '.x');
158653**
158654** causes a result similar to:
158655**
158656**   UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
158657**
158658** The data_xxx tables themselves should have no PRIMARY KEY declarations.
158659** However, RBU is more efficient if reading the rows in from each data_xxx
158660** table in "rowid" order is roughly the same as reading them sorted by
158661** the PRIMARY KEY of the corresponding target database table. In other
158662** words, rows should be sorted using the destination table PRIMARY KEY
158663** fields before they are inserted into the data_xxx tables.
158664**
158665** USAGE
158666**
158667** The API declared below allows an application to apply an RBU update
158668** stored on disk to an existing target database. Essentially, the
158669** application:
158670**
158671**     1) Opens an RBU handle using the sqlite3rbu_open() function.
158672**
158673**     2) Registers any required virtual table modules with the database
158674**        handle returned by sqlite3rbu_db(). Also, if required, register
158675**        the rbu_delta() implementation.
158676**
158677**     3) Calls the sqlite3rbu_step() function one or more times on
158678**        the new handle. Each call to sqlite3rbu_step() performs a single
158679**        b-tree operation, so thousands of calls may be required to apply
158680**        a complete update.
158681**
158682**     4) Calls sqlite3rbu_close() to close the RBU update handle. If
158683**        sqlite3rbu_step() has been called enough times to completely
158684**        apply the update to the target database, then the RBU database
158685**        is marked as fully applied. Otherwise, the state of the RBU
158686**        update application is saved in the RBU database for later
158687**        resumption.
158688**
158689** See comments below for more detail on APIs.
158690**
158691** If an update is only partially applied to the target database by the
158692** time sqlite3rbu_close() is called, various state information is saved
158693** within the RBU database. This allows subsequent processes to automatically
158694** resume the RBU update from where it left off.
158695**
158696** To remove all RBU extension state information, returning an RBU database
158697** to its original contents, it is sufficient to drop all tables that begin
158698** with the prefix "rbu_"
158699**
158700** DATABASE LOCKING
158701**
158702** An RBU update may not be applied to a database in WAL mode. Attempting
158703** to do so is an error (SQLITE_ERROR).
158704**
158705** While an RBU handle is open, a SHARED lock may be held on the target
158706** database file. This means it is possible for other clients to read the
158707** database, but not to write it.
158708**
158709** If an RBU update is started and then suspended before it is completed,
158710** then an external client writes to the database, then attempting to resume
158711** the suspended RBU update is also an error (SQLITE_BUSY).
158712*/
158713
158714#ifndef _SQLITE3RBU_H
158715#define _SQLITE3RBU_H
158716
158717/* #include "sqlite3.h"              ** Required for error code definitions ** */
158718
158719#if 0
158720extern "C" {
158721#endif
158722
158723typedef struct sqlite3rbu sqlite3rbu;
158724
158725/*
158726** Open an RBU handle.
158727**
158728** Argument zTarget is the path to the target database. Argument zRbu is
158729** the path to the RBU database. Each call to this function must be matched
158730** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
158731** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
158732** or zRbu begin with "file:", it will be interpreted as an SQLite
158733** database URI, not a regular file name.
158734**
158735** If the zState argument is passed a NULL value, the RBU extension stores
158736** the current state of the update (how many rows have been updated, which
158737** indexes are yet to be updated etc.) within the RBU database itself. This
158738** can be convenient, as it means that the RBU application does not need to
158739** organize removing a separate state file after the update is concluded.
158740** Or, if zState is non-NULL, it must be a path to a database file in which
158741** the RBU extension can store the state of the update.
158742**
158743** When resuming an RBU update, the zState argument must be passed the same
158744** value as when the RBU update was started.
158745**
158746** Once the RBU update is finished, the RBU extension does not
158747** automatically remove any zState database file, even if it created it.
158748**
158749** By default, RBU uses the default VFS to access the files on disk. To
158750** use a VFS other than the default, an SQLite "file:" URI containing a
158751** "vfs=..." option may be passed as the zTarget option.
158752**
158753** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
158754** SQLite's built-in VFSs, including the multiplexor VFS. However it does
158755** not work out of the box with zipvfs. Refer to the comment describing
158756** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
158757*/
158758SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
158759  const char *zTarget,
158760  const char *zRbu,
158761  const char *zState
158762);
158763
158764/*
158765** Internally, each RBU connection uses a separate SQLite database
158766** connection to access the target and rbu update databases. This
158767** API allows the application direct access to these database handles.
158768**
158769** The first argument passed to this function must be a valid, open, RBU
158770** handle. The second argument should be passed zero to access the target
158771** database handle, or non-zero to access the rbu update database handle.
158772** Accessing the underlying database handles may be useful in the
158773** following scenarios:
158774**
158775**   * If any target tables are virtual tables, it may be necessary to
158776**     call sqlite3_create_module() on the target database handle to
158777**     register the required virtual table implementations.
158778**
158779**   * If the data_xxx tables in the RBU source database are virtual
158780**     tables, the application may need to call sqlite3_create_module() on
158781**     the rbu update db handle to any required virtual table
158782**     implementations.
158783**
158784**   * If the application uses the "rbu_delta()" feature described above,
158785**     it must use sqlite3_create_function() or similar to register the
158786**     rbu_delta() implementation with the target database handle.
158787**
158788** If an error has occurred, either while opening or stepping the RBU object,
158789** this function may return NULL. The error code and message may be collected
158790** when sqlite3rbu_close() is called.
158791*/
158792SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3rbu_db(sqlite3rbu*, int bRbu);
158793
158794/*
158795** Do some work towards applying the RBU update to the target db.
158796**
158797** Return SQLITE_DONE if the update has been completely applied, or
158798** SQLITE_OK if no error occurs but there remains work to do to apply
158799** the RBU update. If an error does occur, some other error code is
158800** returned.
158801**
158802** Once a call to sqlite3rbu_step() has returned a value other than
158803** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
158804** that immediately return the same value.
158805*/
158806SQLITE_API int SQLITE_STDCALL sqlite3rbu_step(sqlite3rbu *pRbu);
158807
158808/*
158809** Force RBU to save its state to disk.
158810**
158811** If a power failure or application crash occurs during an update, following
158812** system recovery RBU may resume the update from the point at which the state
158813** was last saved. In other words, from the most recent successful call to
158814** sqlite3rbu_close() or this function.
158815**
158816** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
158817*/
158818SQLITE_API int SQLITE_STDCALL sqlite3rbu_savestate(sqlite3rbu *pRbu);
158819
158820/*
158821** Close an RBU handle.
158822**
158823** If the RBU update has been completely applied, mark the RBU database
158824** as fully applied. Otherwise, assuming no error has occurred, save the
158825** current state of the RBU update appliation to the RBU database.
158826**
158827** If an error has already occurred as part of an sqlite3rbu_step()
158828** or sqlite3rbu_open() call, or if one occurs within this function, an
158829** SQLite error code is returned. Additionally, *pzErrmsg may be set to
158830** point to a buffer containing a utf-8 formatted English language error
158831** message. It is the responsibility of the caller to eventually free any
158832** such buffer using sqlite3_free().
158833**
158834** Otherwise, if no error occurs, this function returns SQLITE_OK if the
158835** update has been partially applied, or SQLITE_DONE if it has been
158836** completely applied.
158837*/
158838SQLITE_API int SQLITE_STDCALL sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
158839
158840/*
158841** Return the total number of key-value operations (inserts, deletes or
158842** updates) that have been performed on the target database since the
158843** current RBU update was started.
158844*/
158845SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3rbu_progress(sqlite3rbu *pRbu);
158846
158847/*
158848** Create an RBU VFS named zName that accesses the underlying file-system
158849** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
158850** then the new RBU VFS uses the default system VFS to access the file-system.
158851** The new object is registered as a non-default VFS with SQLite before
158852** returning.
158853**
158854** Part of the RBU implementation uses a custom VFS object. Usually, this
158855** object is created and deleted automatically by RBU.
158856**
158857** The exception is for applications that also use zipvfs. In this case,
158858** the custom VFS must be explicitly created by the user before the RBU
158859** handle is opened. The RBU VFS should be installed so that the zipvfs
158860** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
158861** (for example multiplexor) to access the file-system. For example,
158862** to assemble an RBU enabled VFS stack that uses both zipvfs and
158863** multiplexor (error checking omitted):
158864**
158865**     // Create a VFS named "multiplex" (not the default).
158866**     sqlite3_multiplex_initialize(0, 0);
158867**
158868**     // Create an rbu VFS named "rbu" that uses multiplexor. If the
158869**     // second argument were replaced with NULL, the "rbu" VFS would
158870**     // access the file-system via the system default VFS, bypassing the
158871**     // multiplexor.
158872**     sqlite3rbu_create_vfs("rbu", "multiplex");
158873**
158874**     // Create a zipvfs VFS named "zipvfs" that uses rbu.
158875**     zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
158876**
158877**     // Make zipvfs the default VFS.
158878**     sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
158879**
158880** Because the default VFS created above includes a RBU functionality, it
158881** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
158882** that does not include the RBU layer results in an error.
158883**
158884** The overhead of adding the "rbu" VFS to the system is negligible for
158885** non-RBU users. There is no harm in an application accessing the
158886** file-system via "rbu" all the time, even if it only uses RBU functionality
158887** occasionally.
158888*/
158889SQLITE_API int SQLITE_STDCALL sqlite3rbu_create_vfs(const char *zName, const char *zParent);
158890
158891/*
158892** Deregister and destroy an RBU vfs created by an earlier call to
158893** sqlite3rbu_create_vfs().
158894**
158895** VFS objects are not reference counted. If a VFS object is destroyed
158896** before all database handles that use it have been closed, the results
158897** are undefined.
158898*/
158899SQLITE_API void SQLITE_STDCALL sqlite3rbu_destroy_vfs(const char *zName);
158900
158901#if 0
158902}  /* end of the 'extern "C"' block */
158903#endif
158904
158905#endif /* _SQLITE3RBU_H */
158906
158907/************** End of sqlite3rbu.h ******************************************/
158908/************** Continuing where we left off in sqlite3rbu.c *****************/
158909
158910#if defined(_WIN32_WCE)
158911/* #include "windows.h" */
158912#endif
158913
158914/* Maximum number of prepared UPDATE statements held by this module */
158915#define SQLITE_RBU_UPDATE_CACHESIZE 16
158916
158917/*
158918** Swap two objects of type TYPE.
158919*/
158920#if !defined(SQLITE_AMALGAMATION)
158921# define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
158922#endif
158923
158924/*
158925** The rbu_state table is used to save the state of a partially applied
158926** update so that it can be resumed later. The table consists of integer
158927** keys mapped to values as follows:
158928**
158929** RBU_STATE_STAGE:
158930**   May be set to integer values 1, 2, 4 or 5. As follows:
158931**       1: the *-rbu file is currently under construction.
158932**       2: the *-rbu file has been constructed, but not yet moved
158933**          to the *-wal path.
158934**       4: the checkpoint is underway.
158935**       5: the rbu update has been checkpointed.
158936**
158937** RBU_STATE_TBL:
158938**   Only valid if STAGE==1. The target database name of the table
158939**   currently being written.
158940**
158941** RBU_STATE_IDX:
158942**   Only valid if STAGE==1. The target database name of the index
158943**   currently being written, or NULL if the main table is currently being
158944**   updated.
158945**
158946** RBU_STATE_ROW:
158947**   Only valid if STAGE==1. Number of rows already processed for the current
158948**   table/index.
158949**
158950** RBU_STATE_PROGRESS:
158951**   Trbul number of sqlite3rbu_step() calls made so far as part of this
158952**   rbu update.
158953**
158954** RBU_STATE_CKPT:
158955**   Valid if STAGE==4. The 64-bit checksum associated with the wal-index
158956**   header created by recovering the *-wal file. This is used to detect
158957**   cases when another client appends frames to the *-wal file in the
158958**   middle of an incremental checkpoint (an incremental checkpoint cannot
158959**   be continued if this happens).
158960**
158961** RBU_STATE_COOKIE:
158962**   Valid if STAGE==1. The current change-counter cookie value in the
158963**   target db file.
158964**
158965** RBU_STATE_OALSZ:
158966**   Valid if STAGE==1. The size in bytes of the *-oal file.
158967*/
158968#define RBU_STATE_STAGE       1
158969#define RBU_STATE_TBL         2
158970#define RBU_STATE_IDX         3
158971#define RBU_STATE_ROW         4
158972#define RBU_STATE_PROGRESS    5
158973#define RBU_STATE_CKPT        6
158974#define RBU_STATE_COOKIE      7
158975#define RBU_STATE_OALSZ       8
158976
158977#define RBU_STAGE_OAL         1
158978#define RBU_STAGE_MOVE        2
158979#define RBU_STAGE_CAPTURE     3
158980#define RBU_STAGE_CKPT        4
158981#define RBU_STAGE_DONE        5
158982
158983
158984#define RBU_CREATE_STATE \
158985  "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
158986
158987typedef struct RbuFrame RbuFrame;
158988typedef struct RbuObjIter RbuObjIter;
158989typedef struct RbuState RbuState;
158990typedef struct rbu_vfs rbu_vfs;
158991typedef struct rbu_file rbu_file;
158992typedef struct RbuUpdateStmt RbuUpdateStmt;
158993
158994#if !defined(SQLITE_AMALGAMATION)
158995typedef unsigned int u32;
158996typedef unsigned char u8;
158997typedef sqlite3_int64 i64;
158998#endif
158999
159000/*
159001** These values must match the values defined in wal.c for the equivalent
159002** locks. These are not magic numbers as they are part of the SQLite file
159003** format.
159004*/
159005#define WAL_LOCK_WRITE  0
159006#define WAL_LOCK_CKPT   1
159007#define WAL_LOCK_READ0  3
159008
159009/*
159010** A structure to store values read from the rbu_state table in memory.
159011*/
159012struct RbuState {
159013  int eStage;
159014  char *zTbl;
159015  char *zIdx;
159016  i64 iWalCksum;
159017  int nRow;
159018  i64 nProgress;
159019  u32 iCookie;
159020  i64 iOalSz;
159021};
159022
159023struct RbuUpdateStmt {
159024  char *zMask;                    /* Copy of update mask used with pUpdate */
159025  sqlite3_stmt *pUpdate;          /* Last update statement (or NULL) */
159026  RbuUpdateStmt *pNext;
159027};
159028
159029/*
159030** An iterator of this type is used to iterate through all objects in
159031** the target database that require updating. For each such table, the
159032** iterator visits, in order:
159033**
159034**     * the table itself,
159035**     * each index of the table (zero or more points to visit), and
159036**     * a special "cleanup table" state.
159037**
159038** abIndexed:
159039**   If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
159040**   it points to an array of flags nTblCol elements in size. The flag is
159041**   set for each column that is either a part of the PK or a part of an
159042**   index. Or clear otherwise.
159043**
159044*/
159045struct RbuObjIter {
159046  sqlite3_stmt *pTblIter;         /* Iterate through tables */
159047  sqlite3_stmt *pIdxIter;         /* Index iterator */
159048  int nTblCol;                    /* Size of azTblCol[] array */
159049  char **azTblCol;                /* Array of unquoted target column names */
159050  char **azTblType;               /* Array of target column types */
159051  int *aiSrcOrder;                /* src table col -> target table col */
159052  u8 *abTblPk;                    /* Array of flags, set on target PK columns */
159053  u8 *abNotNull;                  /* Array of flags, set on NOT NULL columns */
159054  u8 *abIndexed;                  /* Array of flags, set on indexed & PK cols */
159055  int eType;                      /* Table type - an RBU_PK_XXX value */
159056
159057  /* Output variables. zTbl==0 implies EOF. */
159058  int bCleanup;                   /* True in "cleanup" state */
159059  const char *zTbl;               /* Name of target db table */
159060  const char *zDataTbl;           /* Name of rbu db table (or null) */
159061  const char *zIdx;               /* Name of target db index (or null) */
159062  int iTnum;                      /* Root page of current object */
159063  int iPkTnum;                    /* If eType==EXTERNAL, root of PK index */
159064  int bUnique;                    /* Current index is unique */
159065
159066  /* Statements created by rbuObjIterPrepareAll() */
159067  int nCol;                       /* Number of columns in current object */
159068  sqlite3_stmt *pSelect;          /* Source data */
159069  sqlite3_stmt *pInsert;          /* Statement for INSERT operations */
159070  sqlite3_stmt *pDelete;          /* Statement for DELETE ops */
159071  sqlite3_stmt *pTmpInsert;       /* Insert into rbu_tmp_$zDataTbl */
159072
159073  /* Last UPDATE used (for PK b-tree updates only), or NULL. */
159074  RbuUpdateStmt *pRbuUpdate;
159075};
159076
159077/*
159078** Values for RbuObjIter.eType
159079**
159080**     0: Table does not exist (error)
159081**     1: Table has an implicit rowid.
159082**     2: Table has an explicit IPK column.
159083**     3: Table has an external PK index.
159084**     4: Table is WITHOUT ROWID.
159085**     5: Table is a virtual table.
159086*/
159087#define RBU_PK_NOTABLE        0
159088#define RBU_PK_NONE           1
159089#define RBU_PK_IPK            2
159090#define RBU_PK_EXTERNAL       3
159091#define RBU_PK_WITHOUT_ROWID  4
159092#define RBU_PK_VTAB           5
159093
159094
159095/*
159096** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
159097** one of the following operations.
159098*/
159099#define RBU_INSERT     1          /* Insert on a main table b-tree */
159100#define RBU_DELETE     2          /* Delete a row from a main table b-tree */
159101#define RBU_IDX_DELETE 3          /* Delete a row from an aux. index b-tree */
159102#define RBU_IDX_INSERT 4          /* Insert on an aux. index b-tree */
159103#define RBU_UPDATE     5          /* Update a row in a main table b-tree */
159104
159105
159106/*
159107** A single step of an incremental checkpoint - frame iWalFrame of the wal
159108** file should be copied to page iDbPage of the database file.
159109*/
159110struct RbuFrame {
159111  u32 iDbPage;
159112  u32 iWalFrame;
159113};
159114
159115/*
159116** RBU handle.
159117*/
159118struct sqlite3rbu {
159119  int eStage;                     /* Value of RBU_STATE_STAGE field */
159120  sqlite3 *dbMain;                /* target database handle */
159121  sqlite3 *dbRbu;                 /* rbu database handle */
159122  char *zTarget;                  /* Path to target db */
159123  char *zRbu;                     /* Path to rbu db */
159124  char *zState;                   /* Path to state db (or NULL if zRbu) */
159125  char zStateDb[5];               /* Db name for state ("stat" or "main") */
159126  int rc;                         /* Value returned by last rbu_step() call */
159127  char *zErrmsg;                  /* Error message if rc!=SQLITE_OK */
159128  int nStep;                      /* Rows processed for current object */
159129  int nProgress;                  /* Rows processed for all objects */
159130  RbuObjIter objiter;             /* Iterator for skipping through tbl/idx */
159131  const char *zVfsName;           /* Name of automatically created rbu vfs */
159132  rbu_file *pTargetFd;            /* File handle open on target db */
159133  i64 iOalSz;
159134
159135  /* The following state variables are used as part of the incremental
159136  ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
159137  ** function rbuSetupCheckpoint() for details.  */
159138  u32 iMaxFrame;                  /* Largest iWalFrame value in aFrame[] */
159139  u32 mLock;
159140  int nFrame;                     /* Entries in aFrame[] array */
159141  int nFrameAlloc;                /* Allocated size of aFrame[] array */
159142  RbuFrame *aFrame;
159143  int pgsz;
159144  u8 *aBuf;
159145  i64 iWalCksum;
159146};
159147
159148/*
159149** An rbu VFS is implemented using an instance of this structure.
159150*/
159151struct rbu_vfs {
159152  sqlite3_vfs base;               /* rbu VFS shim methods */
159153  sqlite3_vfs *pRealVfs;          /* Underlying VFS */
159154  sqlite3_mutex *mutex;           /* Mutex to protect pMain */
159155  rbu_file *pMain;                /* Linked list of main db files */
159156};
159157
159158/*
159159** Each file opened by an rbu VFS is represented by an instance of
159160** the following structure.
159161*/
159162struct rbu_file {
159163  sqlite3_file base;              /* sqlite3_file methods */
159164  sqlite3_file *pReal;            /* Underlying file handle */
159165  rbu_vfs *pRbuVfs;               /* Pointer to the rbu_vfs object */
159166  sqlite3rbu *pRbu;               /* Pointer to rbu object (rbu target only) */
159167
159168  int openFlags;                  /* Flags this file was opened with */
159169  u32 iCookie;                    /* Cookie value for main db files */
159170  u8 iWriteVer;                   /* "write-version" value for main db files */
159171
159172  int nShm;                       /* Number of entries in apShm[] array */
159173  char **apShm;                   /* Array of mmap'd *-shm regions */
159174  char *zDel;                     /* Delete this when closing file */
159175
159176  const char *zWal;               /* Wal filename for this main db file */
159177  rbu_file *pWalFd;               /* Wal file descriptor for this main db */
159178  rbu_file *pMainNext;            /* Next MAIN_DB file */
159179};
159180
159181
159182/*************************************************************************
159183** The following three functions, found below:
159184**
159185**   rbuDeltaGetInt()
159186**   rbuDeltaChecksum()
159187**   rbuDeltaApply()
159188**
159189** are lifted from the fossil source code (http://fossil-scm.org). They
159190** are used to implement the scalar SQL function rbu_fossil_delta().
159191*/
159192
159193/*
159194** Read bytes from *pz and convert them into a positive integer.  When
159195** finished, leave *pz pointing to the first character past the end of
159196** the integer.  The *pLen parameter holds the length of the string
159197** in *pz and is decremented once for each character in the integer.
159198*/
159199static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
159200  static const signed char zValue[] = {
159201    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
159202    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
159203    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
159204     0,  1,  2,  3,  4,  5,  6,  7,    8,  9, -1, -1, -1, -1, -1, -1,
159205    -1, 10, 11, 12, 13, 14, 15, 16,   17, 18, 19, 20, 21, 22, 23, 24,
159206    25, 26, 27, 28, 29, 30, 31, 32,   33, 34, 35, -1, -1, -1, -1, 36,
159207    -1, 37, 38, 39, 40, 41, 42, 43,   44, 45, 46, 47, 48, 49, 50, 51,
159208    52, 53, 54, 55, 56, 57, 58, 59,   60, 61, 62, -1, -1, -1, 63, -1,
159209  };
159210  unsigned int v = 0;
159211  int c;
159212  unsigned char *z = (unsigned char*)*pz;
159213  unsigned char *zStart = z;
159214  while( (c = zValue[0x7f&*(z++)])>=0 ){
159215     v = (v<<6) + c;
159216  }
159217  z--;
159218  *pLen -= z - zStart;
159219  *pz = (char*)z;
159220  return v;
159221}
159222
159223/*
159224** Compute a 32-bit checksum on the N-byte buffer.  Return the result.
159225*/
159226static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
159227  const unsigned char *z = (const unsigned char *)zIn;
159228  unsigned sum0 = 0;
159229  unsigned sum1 = 0;
159230  unsigned sum2 = 0;
159231  unsigned sum3 = 0;
159232  while(N >= 16){
159233    sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
159234    sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
159235    sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
159236    sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
159237    z += 16;
159238    N -= 16;
159239  }
159240  while(N >= 4){
159241    sum0 += z[0];
159242    sum1 += z[1];
159243    sum2 += z[2];
159244    sum3 += z[3];
159245    z += 4;
159246    N -= 4;
159247  }
159248  sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
159249  switch(N){
159250    case 3:   sum3 += (z[2] << 8);
159251    case 2:   sum3 += (z[1] << 16);
159252    case 1:   sum3 += (z[0] << 24);
159253    default:  ;
159254  }
159255  return sum3;
159256}
159257
159258/*
159259** Apply a delta.
159260**
159261** The output buffer should be big enough to hold the whole output
159262** file and a NUL terminator at the end.  The delta_output_size()
159263** routine will determine this size for you.
159264**
159265** The delta string should be null-terminated.  But the delta string
159266** may contain embedded NUL characters (if the input and output are
159267** binary files) so we also have to pass in the length of the delta in
159268** the lenDelta parameter.
159269**
159270** This function returns the size of the output file in bytes (excluding
159271** the final NUL terminator character).  Except, if the delta string is
159272** malformed or intended for use with a source file other than zSrc,
159273** then this routine returns -1.
159274**
159275** Refer to the delta_create() documentation above for a description
159276** of the delta file format.
159277*/
159278static int rbuDeltaApply(
159279  const char *zSrc,      /* The source or pattern file */
159280  int lenSrc,            /* Length of the source file */
159281  const char *zDelta,    /* Delta to apply to the pattern */
159282  int lenDelta,          /* Length of the delta */
159283  char *zOut             /* Write the output into this preallocated buffer */
159284){
159285  unsigned int limit;
159286  unsigned int total = 0;
159287#ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
159288  char *zOrigOut = zOut;
159289#endif
159290
159291  limit = rbuDeltaGetInt(&zDelta, &lenDelta);
159292  if( *zDelta!='\n' ){
159293    /* ERROR: size integer not terminated by "\n" */
159294    return -1;
159295  }
159296  zDelta++; lenDelta--;
159297  while( *zDelta && lenDelta>0 ){
159298    unsigned int cnt, ofst;
159299    cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
159300    switch( zDelta[0] ){
159301      case '@': {
159302        zDelta++; lenDelta--;
159303        ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
159304        if( lenDelta>0 && zDelta[0]!=',' ){
159305          /* ERROR: copy command not terminated by ',' */
159306          return -1;
159307        }
159308        zDelta++; lenDelta--;
159309        total += cnt;
159310        if( total>limit ){
159311          /* ERROR: copy exceeds output file size */
159312          return -1;
159313        }
159314        if( (int)(ofst+cnt) > lenSrc ){
159315          /* ERROR: copy extends past end of input */
159316          return -1;
159317        }
159318        memcpy(zOut, &zSrc[ofst], cnt);
159319        zOut += cnt;
159320        break;
159321      }
159322      case ':': {
159323        zDelta++; lenDelta--;
159324        total += cnt;
159325        if( total>limit ){
159326          /* ERROR:  insert command gives an output larger than predicted */
159327          return -1;
159328        }
159329        if( (int)cnt>lenDelta ){
159330          /* ERROR: insert count exceeds size of delta */
159331          return -1;
159332        }
159333        memcpy(zOut, zDelta, cnt);
159334        zOut += cnt;
159335        zDelta += cnt;
159336        lenDelta -= cnt;
159337        break;
159338      }
159339      case ';': {
159340        zDelta++; lenDelta--;
159341        zOut[0] = 0;
159342#ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
159343        if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
159344          /* ERROR:  bad checksum */
159345          return -1;
159346        }
159347#endif
159348        if( total!=limit ){
159349          /* ERROR: generated size does not match predicted size */
159350          return -1;
159351        }
159352        return total;
159353      }
159354      default: {
159355        /* ERROR: unknown delta operator */
159356        return -1;
159357      }
159358    }
159359  }
159360  /* ERROR: unterminated delta */
159361  return -1;
159362}
159363
159364static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
159365  int size;
159366  size = rbuDeltaGetInt(&zDelta, &lenDelta);
159367  if( *zDelta!='\n' ){
159368    /* ERROR: size integer not terminated by "\n" */
159369    return -1;
159370  }
159371  return size;
159372}
159373
159374/*
159375** End of code taken from fossil.
159376*************************************************************************/
159377
159378/*
159379** Implementation of SQL scalar function rbu_fossil_delta().
159380**
159381** This function applies a fossil delta patch to a blob. Exactly two
159382** arguments must be passed to this function. The first is the blob to
159383** patch and the second the patch to apply. If no error occurs, this
159384** function returns the patched blob.
159385*/
159386static void rbuFossilDeltaFunc(
159387  sqlite3_context *context,
159388  int argc,
159389  sqlite3_value **argv
159390){
159391  const char *aDelta;
159392  int nDelta;
159393  const char *aOrig;
159394  int nOrig;
159395
159396  int nOut;
159397  int nOut2;
159398  char *aOut;
159399
159400  assert( argc==2 );
159401
159402  nOrig = sqlite3_value_bytes(argv[0]);
159403  aOrig = (const char*)sqlite3_value_blob(argv[0]);
159404  nDelta = sqlite3_value_bytes(argv[1]);
159405  aDelta = (const char*)sqlite3_value_blob(argv[1]);
159406
159407  /* Figure out the size of the output */
159408  nOut = rbuDeltaOutputSize(aDelta, nDelta);
159409  if( nOut<0 ){
159410    sqlite3_result_error(context, "corrupt fossil delta", -1);
159411    return;
159412  }
159413
159414  aOut = sqlite3_malloc(nOut+1);
159415  if( aOut==0 ){
159416    sqlite3_result_error_nomem(context);
159417  }else{
159418    nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
159419    if( nOut2!=nOut ){
159420      sqlite3_result_error(context, "corrupt fossil delta", -1);
159421    }else{
159422      sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
159423    }
159424  }
159425}
159426
159427
159428/*
159429** Prepare the SQL statement in buffer zSql against database handle db.
159430** If successful, set *ppStmt to point to the new statement and return
159431** SQLITE_OK.
159432**
159433** Otherwise, if an error does occur, set *ppStmt to NULL and return
159434** an SQLite error code. Additionally, set output variable *pzErrmsg to
159435** point to a buffer containing an error message. It is the responsibility
159436** of the caller to (eventually) free this buffer using sqlite3_free().
159437*/
159438static int prepareAndCollectError(
159439  sqlite3 *db,
159440  sqlite3_stmt **ppStmt,
159441  char **pzErrmsg,
159442  const char *zSql
159443){
159444  int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
159445  if( rc!=SQLITE_OK ){
159446    *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
159447    *ppStmt = 0;
159448  }
159449  return rc;
159450}
159451
159452/*
159453** Reset the SQL statement passed as the first argument. Return a copy
159454** of the value returned by sqlite3_reset().
159455**
159456** If an error has occurred, then set *pzErrmsg to point to a buffer
159457** containing an error message. It is the responsibility of the caller
159458** to eventually free this buffer using sqlite3_free().
159459*/
159460static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
159461  int rc = sqlite3_reset(pStmt);
159462  if( rc!=SQLITE_OK ){
159463    *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
159464  }
159465  return rc;
159466}
159467
159468/*
159469** Unless it is NULL, argument zSql points to a buffer allocated using
159470** sqlite3_malloc containing an SQL statement. This function prepares the SQL
159471** statement against database db and frees the buffer. If statement
159472** compilation is successful, *ppStmt is set to point to the new statement
159473** handle and SQLITE_OK is returned.
159474**
159475** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
159476** returned. In this case, *pzErrmsg may also be set to point to an error
159477** message. It is the responsibility of the caller to free this error message
159478** buffer using sqlite3_free().
159479**
159480** If argument zSql is NULL, this function assumes that an OOM has occurred.
159481** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
159482*/
159483static int prepareFreeAndCollectError(
159484  sqlite3 *db,
159485  sqlite3_stmt **ppStmt,
159486  char **pzErrmsg,
159487  char *zSql
159488){
159489  int rc;
159490  assert( *pzErrmsg==0 );
159491  if( zSql==0 ){
159492    rc = SQLITE_NOMEM;
159493    *ppStmt = 0;
159494  }else{
159495    rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
159496    sqlite3_free(zSql);
159497  }
159498  return rc;
159499}
159500
159501/*
159502** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
159503** by an earlier call to rbuObjIterCacheTableInfo().
159504*/
159505static void rbuObjIterFreeCols(RbuObjIter *pIter){
159506  int i;
159507  for(i=0; i<pIter->nTblCol; i++){
159508    sqlite3_free(pIter->azTblCol[i]);
159509    sqlite3_free(pIter->azTblType[i]);
159510  }
159511  sqlite3_free(pIter->azTblCol);
159512  pIter->azTblCol = 0;
159513  pIter->azTblType = 0;
159514  pIter->aiSrcOrder = 0;
159515  pIter->abTblPk = 0;
159516  pIter->abNotNull = 0;
159517  pIter->nTblCol = 0;
159518  pIter->eType = 0;               /* Invalid value */
159519}
159520
159521/*
159522** Finalize all statements and free all allocations that are specific to
159523** the current object (table/index pair).
159524*/
159525static void rbuObjIterClearStatements(RbuObjIter *pIter){
159526  RbuUpdateStmt *pUp;
159527
159528  sqlite3_finalize(pIter->pSelect);
159529  sqlite3_finalize(pIter->pInsert);
159530  sqlite3_finalize(pIter->pDelete);
159531  sqlite3_finalize(pIter->pTmpInsert);
159532  pUp = pIter->pRbuUpdate;
159533  while( pUp ){
159534    RbuUpdateStmt *pTmp = pUp->pNext;
159535    sqlite3_finalize(pUp->pUpdate);
159536    sqlite3_free(pUp);
159537    pUp = pTmp;
159538  }
159539
159540  pIter->pSelect = 0;
159541  pIter->pInsert = 0;
159542  pIter->pDelete = 0;
159543  pIter->pRbuUpdate = 0;
159544  pIter->pTmpInsert = 0;
159545  pIter->nCol = 0;
159546}
159547
159548/*
159549** Clean up any resources allocated as part of the iterator object passed
159550** as the only argument.
159551*/
159552static void rbuObjIterFinalize(RbuObjIter *pIter){
159553  rbuObjIterClearStatements(pIter);
159554  sqlite3_finalize(pIter->pTblIter);
159555  sqlite3_finalize(pIter->pIdxIter);
159556  rbuObjIterFreeCols(pIter);
159557  memset(pIter, 0, sizeof(RbuObjIter));
159558}
159559
159560/*
159561** Advance the iterator to the next position.
159562**
159563** If no error occurs, SQLITE_OK is returned and the iterator is left
159564** pointing to the next entry. Otherwise, an error code and message is
159565** left in the RBU handle passed as the first argument. A copy of the
159566** error code is returned.
159567*/
159568static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
159569  int rc = p->rc;
159570  if( rc==SQLITE_OK ){
159571
159572    /* Free any SQLite statements used while processing the previous object */
159573    rbuObjIterClearStatements(pIter);
159574    if( pIter->zIdx==0 ){
159575      rc = sqlite3_exec(p->dbMain,
159576          "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
159577          "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
159578          "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
159579          "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
159580          , 0, 0, &p->zErrmsg
159581      );
159582    }
159583
159584    if( rc==SQLITE_OK ){
159585      if( pIter->bCleanup ){
159586        rbuObjIterFreeCols(pIter);
159587        pIter->bCleanup = 0;
159588        rc = sqlite3_step(pIter->pTblIter);
159589        if( rc!=SQLITE_ROW ){
159590          rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
159591          pIter->zTbl = 0;
159592        }else{
159593          pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
159594          pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
159595          rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
159596        }
159597      }else{
159598        if( pIter->zIdx==0 ){
159599          sqlite3_stmt *pIdx = pIter->pIdxIter;
159600          rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
159601        }
159602        if( rc==SQLITE_OK ){
159603          rc = sqlite3_step(pIter->pIdxIter);
159604          if( rc!=SQLITE_ROW ){
159605            rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
159606            pIter->bCleanup = 1;
159607            pIter->zIdx = 0;
159608          }else{
159609            pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
159610            pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
159611            pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
159612            rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
159613          }
159614        }
159615      }
159616    }
159617  }
159618
159619  if( rc!=SQLITE_OK ){
159620    rbuObjIterFinalize(pIter);
159621    p->rc = rc;
159622  }
159623  return rc;
159624}
159625
159626
159627/*
159628** The implementation of the rbu_target_name() SQL function. This function
159629** accepts one argument - the name of a table in the RBU database. If the
159630** table name matches the pattern:
159631**
159632**     data[0-9]_<name>
159633**
159634** where <name> is any sequence of 1 or more characters, <name> is returned.
159635** Otherwise, if the only argument does not match the above pattern, an SQL
159636** NULL is returned.
159637**
159638**     "data_t1"     -> "t1"
159639**     "data0123_t2" -> "t2"
159640**     "dataAB_t3"   -> NULL
159641*/
159642static void rbuTargetNameFunc(
159643  sqlite3_context *context,
159644  int argc,
159645  sqlite3_value **argv
159646){
159647  const char *zIn;
159648  assert( argc==1 );
159649
159650  zIn = (const char*)sqlite3_value_text(argv[0]);
159651  if( zIn && strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
159652    int i;
159653    for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
159654    if( zIn[i]=='_' && zIn[i+1] ){
159655      sqlite3_result_text(context, &zIn[i+1], -1, SQLITE_STATIC);
159656    }
159657  }
159658}
159659
159660/*
159661** Initialize the iterator structure passed as the second argument.
159662**
159663** If no error occurs, SQLITE_OK is returned and the iterator is left
159664** pointing to the first entry. Otherwise, an error code and message is
159665** left in the RBU handle passed as the first argument. A copy of the
159666** error code is returned.
159667*/
159668static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
159669  int rc;
159670  memset(pIter, 0, sizeof(RbuObjIter));
159671
159672  rc = prepareAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
159673      "SELECT rbu_target_name(name) AS target, name FROM sqlite_master "
159674      "WHERE type IN ('table', 'view') AND target IS NOT NULL "
159675      "ORDER BY name"
159676  );
159677
159678  if( rc==SQLITE_OK ){
159679    rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
159680        "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
159681        "  FROM main.sqlite_master "
159682        "  WHERE type='index' AND tbl_name = ?"
159683    );
159684  }
159685
159686  pIter->bCleanup = 1;
159687  p->rc = rc;
159688  return rbuObjIterNext(p, pIter);
159689}
159690
159691/*
159692** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
159693** an error code is stored in the RBU handle passed as the first argument.
159694**
159695** If an error has already occurred (p->rc is already set to something other
159696** than SQLITE_OK), then this function returns NULL without modifying the
159697** stored error code. In this case it still calls sqlite3_free() on any
159698** printf() parameters associated with %z conversions.
159699*/
159700static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
159701  char *zSql = 0;
159702  va_list ap;
159703  va_start(ap, zFmt);
159704  zSql = sqlite3_vmprintf(zFmt, ap);
159705  if( p->rc==SQLITE_OK ){
159706    if( zSql==0 ) p->rc = SQLITE_NOMEM;
159707  }else{
159708    sqlite3_free(zSql);
159709    zSql = 0;
159710  }
159711  va_end(ap);
159712  return zSql;
159713}
159714
159715/*
159716** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
159717** arguments are the usual subsitution values. This function performs
159718** the printf() style substitutions and executes the result as an SQL
159719** statement on the RBU handles database.
159720**
159721** If an error occurs, an error code and error message is stored in the
159722** RBU handle. If an error has already occurred when this function is
159723** called, it is a no-op.
159724*/
159725static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
159726  va_list ap;
159727  char *zSql;
159728  va_start(ap, zFmt);
159729  zSql = sqlite3_vmprintf(zFmt, ap);
159730  if( p->rc==SQLITE_OK ){
159731    if( zSql==0 ){
159732      p->rc = SQLITE_NOMEM;
159733    }else{
159734      p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
159735    }
159736  }
159737  sqlite3_free(zSql);
159738  va_end(ap);
159739  return p->rc;
159740}
159741
159742/*
159743** Attempt to allocate and return a pointer to a zeroed block of nByte
159744** bytes.
159745**
159746** If an error (i.e. an OOM condition) occurs, return NULL and leave an
159747** error code in the rbu handle passed as the first argument. Or, if an
159748** error has already occurred when this function is called, return NULL
159749** immediately without attempting the allocation or modifying the stored
159750** error code.
159751*/
159752static void *rbuMalloc(sqlite3rbu *p, int nByte){
159753  void *pRet = 0;
159754  if( p->rc==SQLITE_OK ){
159755    assert( nByte>0 );
159756    pRet = sqlite3_malloc(nByte);
159757    if( pRet==0 ){
159758      p->rc = SQLITE_NOMEM;
159759    }else{
159760      memset(pRet, 0, nByte);
159761    }
159762  }
159763  return pRet;
159764}
159765
159766
159767/*
159768** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
159769** there is room for at least nCol elements. If an OOM occurs, store an
159770** error code in the RBU handle passed as the first argument.
159771*/
159772static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
159773  int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
159774  char **azNew;
159775
159776  azNew = (char**)rbuMalloc(p, nByte);
159777  if( azNew ){
159778    pIter->azTblCol = azNew;
159779    pIter->azTblType = &azNew[nCol];
159780    pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
159781    pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
159782    pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
159783    pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
159784  }
159785}
159786
159787/*
159788** The first argument must be a nul-terminated string. This function
159789** returns a copy of the string in memory obtained from sqlite3_malloc().
159790** It is the responsibility of the caller to eventually free this memory
159791** using sqlite3_free().
159792**
159793** If an OOM condition is encountered when attempting to allocate memory,
159794** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
159795** if the allocation succeeds, (*pRc) is left unchanged.
159796*/
159797static char *rbuStrndup(const char *zStr, int *pRc){
159798  char *zRet = 0;
159799
159800  assert( *pRc==SQLITE_OK );
159801  if( zStr ){
159802    int nCopy = strlen(zStr) + 1;
159803    zRet = (char*)sqlite3_malloc(nCopy);
159804    if( zRet ){
159805      memcpy(zRet, zStr, nCopy);
159806    }else{
159807      *pRc = SQLITE_NOMEM;
159808    }
159809  }
159810
159811  return zRet;
159812}
159813
159814/*
159815** Finalize the statement passed as the second argument.
159816**
159817** If the sqlite3_finalize() call indicates that an error occurs, and the
159818** rbu handle error code is not already set, set the error code and error
159819** message accordingly.
159820*/
159821static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
159822  sqlite3 *db = sqlite3_db_handle(pStmt);
159823  int rc = sqlite3_finalize(pStmt);
159824  if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
159825    p->rc = rc;
159826    p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
159827  }
159828}
159829
159830/* Determine the type of a table.
159831**
159832**   peType is of type (int*), a pointer to an output parameter of type
159833**   (int). This call sets the output parameter as follows, depending
159834**   on the type of the table specified by parameters dbName and zTbl.
159835**
159836**     RBU_PK_NOTABLE:       No such table.
159837**     RBU_PK_NONE:          Table has an implicit rowid.
159838**     RBU_PK_IPK:           Table has an explicit IPK column.
159839**     RBU_PK_EXTERNAL:      Table has an external PK index.
159840**     RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
159841**     RBU_PK_VTAB:          Table is a virtual table.
159842**
159843**   Argument *piPk is also of type (int*), and also points to an output
159844**   parameter. Unless the table has an external primary key index
159845**   (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
159846**   if the table does have an external primary key index, then *piPk
159847**   is set to the root page number of the primary key index before
159848**   returning.
159849**
159850** ALGORITHM:
159851**
159852**   if( no entry exists in sqlite_master ){
159853**     return RBU_PK_NOTABLE
159854**   }else if( sql for the entry starts with "CREATE VIRTUAL" ){
159855**     return RBU_PK_VTAB
159856**   }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
159857**     if( the index that is the pk exists in sqlite_master ){
159858**       *piPK = rootpage of that index.
159859**       return RBU_PK_EXTERNAL
159860**     }else{
159861**       return RBU_PK_WITHOUT_ROWID
159862**     }
159863**   }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
159864**     return RBU_PK_IPK
159865**   }else{
159866**     return RBU_PK_NONE
159867**   }
159868*/
159869static void rbuTableType(
159870  sqlite3rbu *p,
159871  const char *zTab,
159872  int *peType,
159873  int *piTnum,
159874  int *piPk
159875){
159876  /*
159877  ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
159878  ** 1) PRAGMA index_list = ?
159879  ** 2) SELECT count(*) FROM sqlite_master where name=%Q
159880  ** 3) PRAGMA table_info = ?
159881  */
159882  sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
159883
159884  *peType = RBU_PK_NOTABLE;
159885  *piPk = 0;
159886
159887  assert( p->rc==SQLITE_OK );
159888  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
159889    sqlite3_mprintf(
159890          "SELECT (sql LIKE 'create virtual%%'), rootpage"
159891          "  FROM sqlite_master"
159892          " WHERE name=%Q", zTab
159893  ));
159894  if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
159895    /* Either an error, or no such table. */
159896    goto rbuTableType_end;
159897  }
159898  if( sqlite3_column_int(aStmt[0], 0) ){
159899    *peType = RBU_PK_VTAB;                     /* virtual table */
159900    goto rbuTableType_end;
159901  }
159902  *piTnum = sqlite3_column_int(aStmt[0], 1);
159903
159904  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
159905    sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
159906  );
159907  if( p->rc ) goto rbuTableType_end;
159908  while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
159909    const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
159910    const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
159911    if( zOrig && zIdx && zOrig[0]=='p' ){
159912      p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
159913          sqlite3_mprintf(
159914            "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
159915      ));
159916      if( p->rc==SQLITE_OK ){
159917        if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
159918          *piPk = sqlite3_column_int(aStmt[2], 0);
159919          *peType = RBU_PK_EXTERNAL;
159920        }else{
159921          *peType = RBU_PK_WITHOUT_ROWID;
159922        }
159923      }
159924      goto rbuTableType_end;
159925    }
159926  }
159927
159928  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
159929    sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
159930  );
159931  if( p->rc==SQLITE_OK ){
159932    while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
159933      if( sqlite3_column_int(aStmt[3],5)>0 ){
159934        *peType = RBU_PK_IPK;                /* explicit IPK column */
159935        goto rbuTableType_end;
159936      }
159937    }
159938    *peType = RBU_PK_NONE;
159939  }
159940
159941rbuTableType_end: {
159942    unsigned int i;
159943    for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
159944      rbuFinalize(p, aStmt[i]);
159945    }
159946  }
159947}
159948
159949/*
159950** This is a helper function for rbuObjIterCacheTableInfo(). It populates
159951** the pIter->abIndexed[] array.
159952*/
159953static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
159954  sqlite3_stmt *pList = 0;
159955  int bIndex = 0;
159956
159957  if( p->rc==SQLITE_OK ){
159958    memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
159959    p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
159960        sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
159961    );
159962  }
159963
159964  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
159965    const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
159966    sqlite3_stmt *pXInfo = 0;
159967    if( zIdx==0 ) break;
159968    p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
159969        sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
159970    );
159971    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
159972      int iCid = sqlite3_column_int(pXInfo, 1);
159973      if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
159974    }
159975    rbuFinalize(p, pXInfo);
159976    bIndex = 1;
159977  }
159978
159979  rbuFinalize(p, pList);
159980  if( bIndex==0 ) pIter->abIndexed = 0;
159981}
159982
159983
159984/*
159985** If they are not already populated, populate the pIter->azTblCol[],
159986** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
159987** the table (not index) that the iterator currently points to.
159988**
159989** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
159990** an error does occur, an error code and error message are also left in
159991** the RBU handle.
159992*/
159993static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
159994  if( pIter->azTblCol==0 ){
159995    sqlite3_stmt *pStmt = 0;
159996    int nCol = 0;
159997    int i;                        /* for() loop iterator variable */
159998    int bRbuRowid = 0;            /* If input table has column "rbu_rowid" */
159999    int iOrder = 0;
160000    int iTnum = 0;
160001
160002    /* Figure out the type of table this step will deal with. */
160003    assert( pIter->eType==0 );
160004    rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
160005    if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
160006      p->rc = SQLITE_ERROR;
160007      p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
160008    }
160009    if( p->rc ) return p->rc;
160010    if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
160011
160012    assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
160013         || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
160014         || pIter->eType==RBU_PK_VTAB
160015    );
160016
160017    /* Populate the azTblCol[] and nTblCol variables based on the columns
160018    ** of the input table. Ignore any input table columns that begin with
160019    ** "rbu_".  */
160020    p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
160021        sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
160022    );
160023    if( p->rc==SQLITE_OK ){
160024      nCol = sqlite3_column_count(pStmt);
160025      rbuAllocateIterArrays(p, pIter, nCol);
160026    }
160027    for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
160028      const char *zName = (const char*)sqlite3_column_name(pStmt, i);
160029      if( sqlite3_strnicmp("rbu_", zName, 4) ){
160030        char *zCopy = rbuStrndup(zName, &p->rc);
160031        pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
160032        pIter->azTblCol[pIter->nTblCol++] = zCopy;
160033      }
160034      else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
160035        bRbuRowid = 1;
160036      }
160037    }
160038    sqlite3_finalize(pStmt);
160039    pStmt = 0;
160040
160041    if( p->rc==SQLITE_OK
160042     && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
160043    ){
160044      p->rc = SQLITE_ERROR;
160045      p->zErrmsg = sqlite3_mprintf(
160046          "table %q %s rbu_rowid column", pIter->zDataTbl,
160047          (bRbuRowid ? "may not have" : "requires")
160048      );
160049    }
160050
160051    /* Check that all non-HIDDEN columns in the destination table are also
160052    ** present in the input table. Populate the abTblPk[], azTblType[] and
160053    ** aiTblOrder[] arrays at the same time.  */
160054    if( p->rc==SQLITE_OK ){
160055      p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
160056          sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
160057      );
160058    }
160059    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
160060      const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
160061      if( zName==0 ) break;  /* An OOM - finalize() below returns S_NOMEM */
160062      for(i=iOrder; i<pIter->nTblCol; i++){
160063        if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
160064      }
160065      if( i==pIter->nTblCol ){
160066        p->rc = SQLITE_ERROR;
160067        p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
160068            pIter->zDataTbl, zName
160069        );
160070      }else{
160071        int iPk = sqlite3_column_int(pStmt, 5);
160072        int bNotNull = sqlite3_column_int(pStmt, 3);
160073        const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
160074
160075        if( i!=iOrder ){
160076          SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
160077          SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
160078        }
160079
160080        pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
160081        pIter->abTblPk[iOrder] = (iPk!=0);
160082        pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
160083        iOrder++;
160084      }
160085    }
160086
160087    rbuFinalize(p, pStmt);
160088    rbuObjIterCacheIndexedCols(p, pIter);
160089    assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
160090  }
160091
160092  return p->rc;
160093}
160094
160095/*
160096** This function constructs and returns a pointer to a nul-terminated
160097** string containing some SQL clause or list based on one or more of the
160098** column names currently stored in the pIter->azTblCol[] array.
160099*/
160100static char *rbuObjIterGetCollist(
160101  sqlite3rbu *p,                  /* RBU object */
160102  RbuObjIter *pIter               /* Object iterator for column names */
160103){
160104  char *zList = 0;
160105  const char *zSep = "";
160106  int i;
160107  for(i=0; i<pIter->nTblCol; i++){
160108    const char *z = pIter->azTblCol[i];
160109    zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
160110    zSep = ", ";
160111  }
160112  return zList;
160113}
160114
160115/*
160116** This function is used to create a SELECT list (the list of SQL
160117** expressions that follows a SELECT keyword) for a SELECT statement
160118** used to read from an data_xxx or rbu_tmp_xxx table while updating the
160119** index object currently indicated by the iterator object passed as the
160120** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
160121** to obtain the required information.
160122**
160123** If the index is of the following form:
160124**
160125**   CREATE INDEX i1 ON t1(c, b COLLATE nocase);
160126**
160127** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
160128** "ipk", the returned string is:
160129**
160130**   "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
160131**
160132** As well as the returned string, three other malloc'd strings are
160133** returned via output parameters. As follows:
160134**
160135**   pzImposterCols: ...
160136**   pzImposterPk: ...
160137**   pzWhere: ...
160138*/
160139static char *rbuObjIterGetIndexCols(
160140  sqlite3rbu *p,                  /* RBU object */
160141  RbuObjIter *pIter,              /* Object iterator for column names */
160142  char **pzImposterCols,          /* OUT: Columns for imposter table */
160143  char **pzImposterPk,            /* OUT: Imposter PK clause */
160144  char **pzWhere,                 /* OUT: WHERE clause */
160145  int *pnBind                     /* OUT: Trbul number of columns */
160146){
160147  int rc = p->rc;                 /* Error code */
160148  int rc2;                        /* sqlite3_finalize() return code */
160149  char *zRet = 0;                 /* String to return */
160150  char *zImpCols = 0;             /* String to return via *pzImposterCols */
160151  char *zImpPK = 0;               /* String to return via *pzImposterPK */
160152  char *zWhere = 0;               /* String to return via *pzWhere */
160153  int nBind = 0;                  /* Value to return via *pnBind */
160154  const char *zCom = "";          /* Set to ", " later on */
160155  const char *zAnd = "";          /* Set to " AND " later on */
160156  sqlite3_stmt *pXInfo = 0;       /* PRAGMA index_xinfo = ? */
160157
160158  if( rc==SQLITE_OK ){
160159    assert( p->zErrmsg==0 );
160160    rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
160161        sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
160162    );
160163  }
160164
160165  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
160166    int iCid = sqlite3_column_int(pXInfo, 1);
160167    int bDesc = sqlite3_column_int(pXInfo, 3);
160168    const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
160169    const char *zCol;
160170    const char *zType;
160171
160172    if( iCid<0 ){
160173      /* An integer primary key. If the table has an explicit IPK, use
160174      ** its name. Otherwise, use "rbu_rowid".  */
160175      if( pIter->eType==RBU_PK_IPK ){
160176        int i;
160177        for(i=0; pIter->abTblPk[i]==0; i++);
160178        assert( i<pIter->nTblCol );
160179        zCol = pIter->azTblCol[i];
160180      }else{
160181        zCol = "rbu_rowid";
160182      }
160183      zType = "INTEGER";
160184    }else{
160185      zCol = pIter->azTblCol[iCid];
160186      zType = pIter->azTblType[iCid];
160187    }
160188
160189    zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
160190    if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
160191      const char *zOrder = (bDesc ? " DESC" : "");
160192      zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
160193          zImpPK, zCom, nBind, zCol, zOrder
160194      );
160195    }
160196    zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
160197        zImpCols, zCom, nBind, zCol, zType, zCollate
160198    );
160199    zWhere = sqlite3_mprintf(
160200        "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
160201    );
160202    if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
160203    zCom = ", ";
160204    zAnd = " AND ";
160205    nBind++;
160206  }
160207
160208  rc2 = sqlite3_finalize(pXInfo);
160209  if( rc==SQLITE_OK ) rc = rc2;
160210
160211  if( rc!=SQLITE_OK ){
160212    sqlite3_free(zRet);
160213    sqlite3_free(zImpCols);
160214    sqlite3_free(zImpPK);
160215    sqlite3_free(zWhere);
160216    zRet = 0;
160217    zImpCols = 0;
160218    zImpPK = 0;
160219    zWhere = 0;
160220    p->rc = rc;
160221  }
160222
160223  *pzImposterCols = zImpCols;
160224  *pzImposterPk = zImpPK;
160225  *pzWhere = zWhere;
160226  *pnBind = nBind;
160227  return zRet;
160228}
160229
160230/*
160231** Assuming the current table columns are "a", "b" and "c", and the zObj
160232** paramter is passed "old", return a string of the form:
160233**
160234**     "old.a, old.b, old.b"
160235**
160236** With the column names escaped.
160237**
160238** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
160239** the text ", old._rowid_" to the returned value.
160240*/
160241static char *rbuObjIterGetOldlist(
160242  sqlite3rbu *p,
160243  RbuObjIter *pIter,
160244  const char *zObj
160245){
160246  char *zList = 0;
160247  if( p->rc==SQLITE_OK && pIter->abIndexed ){
160248    const char *zS = "";
160249    int i;
160250    for(i=0; i<pIter->nTblCol; i++){
160251      if( pIter->abIndexed[i] ){
160252        const char *zCol = pIter->azTblCol[i];
160253        zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
160254      }else{
160255        zList = sqlite3_mprintf("%z%sNULL", zList, zS);
160256      }
160257      zS = ", ";
160258      if( zList==0 ){
160259        p->rc = SQLITE_NOMEM;
160260        break;
160261      }
160262    }
160263
160264    /* For a table with implicit rowids, append "old._rowid_" to the list. */
160265    if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
160266      zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
160267    }
160268  }
160269  return zList;
160270}
160271
160272/*
160273** Return an expression that can be used in a WHERE clause to match the
160274** primary key of the current table. For example, if the table is:
160275**
160276**   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
160277**
160278** Return the string:
160279**
160280**   "b = ?1 AND c = ?2"
160281*/
160282static char *rbuObjIterGetWhere(
160283  sqlite3rbu *p,
160284  RbuObjIter *pIter
160285){
160286  char *zList = 0;
160287  if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
160288    zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
160289  }else if( pIter->eType==RBU_PK_EXTERNAL ){
160290    const char *zSep = "";
160291    int i;
160292    for(i=0; i<pIter->nTblCol; i++){
160293      if( pIter->abTblPk[i] ){
160294        zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
160295        zSep = " AND ";
160296      }
160297    }
160298    zList = rbuMPrintf(p,
160299        "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
160300    );
160301
160302  }else{
160303    const char *zSep = "";
160304    int i;
160305    for(i=0; i<pIter->nTblCol; i++){
160306      if( pIter->abTblPk[i] ){
160307        const char *zCol = pIter->azTblCol[i];
160308        zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
160309        zSep = " AND ";
160310      }
160311    }
160312  }
160313  return zList;
160314}
160315
160316/*
160317** The SELECT statement iterating through the keys for the current object
160318** (p->objiter.pSelect) currently points to a valid row. However, there
160319** is something wrong with the rbu_control value in the rbu_control value
160320** stored in the (p->nCol+1)'th column. Set the error code and error message
160321** of the RBU handle to something reflecting this.
160322*/
160323static void rbuBadControlError(sqlite3rbu *p){
160324  p->rc = SQLITE_ERROR;
160325  p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
160326}
160327
160328
160329/*
160330** Return a nul-terminated string containing the comma separated list of
160331** assignments that should be included following the "SET" keyword of
160332** an UPDATE statement used to update the table object that the iterator
160333** passed as the second argument currently points to if the rbu_control
160334** column of the data_xxx table entry is set to zMask.
160335**
160336** The memory for the returned string is obtained from sqlite3_malloc().
160337** It is the responsibility of the caller to eventually free it using
160338** sqlite3_free().
160339**
160340** If an OOM error is encountered when allocating space for the new
160341** string, an error code is left in the rbu handle passed as the first
160342** argument and NULL is returned. Or, if an error has already occurred
160343** when this function is called, NULL is returned immediately, without
160344** attempting the allocation or modifying the stored error code.
160345*/
160346static char *rbuObjIterGetSetlist(
160347  sqlite3rbu *p,
160348  RbuObjIter *pIter,
160349  const char *zMask
160350){
160351  char *zList = 0;
160352  if( p->rc==SQLITE_OK ){
160353    int i;
160354
160355    if( (int)strlen(zMask)!=pIter->nTblCol ){
160356      rbuBadControlError(p);
160357    }else{
160358      const char *zSep = "";
160359      for(i=0; i<pIter->nTblCol; i++){
160360        char c = zMask[pIter->aiSrcOrder[i]];
160361        if( c=='x' ){
160362          zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
160363              zList, zSep, pIter->azTblCol[i], i+1
160364          );
160365          zSep = ", ";
160366        }
160367        else if( c=='d' ){
160368          zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
160369              zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
160370          );
160371          zSep = ", ";
160372        }
160373        else if( c=='f' ){
160374          zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
160375              zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
160376          );
160377          zSep = ", ";
160378        }
160379      }
160380    }
160381  }
160382  return zList;
160383}
160384
160385/*
160386** Return a nul-terminated string consisting of nByte comma separated
160387** "?" expressions. For example, if nByte is 3, return a pointer to
160388** a buffer containing the string "?,?,?".
160389**
160390** The memory for the returned string is obtained from sqlite3_malloc().
160391** It is the responsibility of the caller to eventually free it using
160392** sqlite3_free().
160393**
160394** If an OOM error is encountered when allocating space for the new
160395** string, an error code is left in the rbu handle passed as the first
160396** argument and NULL is returned. Or, if an error has already occurred
160397** when this function is called, NULL is returned immediately, without
160398** attempting the allocation or modifying the stored error code.
160399*/
160400static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
160401  char *zRet = 0;
160402  int nByte = nBind*2 + 1;
160403
160404  zRet = (char*)rbuMalloc(p, nByte);
160405  if( zRet ){
160406    int i;
160407    for(i=0; i<nBind; i++){
160408      zRet[i*2] = '?';
160409      zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
160410    }
160411  }
160412  return zRet;
160413}
160414
160415/*
160416** The iterator currently points to a table (not index) of type
160417** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
160418** declaration for the corresponding imposter table. For example,
160419** if the iterator points to a table created as:
160420**
160421**   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
160422**
160423** this function returns:
160424**
160425**   PRIMARY KEY("b", "a" DESC)
160426*/
160427static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
160428  char *z = 0;
160429  assert( pIter->zIdx==0 );
160430  if( p->rc==SQLITE_OK ){
160431    const char *zSep = "PRIMARY KEY(";
160432    sqlite3_stmt *pXList = 0;     /* PRAGMA index_list = (pIter->zTbl) */
160433    sqlite3_stmt *pXInfo = 0;     /* PRAGMA index_xinfo = <pk-index> */
160434
160435    p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
160436        sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
160437    );
160438    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
160439      const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
160440      if( zOrig && strcmp(zOrig, "pk")==0 ){
160441        const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
160442        if( zIdx ){
160443          p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
160444              sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
160445          );
160446        }
160447        break;
160448      }
160449    }
160450    rbuFinalize(p, pXList);
160451
160452    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
160453      if( sqlite3_column_int(pXInfo, 5) ){
160454        /* int iCid = sqlite3_column_int(pXInfo, 0); */
160455        const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
160456        const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
160457        z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
160458        zSep = ", ";
160459      }
160460    }
160461    z = rbuMPrintf(p, "%z)", z);
160462    rbuFinalize(p, pXInfo);
160463  }
160464  return z;
160465}
160466
160467/*
160468** This function creates the second imposter table used when writing to
160469** a table b-tree where the table has an external primary key. If the
160470** iterator passed as the second argument does not currently point to
160471** a table (not index) with an external primary key, this function is a
160472** no-op.
160473**
160474** Assuming the iterator does point to a table with an external PK, this
160475** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
160476** used to access that PK index. For example, if the target table is
160477** declared as follows:
160478**
160479**   CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
160480**
160481** then the imposter table schema is:
160482**
160483**   CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
160484**
160485*/
160486static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
160487  if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
160488    int tnum = pIter->iPkTnum;    /* Root page of PK index */
160489    sqlite3_stmt *pQuery = 0;     /* SELECT name ... WHERE rootpage = $tnum */
160490    const char *zIdx = 0;         /* Name of PK index */
160491    sqlite3_stmt *pXInfo = 0;     /* PRAGMA main.index_xinfo = $zIdx */
160492    const char *zComma = "";
160493    char *zCols = 0;              /* Used to build up list of table cols */
160494    char *zPk = 0;                /* Used to build up table PK declaration */
160495
160496    /* Figure out the name of the primary key index for the current table.
160497    ** This is needed for the argument to "PRAGMA index_xinfo". Set
160498    ** zIdx to point to a nul-terminated string containing this name. */
160499    p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
160500        "SELECT name FROM sqlite_master WHERE rootpage = ?"
160501    );
160502    if( p->rc==SQLITE_OK ){
160503      sqlite3_bind_int(pQuery, 1, tnum);
160504      if( SQLITE_ROW==sqlite3_step(pQuery) ){
160505        zIdx = (const char*)sqlite3_column_text(pQuery, 0);
160506      }
160507    }
160508    if( zIdx ){
160509      p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
160510          sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
160511      );
160512    }
160513    rbuFinalize(p, pQuery);
160514
160515    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
160516      int bKey = sqlite3_column_int(pXInfo, 5);
160517      if( bKey ){
160518        int iCid = sqlite3_column_int(pXInfo, 1);
160519        int bDesc = sqlite3_column_int(pXInfo, 3);
160520        const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
160521        zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma,
160522            iCid, pIter->azTblType[iCid], zCollate
160523        );
160524        zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
160525        zComma = ", ";
160526      }
160527    }
160528    zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
160529    rbuFinalize(p, pXInfo);
160530
160531    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
160532    rbuMPrintfExec(p, p->dbMain,
160533        "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
160534        zCols, zPk
160535    );
160536    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
160537  }
160538}
160539
160540/*
160541** If an error has already occurred when this function is called, it
160542** immediately returns zero (without doing any work). Or, if an error
160543** occurs during the execution of this function, it sets the error code
160544** in the sqlite3rbu object indicated by the first argument and returns
160545** zero.
160546**
160547** The iterator passed as the second argument is guaranteed to point to
160548** a table (not an index) when this function is called. This function
160549** attempts to create any imposter table required to write to the main
160550** table b-tree of the table before returning. Non-zero is returned if
160551** an imposter table are created, or zero otherwise.
160552**
160553** An imposter table is required in all cases except RBU_PK_VTAB. Only
160554** virtual tables are written to directly. The imposter table has the
160555** same schema as the actual target table (less any UNIQUE constraints).
160556** More precisely, the "same schema" means the same columns, types,
160557** collation sequences. For tables that do not have an external PRIMARY
160558** KEY, it also means the same PRIMARY KEY declaration.
160559*/
160560static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
160561  if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
160562    int tnum = pIter->iTnum;
160563    const char *zComma = "";
160564    char *zSql = 0;
160565    int iCol;
160566    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
160567
160568    for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
160569      const char *zPk = "";
160570      const char *zCol = pIter->azTblCol[iCol];
160571      const char *zColl = 0;
160572
160573      p->rc = sqlite3_table_column_metadata(
160574          p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
160575      );
160576
160577      if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
160578        /* If the target table column is an "INTEGER PRIMARY KEY", add
160579        ** "PRIMARY KEY" to the imposter table column declaration. */
160580        zPk = "PRIMARY KEY ";
160581      }
160582      zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s",
160583          zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
160584          (pIter->abNotNull[iCol] ? " NOT NULL" : "")
160585      );
160586      zComma = ", ";
160587    }
160588
160589    if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
160590      char *zPk = rbuWithoutRowidPK(p, pIter);
160591      if( zPk ){
160592        zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
160593      }
160594    }
160595
160596    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
160597    rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
160598        pIter->zTbl, zSql,
160599        (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
160600    );
160601    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
160602  }
160603}
160604
160605/*
160606** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
160607** Specifically a statement of the form:
160608**
160609**     INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
160610**
160611** The number of bound variables is equal to the number of columns in
160612** the target table, plus one (for the rbu_control column), plus one more
160613** (for the rbu_rowid column) if the target table is an implicit IPK or
160614** virtual table.
160615*/
160616static void rbuObjIterPrepareTmpInsert(
160617  sqlite3rbu *p,
160618  RbuObjIter *pIter,
160619  const char *zCollist,
160620  const char *zRbuRowid
160621){
160622  int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
160623  char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
160624  if( zBind ){
160625    assert( pIter->pTmpInsert==0 );
160626    p->rc = prepareFreeAndCollectError(
160627        p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
160628          "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
160629          p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
160630    ));
160631  }
160632}
160633
160634static void rbuTmpInsertFunc(
160635  sqlite3_context *pCtx,
160636  int nVal,
160637  sqlite3_value **apVal
160638){
160639  sqlite3rbu *p = sqlite3_user_data(pCtx);
160640  int rc = SQLITE_OK;
160641  int i;
160642
160643  for(i=0; rc==SQLITE_OK && i<nVal; i++){
160644    rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
160645  }
160646  if( rc==SQLITE_OK ){
160647    sqlite3_step(p->objiter.pTmpInsert);
160648    rc = sqlite3_reset(p->objiter.pTmpInsert);
160649  }
160650
160651  if( rc!=SQLITE_OK ){
160652    sqlite3_result_error_code(pCtx, rc);
160653  }
160654}
160655
160656/*
160657** Ensure that the SQLite statement handles required to update the
160658** target database object currently indicated by the iterator passed
160659** as the second argument are available.
160660*/
160661static int rbuObjIterPrepareAll(
160662  sqlite3rbu *p,
160663  RbuObjIter *pIter,
160664  int nOffset                     /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
160665){
160666  assert( pIter->bCleanup==0 );
160667  if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
160668    const int tnum = pIter->iTnum;
160669    char *zCollist = 0;           /* List of indexed columns */
160670    char **pz = &p->zErrmsg;
160671    const char *zIdx = pIter->zIdx;
160672    char *zLimit = 0;
160673
160674    if( nOffset ){
160675      zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
160676      if( !zLimit ) p->rc = SQLITE_NOMEM;
160677    }
160678
160679    if( zIdx ){
160680      const char *zTbl = pIter->zTbl;
160681      char *zImposterCols = 0;    /* Columns for imposter table */
160682      char *zImposterPK = 0;      /* Primary key declaration for imposter */
160683      char *zWhere = 0;           /* WHERE clause on PK columns */
160684      char *zBind = 0;
160685      int nBind = 0;
160686
160687      assert( pIter->eType!=RBU_PK_VTAB );
160688      zCollist = rbuObjIterGetIndexCols(
160689          p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
160690      );
160691      zBind = rbuObjIterGetBindlist(p, nBind);
160692
160693      /* Create the imposter table used to write to this index. */
160694      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
160695      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
160696      rbuMPrintfExec(p, p->dbMain,
160697          "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
160698          zTbl, zImposterCols, zImposterPK
160699      );
160700      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
160701
160702      /* Create the statement to insert index entries */
160703      pIter->nCol = nBind;
160704      if( p->rc==SQLITE_OK ){
160705        p->rc = prepareFreeAndCollectError(
160706            p->dbMain, &pIter->pInsert, &p->zErrmsg,
160707          sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
160708        );
160709      }
160710
160711      /* And to delete index entries */
160712      if( p->rc==SQLITE_OK ){
160713        p->rc = prepareFreeAndCollectError(
160714            p->dbMain, &pIter->pDelete, &p->zErrmsg,
160715          sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
160716        );
160717      }
160718
160719      /* Create the SELECT statement to read keys in sorted order */
160720      if( p->rc==SQLITE_OK ){
160721        char *zSql;
160722        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
160723          zSql = sqlite3_mprintf(
160724              "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
160725              zCollist, p->zStateDb, pIter->zDataTbl,
160726              zCollist, zLimit
160727          );
160728        }else{
160729          zSql = sqlite3_mprintf(
160730              "SELECT %s, rbu_control FROM '%q' "
160731              "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
160732              "UNION ALL "
160733              "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
160734              "ORDER BY %s%s",
160735              zCollist, pIter->zDataTbl,
160736              zCollist, p->zStateDb, pIter->zDataTbl,
160737              zCollist, zLimit
160738          );
160739        }
160740        p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
160741      }
160742
160743      sqlite3_free(zImposterCols);
160744      sqlite3_free(zImposterPK);
160745      sqlite3_free(zWhere);
160746      sqlite3_free(zBind);
160747    }else{
160748      int bRbuRowid = (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE);
160749      const char *zTbl = pIter->zTbl;       /* Table this step applies to */
160750      const char *zWrite;                   /* Imposter table name */
160751
160752      char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
160753      char *zWhere = rbuObjIterGetWhere(p, pIter);
160754      char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
160755      char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
160756
160757      zCollist = rbuObjIterGetCollist(p, pIter);
160758      pIter->nCol = pIter->nTblCol;
160759
160760      /* Create the imposter table or tables (if required). */
160761      rbuCreateImposterTable(p, pIter);
160762      rbuCreateImposterTable2(p, pIter);
160763      zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
160764
160765      /* Create the INSERT statement to write to the target PK b-tree */
160766      if( p->rc==SQLITE_OK ){
160767        p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
160768            sqlite3_mprintf(
160769              "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
160770              zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
160771            )
160772        );
160773      }
160774
160775      /* Create the DELETE statement to write to the target PK b-tree */
160776      if( p->rc==SQLITE_OK ){
160777        p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
160778            sqlite3_mprintf(
160779              "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
160780            )
160781        );
160782      }
160783
160784      if( pIter->abIndexed ){
160785        const char *zRbuRowid = "";
160786        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
160787          zRbuRowid = ", rbu_rowid";
160788        }
160789
160790        /* Create the rbu_tmp_xxx table and the triggers to populate it. */
160791        rbuMPrintfExec(p, p->dbRbu,
160792            "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
160793            "SELECT *%s FROM '%q' WHERE 0;"
160794            , p->zStateDb, pIter->zDataTbl
160795            , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
160796            , pIter->zDataTbl
160797        );
160798
160799        rbuMPrintfExec(p, p->dbMain,
160800            "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
160801            "BEGIN "
160802            "  SELECT rbu_tmp_insert(2, %s);"
160803            "END;"
160804
160805            "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
160806            "BEGIN "
160807            "  SELECT rbu_tmp_insert(2, %s);"
160808            "END;"
160809
160810            "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
160811            "BEGIN "
160812            "  SELECT rbu_tmp_insert(3, %s);"
160813            "END;",
160814            zWrite, zTbl, zOldlist,
160815            zWrite, zTbl, zOldlist,
160816            zWrite, zTbl, zNewlist
160817        );
160818
160819        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
160820          rbuMPrintfExec(p, p->dbMain,
160821              "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
160822              "BEGIN "
160823              "  SELECT rbu_tmp_insert(0, %s);"
160824              "END;",
160825              zWrite, zTbl, zNewlist
160826          );
160827        }
160828
160829        rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
160830      }
160831
160832      /* Create the SELECT statement to read keys from data_xxx */
160833      if( p->rc==SQLITE_OK ){
160834        p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
160835            sqlite3_mprintf(
160836              "SELECT %s, rbu_control%s FROM '%q'%s",
160837              zCollist, (bRbuRowid ? ", rbu_rowid" : ""),
160838              pIter->zDataTbl, zLimit
160839            )
160840        );
160841      }
160842
160843      sqlite3_free(zWhere);
160844      sqlite3_free(zOldlist);
160845      sqlite3_free(zNewlist);
160846      sqlite3_free(zBindings);
160847    }
160848    sqlite3_free(zCollist);
160849    sqlite3_free(zLimit);
160850  }
160851
160852  return p->rc;
160853}
160854
160855/*
160856** Set output variable *ppStmt to point to an UPDATE statement that may
160857** be used to update the imposter table for the main table b-tree of the
160858** table object that pIter currently points to, assuming that the
160859** rbu_control column of the data_xyz table contains zMask.
160860**
160861** If the zMask string does not specify any columns to update, then this
160862** is not an error. Output variable *ppStmt is set to NULL in this case.
160863*/
160864static int rbuGetUpdateStmt(
160865  sqlite3rbu *p,                  /* RBU handle */
160866  RbuObjIter *pIter,              /* Object iterator */
160867  const char *zMask,              /* rbu_control value ('x.x.') */
160868  sqlite3_stmt **ppStmt           /* OUT: UPDATE statement handle */
160869){
160870  RbuUpdateStmt **pp;
160871  RbuUpdateStmt *pUp = 0;
160872  int nUp = 0;
160873
160874  /* In case an error occurs */
160875  *ppStmt = 0;
160876
160877  /* Search for an existing statement. If one is found, shift it to the front
160878  ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
160879  ** to the number of statements currently in the cache and pUp to the
160880  ** last object in the list.  */
160881  for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
160882    pUp = *pp;
160883    if( strcmp(pUp->zMask, zMask)==0 ){
160884      *pp = pUp->pNext;
160885      pUp->pNext = pIter->pRbuUpdate;
160886      pIter->pRbuUpdate = pUp;
160887      *ppStmt = pUp->pUpdate;
160888      return SQLITE_OK;
160889    }
160890    nUp++;
160891  }
160892  assert( pUp==0 || pUp->pNext==0 );
160893
160894  if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
160895    for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
160896    *pp = 0;
160897    sqlite3_finalize(pUp->pUpdate);
160898    pUp->pUpdate = 0;
160899  }else{
160900    pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
160901  }
160902
160903  if( pUp ){
160904    char *zWhere = rbuObjIterGetWhere(p, pIter);
160905    char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
160906    char *zUpdate = 0;
160907
160908    pUp->zMask = (char*)&pUp[1];
160909    memcpy(pUp->zMask, zMask, pIter->nTblCol);
160910    pUp->pNext = pIter->pRbuUpdate;
160911    pIter->pRbuUpdate = pUp;
160912
160913    if( zSet ){
160914      const char *zPrefix = "";
160915
160916      if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
160917      zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
160918          zPrefix, pIter->zTbl, zSet, zWhere
160919      );
160920      p->rc = prepareFreeAndCollectError(
160921          p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
160922      );
160923      *ppStmt = pUp->pUpdate;
160924    }
160925    sqlite3_free(zWhere);
160926    sqlite3_free(zSet);
160927  }
160928
160929  return p->rc;
160930}
160931
160932static sqlite3 *rbuOpenDbhandle(sqlite3rbu *p, const char *zName){
160933  sqlite3 *db = 0;
160934  if( p->rc==SQLITE_OK ){
160935    const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
160936    p->rc = sqlite3_open_v2(zName, &db, flags, p->zVfsName);
160937    if( p->rc ){
160938      p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
160939      sqlite3_close(db);
160940      db = 0;
160941    }
160942  }
160943  return db;
160944}
160945
160946/*
160947** Open the database handle and attach the RBU database as "rbu". If an
160948** error occurs, leave an error code and message in the RBU handle.
160949*/
160950static void rbuOpenDatabase(sqlite3rbu *p){
160951  assert( p->rc==SQLITE_OK );
160952  assert( p->dbMain==0 && p->dbRbu==0 );
160953
160954  p->eStage = 0;
160955  p->dbMain = rbuOpenDbhandle(p, p->zTarget);
160956  p->dbRbu = rbuOpenDbhandle(p, p->zRbu);
160957
160958  /* If using separate RBU and state databases, attach the state database to
160959  ** the RBU db handle now.  */
160960  if( p->zState ){
160961    rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
160962    memcpy(p->zStateDb, "stat", 4);
160963  }else{
160964    memcpy(p->zStateDb, "main", 4);
160965  }
160966
160967  if( p->rc==SQLITE_OK ){
160968    p->rc = sqlite3_create_function(p->dbMain,
160969        "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
160970    );
160971  }
160972
160973  if( p->rc==SQLITE_OK ){
160974    p->rc = sqlite3_create_function(p->dbMain,
160975        "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
160976    );
160977  }
160978
160979  if( p->rc==SQLITE_OK ){
160980    p->rc = sqlite3_create_function(p->dbRbu,
160981        "rbu_target_name", 1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
160982    );
160983  }
160984
160985  if( p->rc==SQLITE_OK ){
160986    p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
160987  }
160988  rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
160989
160990  /* Mark the database file just opened as an RBU target database. If
160991  ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
160992  ** This is an error.  */
160993  if( p->rc==SQLITE_OK ){
160994    p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
160995  }
160996
160997  if( p->rc==SQLITE_NOTFOUND ){
160998    p->rc = SQLITE_ERROR;
160999    p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
161000  }
161001}
161002
161003/*
161004** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
161005** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
161006**
161007** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
161008** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
161009** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
161010** three characters, then shorten the suffix on z[] to be the last three
161011** characters of the original suffix.
161012**
161013** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
161014** do the suffix shortening regardless of URI parameter.
161015**
161016** Examples:
161017**
161018**     test.db-journal    =>   test.nal
161019**     test.db-wal        =>   test.wal
161020**     test.db-shm        =>   test.shm
161021**     test.db-mj7f3319fa =>   test.9fa
161022*/
161023static void rbuFileSuffix3(const char *zBase, char *z){
161024#ifdef SQLITE_ENABLE_8_3_NAMES
161025#if SQLITE_ENABLE_8_3_NAMES<2
161026  if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
161027#endif
161028  {
161029    int i, sz;
161030    sz = sqlite3Strlen30(z);
161031    for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
161032    if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
161033  }
161034#endif
161035}
161036
161037/*
161038** Return the current wal-index header checksum for the target database
161039** as a 64-bit integer.
161040**
161041** The checksum is store in the first page of xShmMap memory as an 8-byte
161042** blob starting at byte offset 40.
161043*/
161044static i64 rbuShmChecksum(sqlite3rbu *p){
161045  i64 iRet = 0;
161046  if( p->rc==SQLITE_OK ){
161047    sqlite3_file *pDb = p->pTargetFd->pReal;
161048    u32 volatile *ptr;
161049    p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
161050    if( p->rc==SQLITE_OK ){
161051      iRet = ((i64)ptr[10] << 32) + ptr[11];
161052    }
161053  }
161054  return iRet;
161055}
161056
161057/*
161058** This function is called as part of initializing or reinitializing an
161059** incremental checkpoint.
161060**
161061** It populates the sqlite3rbu.aFrame[] array with the set of
161062** (wal frame -> db page) copy operations required to checkpoint the
161063** current wal file, and obtains the set of shm locks required to safely
161064** perform the copy operations directly on the file-system.
161065**
161066** If argument pState is not NULL, then the incremental checkpoint is
161067** being resumed. In this case, if the checksum of the wal-index-header
161068** following recovery is not the same as the checksum saved in the RbuState
161069** object, then the rbu handle is set to DONE state. This occurs if some
161070** other client appends a transaction to the wal file in the middle of
161071** an incremental checkpoint.
161072*/
161073static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
161074
161075  /* If pState is NULL, then the wal file may not have been opened and
161076  ** recovered. Running a read-statement here to ensure that doing so
161077  ** does not interfere with the "capture" process below.  */
161078  if( pState==0 ){
161079    p->eStage = 0;
161080    if( p->rc==SQLITE_OK ){
161081      p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
161082    }
161083  }
161084
161085  /* Assuming no error has occurred, run a "restart" checkpoint with the
161086  ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
161087  ** special behaviour in the rbu VFS:
161088  **
161089  **   * If the exclusive shm WRITER or READ0 lock cannot be obtained,
161090  **     the checkpoint fails with SQLITE_BUSY (normally SQLite would
161091  **     proceed with running a passive checkpoint instead of failing).
161092  **
161093  **   * Attempts to read from the *-wal file or write to the database file
161094  **     do not perform any IO. Instead, the frame/page combinations that
161095  **     would be read/written are recorded in the sqlite3rbu.aFrame[]
161096  **     array.
161097  **
161098  **   * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
161099  **     READ0 and CHECKPOINT locks taken as part of the checkpoint are
161100  **     no-ops. These locks will not be released until the connection
161101  **     is closed.
161102  **
161103  **   * Attempting to xSync() the database file causes an SQLITE_INTERNAL
161104  **     error.
161105  **
161106  ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
161107  ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
161108  ** array populated with a set of (frame -> page) mappings. Because the
161109  ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
161110  ** data from the wal file into the database file according to the
161111  ** contents of aFrame[].
161112  */
161113  if( p->rc==SQLITE_OK ){
161114    int rc2;
161115    p->eStage = RBU_STAGE_CAPTURE;
161116    rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
161117    if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
161118  }
161119
161120  if( p->rc==SQLITE_OK ){
161121    p->eStage = RBU_STAGE_CKPT;
161122    p->nStep = (pState ? pState->nRow : 0);
161123    p->aBuf = rbuMalloc(p, p->pgsz);
161124    p->iWalCksum = rbuShmChecksum(p);
161125  }
161126
161127  if( p->rc==SQLITE_OK && pState && pState->iWalCksum!=p->iWalCksum ){
161128    p->rc = SQLITE_DONE;
161129    p->eStage = RBU_STAGE_DONE;
161130  }
161131}
161132
161133/*
161134** Called when iAmt bytes are read from offset iOff of the wal file while
161135** the rbu object is in capture mode. Record the frame number of the frame
161136** being read in the aFrame[] array.
161137*/
161138static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
161139  const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
161140  u32 iFrame;
161141
161142  if( pRbu->mLock!=mReq ){
161143    pRbu->rc = SQLITE_BUSY;
161144    return SQLITE_INTERNAL;
161145  }
161146
161147  pRbu->pgsz = iAmt;
161148  if( pRbu->nFrame==pRbu->nFrameAlloc ){
161149    int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
161150    RbuFrame *aNew;
161151    aNew = (RbuFrame*)sqlite3_realloc(pRbu->aFrame, nNew * sizeof(RbuFrame));
161152    if( aNew==0 ) return SQLITE_NOMEM;
161153    pRbu->aFrame = aNew;
161154    pRbu->nFrameAlloc = nNew;
161155  }
161156
161157  iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
161158  if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
161159  pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
161160  pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
161161  pRbu->nFrame++;
161162  return SQLITE_OK;
161163}
161164
161165/*
161166** Called when a page of data is written to offset iOff of the database
161167** file while the rbu handle is in capture mode. Record the page number
161168** of the page being written in the aFrame[] array.
161169*/
161170static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
161171  pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
161172  return SQLITE_OK;
161173}
161174
161175/*
161176** This is called as part of an incremental checkpoint operation. Copy
161177** a single frame of data from the wal file into the database file, as
161178** indicated by the RbuFrame object.
161179*/
161180static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
161181  sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
161182  sqlite3_file *pDb = p->pTargetFd->pReal;
161183  i64 iOff;
161184
161185  assert( p->rc==SQLITE_OK );
161186  iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
161187  p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
161188  if( p->rc ) return;
161189
161190  iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
161191  p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
161192}
161193
161194
161195/*
161196** Take an EXCLUSIVE lock on the database file.
161197*/
161198static void rbuLockDatabase(sqlite3rbu *p){
161199  sqlite3_file *pReal = p->pTargetFd->pReal;
161200  assert( p->rc==SQLITE_OK );
161201  p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
161202  if( p->rc==SQLITE_OK ){
161203    p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
161204  }
161205}
161206
161207#if defined(_WIN32_WCE)
161208static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
161209  int nChar;
161210  LPWSTR zWideFilename;
161211
161212  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
161213  if( nChar==0 ){
161214    return 0;
161215  }
161216  zWideFilename = sqlite3_malloc( nChar*sizeof(zWideFilename[0]) );
161217  if( zWideFilename==0 ){
161218    return 0;
161219  }
161220  memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
161221  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
161222                                nChar);
161223  if( nChar==0 ){
161224    sqlite3_free(zWideFilename);
161225    zWideFilename = 0;
161226  }
161227  return zWideFilename;
161228}
161229#endif
161230
161231/*
161232** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
161233** on the database file. This proc moves the *-oal file to the *-wal path,
161234** then reopens the database file (this time in vanilla, non-oal, WAL mode).
161235** If an error occurs, leave an error code and error message in the rbu
161236** handle.
161237*/
161238static void rbuMoveOalFile(sqlite3rbu *p){
161239  const char *zBase = sqlite3_db_filename(p->dbMain, "main");
161240
161241  char *zWal = sqlite3_mprintf("%s-wal", zBase);
161242  char *zOal = sqlite3_mprintf("%s-oal", zBase);
161243
161244  assert( p->eStage==RBU_STAGE_MOVE );
161245  assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
161246  if( zWal==0 || zOal==0 ){
161247    p->rc = SQLITE_NOMEM;
161248  }else{
161249    /* Move the *-oal file to *-wal. At this point connection p->db is
161250    ** holding a SHARED lock on the target database file (because it is
161251    ** in WAL mode). So no other connection may be writing the db.
161252    **
161253    ** In order to ensure that there are no database readers, an EXCLUSIVE
161254    ** lock is obtained here before the *-oal is moved to *-wal.
161255    */
161256    rbuLockDatabase(p);
161257    if( p->rc==SQLITE_OK ){
161258      rbuFileSuffix3(zBase, zWal);
161259      rbuFileSuffix3(zBase, zOal);
161260
161261      /* Re-open the databases. */
161262      rbuObjIterFinalize(&p->objiter);
161263      sqlite3_close(p->dbMain);
161264      sqlite3_close(p->dbRbu);
161265      p->dbMain = 0;
161266      p->dbRbu = 0;
161267
161268#if defined(_WIN32_WCE)
161269      {
161270        LPWSTR zWideOal;
161271        LPWSTR zWideWal;
161272
161273        zWideOal = rbuWinUtf8ToUnicode(zOal);
161274        if( zWideOal ){
161275          zWideWal = rbuWinUtf8ToUnicode(zWal);
161276          if( zWideWal ){
161277            if( MoveFileW(zWideOal, zWideWal) ){
161278              p->rc = SQLITE_OK;
161279            }else{
161280              p->rc = SQLITE_IOERR;
161281            }
161282            sqlite3_free(zWideWal);
161283          }else{
161284            p->rc = SQLITE_IOERR_NOMEM;
161285          }
161286          sqlite3_free(zWideOal);
161287        }else{
161288          p->rc = SQLITE_IOERR_NOMEM;
161289        }
161290      }
161291#else
161292      p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
161293#endif
161294
161295      if( p->rc==SQLITE_OK ){
161296        rbuOpenDatabase(p);
161297        rbuSetupCheckpoint(p, 0);
161298      }
161299    }
161300  }
161301
161302  sqlite3_free(zWal);
161303  sqlite3_free(zOal);
161304}
161305
161306/*
161307** The SELECT statement iterating through the keys for the current object
161308** (p->objiter.pSelect) currently points to a valid row. This function
161309** determines the type of operation requested by this row and returns
161310** one of the following values to indicate the result:
161311**
161312**     * RBU_INSERT
161313**     * RBU_DELETE
161314**     * RBU_IDX_DELETE
161315**     * RBU_UPDATE
161316**
161317** If RBU_UPDATE is returned, then output variable *pzMask is set to
161318** point to the text value indicating the columns to update.
161319**
161320** If the rbu_control field contains an invalid value, an error code and
161321** message are left in the RBU handle and zero returned.
161322*/
161323static int rbuStepType(sqlite3rbu *p, const char **pzMask){
161324  int iCol = p->objiter.nCol;     /* Index of rbu_control column */
161325  int res = 0;                    /* Return value */
161326
161327  switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
161328    case SQLITE_INTEGER: {
161329      int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
161330      if( iVal==0 ){
161331        res = RBU_INSERT;
161332      }else if( iVal==1 ){
161333        res = RBU_DELETE;
161334      }else if( iVal==2 ){
161335        res = RBU_IDX_DELETE;
161336      }else if( iVal==3 ){
161337        res = RBU_IDX_INSERT;
161338      }
161339      break;
161340    }
161341
161342    case SQLITE_TEXT: {
161343      const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
161344      if( z==0 ){
161345        p->rc = SQLITE_NOMEM;
161346      }else{
161347        *pzMask = (const char*)z;
161348      }
161349      res = RBU_UPDATE;
161350
161351      break;
161352    }
161353
161354    default:
161355      break;
161356  }
161357
161358  if( res==0 ){
161359    rbuBadControlError(p);
161360  }
161361  return res;
161362}
161363
161364#ifdef SQLITE_DEBUG
161365/*
161366** Assert that column iCol of statement pStmt is named zName.
161367*/
161368static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
161369  const char *zCol = sqlite3_column_name(pStmt, iCol);
161370  assert( 0==sqlite3_stricmp(zName, zCol) );
161371}
161372#else
161373# define assertColumnName(x,y,z)
161374#endif
161375
161376/*
161377** This function does the work for an sqlite3rbu_step() call.
161378**
161379** The object-iterator (p->objiter) currently points to a valid object,
161380** and the input cursor (p->objiter.pSelect) currently points to a valid
161381** input row. Perform whatever processing is required and return.
161382**
161383** If no  error occurs, SQLITE_OK is returned. Otherwise, an error code
161384** and message is left in the RBU handle and a copy of the error code
161385** returned.
161386*/
161387static int rbuStep(sqlite3rbu *p){
161388  RbuObjIter *pIter = &p->objiter;
161389  const char *zMask = 0;
161390  int i;
161391  int eType = rbuStepType(p, &zMask);
161392
161393  if( eType ){
161394    assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
161395
161396    if( pIter->zIdx==0 && eType==RBU_IDX_DELETE ){
161397      rbuBadControlError(p);
161398    }
161399    else if(
161400        eType==RBU_INSERT
161401     || eType==RBU_DELETE
161402     || eType==RBU_IDX_DELETE
161403     || eType==RBU_IDX_INSERT
161404    ){
161405      sqlite3_value *pVal;
161406      sqlite3_stmt *pWriter;
161407
161408      assert( eType!=RBU_UPDATE );
161409      assert( eType!=RBU_DELETE || pIter->zIdx==0 );
161410
161411      if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
161412        pWriter = pIter->pDelete;
161413      }else{
161414        pWriter = pIter->pInsert;
161415      }
161416
161417      for(i=0; i<pIter->nCol; i++){
161418        /* If this is an INSERT into a table b-tree and the table has an
161419        ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
161420        ** to write a NULL into the IPK column. That is not permitted.  */
161421        if( eType==RBU_INSERT
161422         && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
161423         && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
161424        ){
161425          p->rc = SQLITE_MISMATCH;
161426          p->zErrmsg = sqlite3_mprintf("datatype mismatch");
161427          goto step_out;
161428        }
161429
161430        if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
161431          continue;
161432        }
161433
161434        pVal = sqlite3_column_value(pIter->pSelect, i);
161435        p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
161436        if( p->rc ) goto step_out;
161437      }
161438      if( pIter->zIdx==0
161439       && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
161440      ){
161441        /* For a virtual table, or a table with no primary key, the
161442        ** SELECT statement is:
161443        **
161444        **   SELECT <cols>, rbu_control, rbu_rowid FROM ....
161445        **
161446        ** Hence column_value(pIter->nCol+1).
161447        */
161448        assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
161449        pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
161450        p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
161451      }
161452      if( p->rc==SQLITE_OK ){
161453        sqlite3_step(pWriter);
161454        p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
161455      }
161456    }else{
161457      sqlite3_value *pVal;
161458      sqlite3_stmt *pUpdate = 0;
161459      assert( eType==RBU_UPDATE );
161460      rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
161461      if( pUpdate ){
161462        for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
161463          char c = zMask[pIter->aiSrcOrder[i]];
161464          pVal = sqlite3_column_value(pIter->pSelect, i);
161465          if( pIter->abTblPk[i] || c!='.' ){
161466            p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
161467          }
161468        }
161469        if( p->rc==SQLITE_OK
161470         && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
161471        ){
161472          /* Bind the rbu_rowid value to column _rowid_ */
161473          assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
161474          pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
161475          p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
161476        }
161477        if( p->rc==SQLITE_OK ){
161478          sqlite3_step(pUpdate);
161479          p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
161480        }
161481      }
161482    }
161483  }
161484
161485 step_out:
161486  return p->rc;
161487}
161488
161489/*
161490** Increment the schema cookie of the main database opened by p->dbMain.
161491*/
161492static void rbuIncrSchemaCookie(sqlite3rbu *p){
161493  if( p->rc==SQLITE_OK ){
161494    int iCookie = 1000000;
161495    sqlite3_stmt *pStmt;
161496
161497    p->rc = prepareAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
161498        "PRAGMA schema_version"
161499    );
161500    if( p->rc==SQLITE_OK ){
161501      /* Coverage: it may be that this sqlite3_step() cannot fail. There
161502      ** is already a transaction open, so the prepared statement cannot
161503      ** throw an SQLITE_SCHEMA exception. The only database page the
161504      ** statement reads is page 1, which is guaranteed to be in the cache.
161505      ** And no memory allocations are required.  */
161506      if( SQLITE_ROW==sqlite3_step(pStmt) ){
161507        iCookie = sqlite3_column_int(pStmt, 0);
161508      }
161509      rbuFinalize(p, pStmt);
161510    }
161511    if( p->rc==SQLITE_OK ){
161512      rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
161513    }
161514  }
161515}
161516
161517/*
161518** Update the contents of the rbu_state table within the rbu database. The
161519** value stored in the RBU_STATE_STAGE column is eStage. All other values
161520** are determined by inspecting the rbu handle passed as the first argument.
161521*/
161522static void rbuSaveState(sqlite3rbu *p, int eStage){
161523  if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
161524    sqlite3_stmt *pInsert = 0;
161525    int rc;
161526
161527    assert( p->zErrmsg==0 );
161528    rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
161529        sqlite3_mprintf(
161530          "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
161531          "(%d, %d), "
161532          "(%d, %Q), "
161533          "(%d, %Q), "
161534          "(%d, %d), "
161535          "(%d, %d), "
161536          "(%d, %lld), "
161537          "(%d, %lld), "
161538          "(%d, %lld) ",
161539          p->zStateDb,
161540          RBU_STATE_STAGE, eStage,
161541          RBU_STATE_TBL, p->objiter.zTbl,
161542          RBU_STATE_IDX, p->objiter.zIdx,
161543          RBU_STATE_ROW, p->nStep,
161544          RBU_STATE_PROGRESS, p->nProgress,
161545          RBU_STATE_CKPT, p->iWalCksum,
161546          RBU_STATE_COOKIE, (i64)p->pTargetFd->iCookie,
161547          RBU_STATE_OALSZ, p->iOalSz
161548      )
161549    );
161550    assert( pInsert==0 || rc==SQLITE_OK );
161551
161552    if( rc==SQLITE_OK ){
161553      sqlite3_step(pInsert);
161554      rc = sqlite3_finalize(pInsert);
161555    }
161556    if( rc!=SQLITE_OK ) p->rc = rc;
161557  }
161558}
161559
161560
161561/*
161562** Step the RBU object.
161563*/
161564SQLITE_API int SQLITE_STDCALL sqlite3rbu_step(sqlite3rbu *p){
161565  if( p ){
161566    switch( p->eStage ){
161567      case RBU_STAGE_OAL: {
161568        RbuObjIter *pIter = &p->objiter;
161569        while( p->rc==SQLITE_OK && pIter->zTbl ){
161570
161571          if( pIter->bCleanup ){
161572            /* Clean up the rbu_tmp_xxx table for the previous table. It
161573            ** cannot be dropped as there are currently active SQL statements.
161574            ** But the contents can be deleted.  */
161575            if( pIter->abIndexed ){
161576              rbuMPrintfExec(p, p->dbRbu,
161577                  "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
161578              );
161579            }
161580          }else{
161581            rbuObjIterPrepareAll(p, pIter, 0);
161582
161583            /* Advance to the next row to process. */
161584            if( p->rc==SQLITE_OK ){
161585              int rc = sqlite3_step(pIter->pSelect);
161586              if( rc==SQLITE_ROW ){
161587                p->nProgress++;
161588                p->nStep++;
161589                return rbuStep(p);
161590              }
161591              p->rc = sqlite3_reset(pIter->pSelect);
161592              p->nStep = 0;
161593            }
161594          }
161595
161596          rbuObjIterNext(p, pIter);
161597        }
161598
161599        if( p->rc==SQLITE_OK ){
161600          assert( pIter->zTbl==0 );
161601          rbuSaveState(p, RBU_STAGE_MOVE);
161602          rbuIncrSchemaCookie(p);
161603          if( p->rc==SQLITE_OK ){
161604            p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
161605          }
161606          if( p->rc==SQLITE_OK ){
161607            p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
161608          }
161609          p->eStage = RBU_STAGE_MOVE;
161610        }
161611        break;
161612      }
161613
161614      case RBU_STAGE_MOVE: {
161615        if( p->rc==SQLITE_OK ){
161616          rbuMoveOalFile(p);
161617          p->nProgress++;
161618        }
161619        break;
161620      }
161621
161622      case RBU_STAGE_CKPT: {
161623        if( p->rc==SQLITE_OK ){
161624          if( p->nStep>=p->nFrame ){
161625            sqlite3_file *pDb = p->pTargetFd->pReal;
161626
161627            /* Sync the db file */
161628            p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
161629
161630            /* Update nBackfill */
161631            if( p->rc==SQLITE_OK ){
161632              void volatile *ptr;
161633              p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
161634              if( p->rc==SQLITE_OK ){
161635                ((u32 volatile*)ptr)[24] = p->iMaxFrame;
161636              }
161637            }
161638
161639            if( p->rc==SQLITE_OK ){
161640              p->eStage = RBU_STAGE_DONE;
161641              p->rc = SQLITE_DONE;
161642            }
161643          }else{
161644            RbuFrame *pFrame = &p->aFrame[p->nStep];
161645            rbuCheckpointFrame(p, pFrame);
161646            p->nStep++;
161647          }
161648          p->nProgress++;
161649        }
161650        break;
161651      }
161652
161653      default:
161654        break;
161655    }
161656    return p->rc;
161657  }else{
161658    return SQLITE_NOMEM;
161659  }
161660}
161661
161662/*
161663** Free an RbuState object allocated by rbuLoadState().
161664*/
161665static void rbuFreeState(RbuState *p){
161666  if( p ){
161667    sqlite3_free(p->zTbl);
161668    sqlite3_free(p->zIdx);
161669    sqlite3_free(p);
161670  }
161671}
161672
161673/*
161674** Allocate an RbuState object and load the contents of the rbu_state
161675** table into it. Return a pointer to the new object. It is the
161676** responsibility of the caller to eventually free the object using
161677** sqlite3_free().
161678**
161679** If an error occurs, leave an error code and message in the rbu handle
161680** and return NULL.
161681*/
161682static RbuState *rbuLoadState(sqlite3rbu *p){
161683  RbuState *pRet = 0;
161684  sqlite3_stmt *pStmt = 0;
161685  int rc;
161686  int rc2;
161687
161688  pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
161689  if( pRet==0 ) return 0;
161690
161691  rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
161692      sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
161693  );
161694  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
161695    switch( sqlite3_column_int(pStmt, 0) ){
161696      case RBU_STATE_STAGE:
161697        pRet->eStage = sqlite3_column_int(pStmt, 1);
161698        if( pRet->eStage!=RBU_STAGE_OAL
161699         && pRet->eStage!=RBU_STAGE_MOVE
161700         && pRet->eStage!=RBU_STAGE_CKPT
161701        ){
161702          p->rc = SQLITE_CORRUPT;
161703        }
161704        break;
161705
161706      case RBU_STATE_TBL:
161707        pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
161708        break;
161709
161710      case RBU_STATE_IDX:
161711        pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
161712        break;
161713
161714      case RBU_STATE_ROW:
161715        pRet->nRow = sqlite3_column_int(pStmt, 1);
161716        break;
161717
161718      case RBU_STATE_PROGRESS:
161719        pRet->nProgress = sqlite3_column_int64(pStmt, 1);
161720        break;
161721
161722      case RBU_STATE_CKPT:
161723        pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
161724        break;
161725
161726      case RBU_STATE_COOKIE:
161727        pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
161728        break;
161729
161730      case RBU_STATE_OALSZ:
161731        pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
161732        break;
161733
161734      default:
161735        rc = SQLITE_CORRUPT;
161736        break;
161737    }
161738  }
161739  rc2 = sqlite3_finalize(pStmt);
161740  if( rc==SQLITE_OK ) rc = rc2;
161741
161742  p->rc = rc;
161743  return pRet;
161744}
161745
161746/*
161747** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
161748** otherwise. Either or both argument may be NULL. Two NULL values are
161749** considered equal, and NULL is considered distinct from all other values.
161750*/
161751static int rbuStrCompare(const char *z1, const char *z2){
161752  if( z1==0 && z2==0 ) return 0;
161753  if( z1==0 || z2==0 ) return 1;
161754  return (sqlite3_stricmp(z1, z2)!=0);
161755}
161756
161757/*
161758** This function is called as part of sqlite3rbu_open() when initializing
161759** an rbu handle in OAL stage. If the rbu update has not started (i.e.
161760** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
161761** things so that the next call to sqlite3rbu_step() continues on from
161762** where the previous rbu handle left off.
161763**
161764** If an error occurs, an error code and error message are left in the
161765** rbu handle passed as the first argument.
161766*/
161767static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
161768  assert( p->rc==SQLITE_OK );
161769  if( pState->zTbl ){
161770    RbuObjIter *pIter = &p->objiter;
161771    int rc = SQLITE_OK;
161772
161773    while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
161774       || rbuStrCompare(pIter->zIdx, pState->zIdx)
161775       || rbuStrCompare(pIter->zTbl, pState->zTbl)
161776    )){
161777      rc = rbuObjIterNext(p, pIter);
161778    }
161779
161780    if( rc==SQLITE_OK && !pIter->zTbl ){
161781      rc = SQLITE_ERROR;
161782      p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
161783    }
161784
161785    if( rc==SQLITE_OK ){
161786      p->nStep = pState->nRow;
161787      rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
161788    }
161789
161790    p->rc = rc;
161791  }
161792}
161793
161794/*
161795** If there is a "*-oal" file in the file-system corresponding to the
161796** target database in the file-system, delete it. If an error occurs,
161797** leave an error code and error message in the rbu handle.
161798*/
161799static void rbuDeleteOalFile(sqlite3rbu *p){
161800  char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
161801  if( zOal ){
161802    sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
161803    assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
161804    pVfs->xDelete(pVfs, zOal, 0);
161805    sqlite3_free(zOal);
161806  }
161807}
161808
161809/*
161810** Allocate a private rbu VFS for the rbu handle passed as the only
161811** argument. This VFS will be used unless the call to sqlite3rbu_open()
161812** specified a URI with a vfs=? option in place of a target database
161813** file name.
161814*/
161815static void rbuCreateVfs(sqlite3rbu *p){
161816  int rnd;
161817  char zRnd[64];
161818
161819  assert( p->rc==SQLITE_OK );
161820  sqlite3_randomness(sizeof(int), (void*)&rnd);
161821  sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
161822  p->rc = sqlite3rbu_create_vfs(zRnd, 0);
161823  if( p->rc==SQLITE_OK ){
161824    sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
161825    assert( pVfs );
161826    p->zVfsName = pVfs->zName;
161827  }
161828}
161829
161830/*
161831** Destroy the private VFS created for the rbu handle passed as the only
161832** argument by an earlier call to rbuCreateVfs().
161833*/
161834static void rbuDeleteVfs(sqlite3rbu *p){
161835  if( p->zVfsName ){
161836    sqlite3rbu_destroy_vfs(p->zVfsName);
161837    p->zVfsName = 0;
161838  }
161839}
161840
161841/*
161842** Open and return a new RBU handle.
161843*/
161844SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
161845  const char *zTarget,
161846  const char *zRbu,
161847  const char *zState
161848){
161849  sqlite3rbu *p;
161850  int nTarget = strlen(zTarget);
161851  int nRbu = strlen(zRbu);
161852  int nState = zState ? strlen(zState) : 0;
161853
161854  p = (sqlite3rbu*)sqlite3_malloc(sizeof(sqlite3rbu)+nTarget+1+nRbu+1+nState+1);
161855  if( p ){
161856    RbuState *pState = 0;
161857
161858    /* Create the custom VFS. */
161859    memset(p, 0, sizeof(sqlite3rbu));
161860    rbuCreateVfs(p);
161861
161862    /* Open the target database */
161863    if( p->rc==SQLITE_OK ){
161864      p->zTarget = (char*)&p[1];
161865      memcpy(p->zTarget, zTarget, nTarget+1);
161866      p->zRbu = &p->zTarget[nTarget+1];
161867      memcpy(p->zRbu, zRbu, nRbu+1);
161868      if( zState ){
161869        p->zState = &p->zRbu[nRbu+1];
161870        memcpy(p->zState, zState, nState+1);
161871      }
161872      rbuOpenDatabase(p);
161873    }
161874
161875    /* If it has not already been created, create the rbu_state table */
161876    rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
161877
161878    if( p->rc==SQLITE_OK ){
161879      pState = rbuLoadState(p);
161880      assert( pState || p->rc!=SQLITE_OK );
161881      if( p->rc==SQLITE_OK ){
161882
161883        if( pState->eStage==0 ){
161884          rbuDeleteOalFile(p);
161885          p->eStage = RBU_STAGE_OAL;
161886        }else{
161887          p->eStage = pState->eStage;
161888        }
161889        p->nProgress = pState->nProgress;
161890        p->iOalSz = pState->iOalSz;
161891      }
161892    }
161893    assert( p->rc!=SQLITE_OK || p->eStage!=0 );
161894
161895    if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
161896      if( p->eStage==RBU_STAGE_OAL ){
161897        p->rc = SQLITE_ERROR;
161898        p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
161899      }else if( p->eStage==RBU_STAGE_MOVE ){
161900        p->eStage = RBU_STAGE_CKPT;
161901        p->nStep = 0;
161902      }
161903    }
161904
161905    if( p->rc==SQLITE_OK
161906     && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
161907     && pState->eStage!=0 && p->pTargetFd->iCookie!=pState->iCookie
161908    ){
161909      /* At this point (pTargetFd->iCookie) contains the value of the
161910      ** change-counter cookie (the thing that gets incremented when a
161911      ** transaction is committed in rollback mode) currently stored on
161912      ** page 1 of the database file. */
161913      p->rc = SQLITE_BUSY;
161914      p->zErrmsg = sqlite3_mprintf("database modified during rbu update");
161915    }
161916
161917    if( p->rc==SQLITE_OK ){
161918      if( p->eStage==RBU_STAGE_OAL ){
161919        sqlite3 *db = p->dbMain;
161920
161921        /* Open transactions both databases. The *-oal file is opened or
161922        ** created at this point. */
161923        p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
161924        if( p->rc==SQLITE_OK ){
161925          p->rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
161926        }
161927
161928        /* Check if the main database is a zipvfs db. If it is, set the upper
161929        ** level pager to use "journal_mode=off". This prevents it from
161930        ** generating a large journal using a temp file.  */
161931        if( p->rc==SQLITE_OK ){
161932          int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
161933          if( frc==SQLITE_OK ){
161934            p->rc = sqlite3_exec(db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
161935          }
161936        }
161937
161938        /* Point the object iterator at the first object */
161939        if( p->rc==SQLITE_OK ){
161940          p->rc = rbuObjIterFirst(p, &p->objiter);
161941        }
161942
161943        /* If the RBU database contains no data_xxx tables, declare the RBU
161944        ** update finished.  */
161945        if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
161946          p->rc = SQLITE_DONE;
161947        }
161948
161949        if( p->rc==SQLITE_OK ){
161950          rbuSetupOal(p, pState);
161951        }
161952
161953      }else if( p->eStage==RBU_STAGE_MOVE ){
161954        /* no-op */
161955      }else if( p->eStage==RBU_STAGE_CKPT ){
161956        rbuSetupCheckpoint(p, pState);
161957      }else if( p->eStage==RBU_STAGE_DONE ){
161958        p->rc = SQLITE_DONE;
161959      }else{
161960        p->rc = SQLITE_CORRUPT;
161961      }
161962    }
161963
161964    rbuFreeState(pState);
161965  }
161966
161967  return p;
161968}
161969
161970
161971/*
161972** Return the database handle used by pRbu.
161973*/
161974SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
161975  sqlite3 *db = 0;
161976  if( pRbu ){
161977    db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
161978  }
161979  return db;
161980}
161981
161982
161983/*
161984** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
161985** then edit any error message string so as to remove all occurrences of
161986** the pattern "rbu_imp_[0-9]*".
161987*/
161988static void rbuEditErrmsg(sqlite3rbu *p){
161989  if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
161990    int i;
161991    int nErrmsg = strlen(p->zErrmsg);
161992    for(i=0; i<(nErrmsg-8); i++){
161993      if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
161994        int nDel = 8;
161995        while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
161996        memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
161997        nErrmsg -= nDel;
161998      }
161999    }
162000  }
162001}
162002
162003/*
162004** Close the RBU handle.
162005*/
162006SQLITE_API int SQLITE_STDCALL sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
162007  int rc;
162008  if( p ){
162009
162010    /* Commit the transaction to the *-oal file. */
162011    if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
162012      p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
162013    }
162014
162015    rbuSaveState(p, p->eStage);
162016
162017    if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
162018      p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
162019    }
162020
162021    /* Close any open statement handles. */
162022    rbuObjIterFinalize(&p->objiter);
162023
162024    /* Close the open database handle and VFS object. */
162025    sqlite3_close(p->dbMain);
162026    sqlite3_close(p->dbRbu);
162027    rbuDeleteVfs(p);
162028    sqlite3_free(p->aBuf);
162029    sqlite3_free(p->aFrame);
162030
162031    rbuEditErrmsg(p);
162032    rc = p->rc;
162033    *pzErrmsg = p->zErrmsg;
162034    sqlite3_free(p);
162035  }else{
162036    rc = SQLITE_NOMEM;
162037    *pzErrmsg = 0;
162038  }
162039  return rc;
162040}
162041
162042/*
162043** Return the total number of key-value operations (inserts, deletes or
162044** updates) that have been performed on the target database since the
162045** current RBU update was started.
162046*/
162047SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3rbu_progress(sqlite3rbu *pRbu){
162048  return pRbu->nProgress;
162049}
162050
162051SQLITE_API int SQLITE_STDCALL sqlite3rbu_savestate(sqlite3rbu *p){
162052  int rc = p->rc;
162053
162054  if( rc==SQLITE_DONE ) return SQLITE_OK;
162055
162056  assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
162057  if( p->eStage==RBU_STAGE_OAL ){
162058    assert( rc!=SQLITE_DONE );
162059    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
162060  }
162061
162062  p->rc = rc;
162063  rbuSaveState(p, p->eStage);
162064  rc = p->rc;
162065
162066  if( p->eStage==RBU_STAGE_OAL ){
162067    assert( rc!=SQLITE_DONE );
162068    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
162069    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
162070    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
162071  }
162072
162073  p->rc = rc;
162074  return rc;
162075}
162076
162077/**************************************************************************
162078** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
162079** of a standard VFS in the following ways:
162080**
162081** 1. Whenever the first page of a main database file is read or
162082**    written, the value of the change-counter cookie is stored in
162083**    rbu_file.iCookie. Similarly, the value of the "write-version"
162084**    database header field is stored in rbu_file.iWriteVer. This ensures
162085**    that the values are always trustworthy within an open transaction.
162086**
162087** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
162088**    member variable of the associated database file descriptor is set
162089**    to point to the new file. A mutex protected linked list of all main
162090**    db fds opened using a particular RBU VFS is maintained at
162091**    rbu_vfs.pMain to facilitate this.
162092**
162093** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
162094**    object can be marked as the target database of an RBU update. This
162095**    turns on the following extra special behaviour:
162096**
162097** 3a. If xAccess() is called to check if there exists a *-wal file
162098**     associated with an RBU target database currently in RBU_STAGE_OAL
162099**     stage (preparing the *-oal file), the following special handling
162100**     applies:
162101**
162102**      * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
162103**        target database may not be in wal mode already.
162104**
162105**      * if the *-wal file does not exist, set the output parameter to
162106**        non-zero (to tell SQLite that it does exist) anyway.
162107**
162108**     Then, when xOpen() is called to open the *-wal file associated with
162109**     the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
162110**     file, the rbu vfs opens the corresponding *-oal file instead.
162111**
162112** 3b. The *-shm pages returned by xShmMap() for a target db file in
162113**     RBU_STAGE_OAL mode are actually stored in heap memory. This is to
162114**     avoid creating a *-shm file on disk. Additionally, xShmLock() calls
162115**     are no-ops on target database files in RBU_STAGE_OAL mode. This is
162116**     because assert() statements in some VFS implementations fail if
162117**     xShmLock() is called before xShmMap().
162118**
162119** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
162120**     mode except RBU_STAGE_DONE (all work completed and checkpointed), it
162121**     fails with an SQLITE_BUSY error. This is to stop RBU connections
162122**     from automatically checkpointing a *-wal (or *-oal) file from within
162123**     sqlite3_close().
162124**
162125** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
162126**     all xWrite() calls on the target database file perform no IO.
162127**     Instead the frame and page numbers that would be read and written
162128**     are recorded. Additionally, successful attempts to obtain exclusive
162129**     xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
162130**     database file are recorded. xShmLock() calls to unlock the same
162131**     locks are no-ops (so that once obtained, these locks are never
162132**     relinquished). Finally, calls to xSync() on the target database
162133**     file fail with SQLITE_INTERNAL errors.
162134*/
162135
162136static void rbuUnlockShm(rbu_file *p){
162137  if( p->pRbu ){
162138    int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
162139    int i;
162140    for(i=0; i<SQLITE_SHM_NLOCK;i++){
162141      if( (1<<i) & p->pRbu->mLock ){
162142        xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
162143      }
162144    }
162145    p->pRbu->mLock = 0;
162146  }
162147}
162148
162149/*
162150** Close an rbu file.
162151*/
162152static int rbuVfsClose(sqlite3_file *pFile){
162153  rbu_file *p = (rbu_file*)pFile;
162154  int rc;
162155  int i;
162156
162157  /* Free the contents of the apShm[] array. And the array itself. */
162158  for(i=0; i<p->nShm; i++){
162159    sqlite3_free(p->apShm[i]);
162160  }
162161  sqlite3_free(p->apShm);
162162  p->apShm = 0;
162163  sqlite3_free(p->zDel);
162164
162165  if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
162166    rbu_file **pp;
162167    sqlite3_mutex_enter(p->pRbuVfs->mutex);
162168    for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
162169    *pp = p->pMainNext;
162170    sqlite3_mutex_leave(p->pRbuVfs->mutex);
162171    rbuUnlockShm(p);
162172    p->pReal->pMethods->xShmUnmap(p->pReal, 0);
162173  }
162174
162175  /* Close the underlying file handle */
162176  rc = p->pReal->pMethods->xClose(p->pReal);
162177  return rc;
162178}
162179
162180
162181/*
162182** Read and return an unsigned 32-bit big-endian integer from the buffer
162183** passed as the only argument.
162184*/
162185static u32 rbuGetU32(u8 *aBuf){
162186  return ((u32)aBuf[0] << 24)
162187       + ((u32)aBuf[1] << 16)
162188       + ((u32)aBuf[2] <<  8)
162189       + ((u32)aBuf[3]);
162190}
162191
162192/*
162193** Read data from an rbuVfs-file.
162194*/
162195static int rbuVfsRead(
162196  sqlite3_file *pFile,
162197  void *zBuf,
162198  int iAmt,
162199  sqlite_int64 iOfst
162200){
162201  rbu_file *p = (rbu_file*)pFile;
162202  sqlite3rbu *pRbu = p->pRbu;
162203  int rc;
162204
162205  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
162206    assert( p->openFlags & SQLITE_OPEN_WAL );
162207    rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
162208  }else{
162209    if( pRbu && pRbu->eStage==RBU_STAGE_OAL
162210     && (p->openFlags & SQLITE_OPEN_WAL)
162211     && iOfst>=pRbu->iOalSz
162212    ){
162213      rc = SQLITE_OK;
162214      memset(zBuf, 0, iAmt);
162215    }else{
162216      rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
162217    }
162218    if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
162219      /* These look like magic numbers. But they are stable, as they are part
162220       ** of the definition of the SQLite file format, which may not change. */
162221      u8 *pBuf = (u8*)zBuf;
162222      p->iCookie = rbuGetU32(&pBuf[24]);
162223      p->iWriteVer = pBuf[19];
162224    }
162225  }
162226  return rc;
162227}
162228
162229/*
162230** Write data to an rbuVfs-file.
162231*/
162232static int rbuVfsWrite(
162233  sqlite3_file *pFile,
162234  const void *zBuf,
162235  int iAmt,
162236  sqlite_int64 iOfst
162237){
162238  rbu_file *p = (rbu_file*)pFile;
162239  sqlite3rbu *pRbu = p->pRbu;
162240  int rc;
162241
162242  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
162243    assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
162244    rc = rbuCaptureDbWrite(p->pRbu, iOfst);
162245  }else{
162246    if( pRbu && pRbu->eStage==RBU_STAGE_OAL
162247     && (p->openFlags & SQLITE_OPEN_WAL)
162248     && iOfst>=pRbu->iOalSz
162249    ){
162250      pRbu->iOalSz = iAmt + iOfst;
162251    }
162252    rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
162253    if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
162254      /* These look like magic numbers. But they are stable, as they are part
162255      ** of the definition of the SQLite file format, which may not change. */
162256      u8 *pBuf = (u8*)zBuf;
162257      p->iCookie = rbuGetU32(&pBuf[24]);
162258      p->iWriteVer = pBuf[19];
162259    }
162260  }
162261  return rc;
162262}
162263
162264/*
162265** Truncate an rbuVfs-file.
162266*/
162267static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
162268  rbu_file *p = (rbu_file*)pFile;
162269  return p->pReal->pMethods->xTruncate(p->pReal, size);
162270}
162271
162272/*
162273** Sync an rbuVfs-file.
162274*/
162275static int rbuVfsSync(sqlite3_file *pFile, int flags){
162276  rbu_file *p = (rbu_file *)pFile;
162277  if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
162278    if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
162279      return SQLITE_INTERNAL;
162280    }
162281    return SQLITE_OK;
162282  }
162283  return p->pReal->pMethods->xSync(p->pReal, flags);
162284}
162285
162286/*
162287** Return the current file-size of an rbuVfs-file.
162288*/
162289static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
162290  rbu_file *p = (rbu_file *)pFile;
162291  return p->pReal->pMethods->xFileSize(p->pReal, pSize);
162292}
162293
162294/*
162295** Lock an rbuVfs-file.
162296*/
162297static int rbuVfsLock(sqlite3_file *pFile, int eLock){
162298  rbu_file *p = (rbu_file*)pFile;
162299  sqlite3rbu *pRbu = p->pRbu;
162300  int rc = SQLITE_OK;
162301
162302  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
162303  if( pRbu && eLock==SQLITE_LOCK_EXCLUSIVE && pRbu->eStage!=RBU_STAGE_DONE ){
162304    /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
162305    ** prevents it from checkpointing the database from sqlite3_close(). */
162306    rc = SQLITE_BUSY;
162307  }else{
162308    rc = p->pReal->pMethods->xLock(p->pReal, eLock);
162309  }
162310
162311  return rc;
162312}
162313
162314/*
162315** Unlock an rbuVfs-file.
162316*/
162317static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
162318  rbu_file *p = (rbu_file *)pFile;
162319  return p->pReal->pMethods->xUnlock(p->pReal, eLock);
162320}
162321
162322/*
162323** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
162324*/
162325static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
162326  rbu_file *p = (rbu_file *)pFile;
162327  return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
162328}
162329
162330/*
162331** File control method. For custom operations on an rbuVfs-file.
162332*/
162333static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
162334  rbu_file *p = (rbu_file *)pFile;
162335  int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
162336  int rc;
162337
162338  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
162339       || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
162340  );
162341  if( op==SQLITE_FCNTL_RBU ){
162342    sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
162343
162344    /* First try to find another RBU vfs lower down in the vfs stack. If
162345    ** one is found, this vfs will operate in pass-through mode. The lower
162346    ** level vfs will do the special RBU handling.  */
162347    rc = xControl(p->pReal, op, pArg);
162348
162349    if( rc==SQLITE_NOTFOUND ){
162350      /* Now search for a zipvfs instance lower down in the VFS stack. If
162351      ** one is found, this is an error.  */
162352      void *dummy = 0;
162353      rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
162354      if( rc==SQLITE_OK ){
162355        rc = SQLITE_ERROR;
162356        pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
162357      }else if( rc==SQLITE_NOTFOUND ){
162358        pRbu->pTargetFd = p;
162359        p->pRbu = pRbu;
162360        if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
162361        rc = SQLITE_OK;
162362      }
162363    }
162364    return rc;
162365  }
162366
162367  rc = xControl(p->pReal, op, pArg);
162368  if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
162369    rbu_vfs *pRbuVfs = p->pRbuVfs;
162370    char *zIn = *(char**)pArg;
162371    char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
162372    *(char**)pArg = zOut;
162373    if( zOut==0 ) rc = SQLITE_NOMEM;
162374  }
162375
162376  return rc;
162377}
162378
162379/*
162380** Return the sector-size in bytes for an rbuVfs-file.
162381*/
162382static int rbuVfsSectorSize(sqlite3_file *pFile){
162383  rbu_file *p = (rbu_file *)pFile;
162384  return p->pReal->pMethods->xSectorSize(p->pReal);
162385}
162386
162387/*
162388** Return the device characteristic flags supported by an rbuVfs-file.
162389*/
162390static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
162391  rbu_file *p = (rbu_file *)pFile;
162392  return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
162393}
162394
162395/*
162396** Take or release a shared-memory lock.
162397*/
162398static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
162399  rbu_file *p = (rbu_file*)pFile;
162400  sqlite3rbu *pRbu = p->pRbu;
162401  int rc = SQLITE_OK;
162402
162403#ifdef SQLITE_AMALGAMATION
162404    assert( WAL_CKPT_LOCK==1 );
162405#endif
162406
162407  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
162408  if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
162409    /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
162410    ** taking this lock also prevents any checkpoints from occurring.
162411    ** todo: really, it's not clear why this might occur, as
162412    ** wal_autocheckpoint ought to be turned off.  */
162413    if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
162414  }else{
162415    int bCapture = 0;
162416    if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
162417     && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
162418     && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
162419    ){
162420      bCapture = 1;
162421    }
162422
162423    if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
162424      rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
162425      if( bCapture && rc==SQLITE_OK ){
162426        pRbu->mLock |= (1 << ofst);
162427      }
162428    }
162429  }
162430
162431  return rc;
162432}
162433
162434/*
162435** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
162436*/
162437static int rbuVfsShmMap(
162438  sqlite3_file *pFile,
162439  int iRegion,
162440  int szRegion,
162441  int isWrite,
162442  void volatile **pp
162443){
162444  rbu_file *p = (rbu_file*)pFile;
162445  int rc = SQLITE_OK;
162446  int eStage = (p->pRbu ? p->pRbu->eStage : 0);
162447
162448  /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
162449  ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
162450  ** instead of a file on disk.  */
162451  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
162452  if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
162453    if( iRegion<=p->nShm ){
162454      int nByte = (iRegion+1) * sizeof(char*);
162455      char **apNew = (char**)sqlite3_realloc(p->apShm, nByte);
162456      if( apNew==0 ){
162457        rc = SQLITE_NOMEM;
162458      }else{
162459        memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
162460        p->apShm = apNew;
162461        p->nShm = iRegion+1;
162462      }
162463    }
162464
162465    if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
162466      char *pNew = (char*)sqlite3_malloc(szRegion);
162467      if( pNew==0 ){
162468        rc = SQLITE_NOMEM;
162469      }else{
162470        memset(pNew, 0, szRegion);
162471        p->apShm[iRegion] = pNew;
162472      }
162473    }
162474
162475    if( rc==SQLITE_OK ){
162476      *pp = p->apShm[iRegion];
162477    }else{
162478      *pp = 0;
162479    }
162480  }else{
162481    assert( p->apShm==0 );
162482    rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
162483  }
162484
162485  return rc;
162486}
162487
162488/*
162489** Memory barrier.
162490*/
162491static void rbuVfsShmBarrier(sqlite3_file *pFile){
162492  rbu_file *p = (rbu_file *)pFile;
162493  p->pReal->pMethods->xShmBarrier(p->pReal);
162494}
162495
162496/*
162497** The xShmUnmap method.
162498*/
162499static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
162500  rbu_file *p = (rbu_file*)pFile;
162501  int rc = SQLITE_OK;
162502  int eStage = (p->pRbu ? p->pRbu->eStage : 0);
162503
162504  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
162505  if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
162506    /* no-op */
162507  }else{
162508    /* Release the checkpointer and writer locks */
162509    rbuUnlockShm(p);
162510    rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
162511  }
162512  return rc;
162513}
162514
162515/*
162516** Given that zWal points to a buffer containing a wal file name passed to
162517** either the xOpen() or xAccess() VFS method, return a pointer to the
162518** file-handle opened by the same database connection on the corresponding
162519** database file.
162520*/
162521static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
162522  rbu_file *pDb;
162523  sqlite3_mutex_enter(pRbuVfs->mutex);
162524  for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext);
162525  sqlite3_mutex_leave(pRbuVfs->mutex);
162526  return pDb;
162527}
162528
162529/*
162530** Open an rbu file handle.
162531*/
162532static int rbuVfsOpen(
162533  sqlite3_vfs *pVfs,
162534  const char *zName,
162535  sqlite3_file *pFile,
162536  int flags,
162537  int *pOutFlags
162538){
162539  static sqlite3_io_methods rbuvfs_io_methods = {
162540    2,                            /* iVersion */
162541    rbuVfsClose,                  /* xClose */
162542    rbuVfsRead,                   /* xRead */
162543    rbuVfsWrite,                  /* xWrite */
162544    rbuVfsTruncate,               /* xTruncate */
162545    rbuVfsSync,                   /* xSync */
162546    rbuVfsFileSize,               /* xFileSize */
162547    rbuVfsLock,                   /* xLock */
162548    rbuVfsUnlock,                 /* xUnlock */
162549    rbuVfsCheckReservedLock,      /* xCheckReservedLock */
162550    rbuVfsFileControl,            /* xFileControl */
162551    rbuVfsSectorSize,             /* xSectorSize */
162552    rbuVfsDeviceCharacteristics,  /* xDeviceCharacteristics */
162553    rbuVfsShmMap,                 /* xShmMap */
162554    rbuVfsShmLock,                /* xShmLock */
162555    rbuVfsShmBarrier,             /* xShmBarrier */
162556    rbuVfsShmUnmap,               /* xShmUnmap */
162557    0, 0                          /* xFetch, xUnfetch */
162558  };
162559  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
162560  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
162561  rbu_file *pFd = (rbu_file *)pFile;
162562  int rc = SQLITE_OK;
162563  const char *zOpen = zName;
162564
162565  memset(pFd, 0, sizeof(rbu_file));
162566  pFd->pReal = (sqlite3_file*)&pFd[1];
162567  pFd->pRbuVfs = pRbuVfs;
162568  pFd->openFlags = flags;
162569  if( zName ){
162570    if( flags & SQLITE_OPEN_MAIN_DB ){
162571      /* A main database has just been opened. The following block sets
162572      ** (pFd->zWal) to point to a buffer owned by SQLite that contains
162573      ** the name of the *-wal file this db connection will use. SQLite
162574      ** happens to pass a pointer to this buffer when using xAccess()
162575      ** or xOpen() to operate on the *-wal file.  */
162576      int n = strlen(zName);
162577      const char *z = &zName[n];
162578      if( flags & SQLITE_OPEN_URI ){
162579        int odd = 0;
162580        while( 1 ){
162581          if( z[0]==0 ){
162582            odd = 1 - odd;
162583            if( odd && z[1]==0 ) break;
162584          }
162585          z++;
162586        }
162587        z += 2;
162588      }else{
162589        while( *z==0 ) z++;
162590      }
162591      z += (n + 8 + 1);
162592      pFd->zWal = z;
162593    }
162594    else if( flags & SQLITE_OPEN_WAL ){
162595      rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
162596      if( pDb ){
162597        if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
162598          /* This call is to open a *-wal file. Intead, open the *-oal. This
162599          ** code ensures that the string passed to xOpen() is terminated by a
162600          ** pair of '\0' bytes in case the VFS attempts to extract a URI
162601          ** parameter from it.  */
162602          int nCopy = strlen(zName);
162603          char *zCopy = sqlite3_malloc(nCopy+2);
162604          if( zCopy ){
162605            memcpy(zCopy, zName, nCopy);
162606            zCopy[nCopy-3] = 'o';
162607            zCopy[nCopy] = '\0';
162608            zCopy[nCopy+1] = '\0';
162609            zOpen = (const char*)(pFd->zDel = zCopy);
162610          }else{
162611            rc = SQLITE_NOMEM;
162612          }
162613          pFd->pRbu = pDb->pRbu;
162614        }
162615        pDb->pWalFd = pFd;
162616      }
162617    }
162618  }
162619
162620  if( rc==SQLITE_OK ){
162621    rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, flags, pOutFlags);
162622  }
162623  if( pFd->pReal->pMethods ){
162624    /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
162625    ** pointer and, if the file is a main database file, link it into the
162626    ** mutex protected linked list of all such files.  */
162627    pFile->pMethods = &rbuvfs_io_methods;
162628    if( flags & SQLITE_OPEN_MAIN_DB ){
162629      sqlite3_mutex_enter(pRbuVfs->mutex);
162630      pFd->pMainNext = pRbuVfs->pMain;
162631      pRbuVfs->pMain = pFd;
162632      sqlite3_mutex_leave(pRbuVfs->mutex);
162633    }
162634  }else{
162635    sqlite3_free(pFd->zDel);
162636  }
162637
162638  return rc;
162639}
162640
162641/*
162642** Delete the file located at zPath.
162643*/
162644static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
162645  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
162646  return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
162647}
162648
162649/*
162650** Test for access permissions. Return true if the requested permission
162651** is available, or false otherwise.
162652*/
162653static int rbuVfsAccess(
162654  sqlite3_vfs *pVfs,
162655  const char *zPath,
162656  int flags,
162657  int *pResOut
162658){
162659  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
162660  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
162661  int rc;
162662
162663  rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
162664
162665  /* If this call is to check if a *-wal file associated with an RBU target
162666  ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
162667  ** the following special handling is activated:
162668  **
162669  **   a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
162670  **      ensures that the RBU extension never tries to update a database
162671  **      in wal mode, even if the first page of the database file has
162672  **      been damaged.
162673  **
162674  **   b) if the *-wal file does not exist, claim that it does anyway,
162675  **      causing SQLite to call xOpen() to open it. This call will also
162676  **      be intercepted (see the rbuVfsOpen() function) and the *-oal
162677  **      file opened instead.
162678  */
162679  if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
162680    rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
162681    if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
162682      if( *pResOut ){
162683        rc = SQLITE_CANTOPEN;
162684      }else{
162685        *pResOut = 1;
162686      }
162687    }
162688  }
162689
162690  return rc;
162691}
162692
162693/*
162694** Populate buffer zOut with the full canonical pathname corresponding
162695** to the pathname in zPath. zOut is guaranteed to point to a buffer
162696** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
162697*/
162698static int rbuVfsFullPathname(
162699  sqlite3_vfs *pVfs,
162700  const char *zPath,
162701  int nOut,
162702  char *zOut
162703){
162704  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
162705  return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
162706}
162707
162708#ifndef SQLITE_OMIT_LOAD_EXTENSION
162709/*
162710** Open the dynamic library located at zPath and return a handle.
162711*/
162712static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
162713  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
162714  return pRealVfs->xDlOpen(pRealVfs, zPath);
162715}
162716
162717/*
162718** Populate the buffer zErrMsg (size nByte bytes) with a human readable
162719** utf-8 string describing the most recent error encountered associated
162720** with dynamic libraries.
162721*/
162722static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
162723  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
162724  pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
162725}
162726
162727/*
162728** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
162729*/
162730static void (*rbuVfsDlSym(
162731  sqlite3_vfs *pVfs,
162732  void *pArg,
162733  const char *zSym
162734))(void){
162735  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
162736  return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
162737}
162738
162739/*
162740** Close the dynamic library handle pHandle.
162741*/
162742static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
162743  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
162744  pRealVfs->xDlClose(pRealVfs, pHandle);
162745}
162746#endif /* SQLITE_OMIT_LOAD_EXTENSION */
162747
162748/*
162749** Populate the buffer pointed to by zBufOut with nByte bytes of
162750** random data.
162751*/
162752static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
162753  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
162754  return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
162755}
162756
162757/*
162758** Sleep for nMicro microseconds. Return the number of microseconds
162759** actually slept.
162760*/
162761static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
162762  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
162763  return pRealVfs->xSleep(pRealVfs, nMicro);
162764}
162765
162766/*
162767** Return the current time as a Julian Day number in *pTimeOut.
162768*/
162769static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
162770  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
162771  return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
162772}
162773
162774/*
162775** No-op.
162776*/
162777static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
162778  return 0;
162779}
162780
162781/*
162782** Deregister and destroy an RBU vfs created by an earlier call to
162783** sqlite3rbu_create_vfs().
162784*/
162785SQLITE_API void SQLITE_STDCALL sqlite3rbu_destroy_vfs(const char *zName){
162786  sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
162787  if( pVfs && pVfs->xOpen==rbuVfsOpen ){
162788    sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
162789    sqlite3_vfs_unregister(pVfs);
162790    sqlite3_free(pVfs);
162791  }
162792}
162793
162794/*
162795** Create an RBU VFS named zName that accesses the underlying file-system
162796** via existing VFS zParent. The new object is registered as a non-default
162797** VFS with SQLite before returning.
162798*/
162799SQLITE_API int SQLITE_STDCALL sqlite3rbu_create_vfs(const char *zName, const char *zParent){
162800
162801  /* Template for VFS */
162802  static sqlite3_vfs vfs_template = {
162803    1,                            /* iVersion */
162804    0,                            /* szOsFile */
162805    0,                            /* mxPathname */
162806    0,                            /* pNext */
162807    0,                            /* zName */
162808    0,                            /* pAppData */
162809    rbuVfsOpen,                   /* xOpen */
162810    rbuVfsDelete,                 /* xDelete */
162811    rbuVfsAccess,                 /* xAccess */
162812    rbuVfsFullPathname,           /* xFullPathname */
162813
162814#ifndef SQLITE_OMIT_LOAD_EXTENSION
162815    rbuVfsDlOpen,                 /* xDlOpen */
162816    rbuVfsDlError,                /* xDlError */
162817    rbuVfsDlSym,                  /* xDlSym */
162818    rbuVfsDlClose,                /* xDlClose */
162819#else
162820    0, 0, 0, 0,
162821#endif
162822
162823    rbuVfsRandomness,             /* xRandomness */
162824    rbuVfsSleep,                  /* xSleep */
162825    rbuVfsCurrentTime,            /* xCurrentTime */
162826    rbuVfsGetLastError,           /* xGetLastError */
162827    0,                            /* xCurrentTimeInt64 (version 2) */
162828    0, 0, 0                       /* Unimplemented version 3 methods */
162829  };
162830
162831  rbu_vfs *pNew = 0;              /* Newly allocated VFS */
162832  int nName;
162833  int rc = SQLITE_OK;
162834
162835  int nByte;
162836  nName = strlen(zName);
162837  nByte = sizeof(rbu_vfs) + nName + 1;
162838  pNew = (rbu_vfs*)sqlite3_malloc(nByte);
162839  if( pNew==0 ){
162840    rc = SQLITE_NOMEM;
162841  }else{
162842    sqlite3_vfs *pParent;           /* Parent VFS */
162843    memset(pNew, 0, nByte);
162844    pParent = sqlite3_vfs_find(zParent);
162845    if( pParent==0 ){
162846      rc = SQLITE_NOTFOUND;
162847    }else{
162848      char *zSpace;
162849      memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
162850      pNew->base.mxPathname = pParent->mxPathname;
162851      pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
162852      pNew->pRealVfs = pParent;
162853      pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
162854      memcpy(zSpace, zName, nName);
162855
162856      /* Allocate the mutex and register the new VFS (not as the default) */
162857      pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
162858      if( pNew->mutex==0 ){
162859        rc = SQLITE_NOMEM;
162860      }else{
162861        rc = sqlite3_vfs_register(&pNew->base, 0);
162862      }
162863    }
162864
162865    if( rc!=SQLITE_OK ){
162866      sqlite3_mutex_free(pNew->mutex);
162867      sqlite3_free(pNew);
162868    }
162869  }
162870
162871  return rc;
162872}
162873
162874
162875/**************************************************************************/
162876
162877#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
162878
162879/************** End of sqlite3rbu.c ******************************************/
162880/************** Begin file dbstat.c ******************************************/
162881/*
162882** 2010 July 12
162883**
162884** The author disclaims copyright to this source code.  In place of
162885** a legal notice, here is a blessing:
162886**
162887**    May you do good and not evil.
162888**    May you find forgiveness for yourself and forgive others.
162889**    May you share freely, never taking more than you give.
162890**
162891******************************************************************************
162892**
162893** This file contains an implementation of the "dbstat" virtual table.
162894**
162895** The dbstat virtual table is used to extract low-level formatting
162896** information from an SQLite database in order to implement the
162897** "sqlite3_analyzer" utility.  See the ../tool/spaceanal.tcl script
162898** for an example implementation.
162899**
162900** Additional information is available on the "dbstat.html" page of the
162901** official SQLite documentation.
162902*/
162903
162904/* #include "sqliteInt.h"   ** Requires access to internal data structures ** */
162905#if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
162906    && !defined(SQLITE_OMIT_VIRTUALTABLE)
162907
162908/*
162909** Page paths:
162910**
162911**   The value of the 'path' column describes the path taken from the
162912**   root-node of the b-tree structure to each page. The value of the
162913**   root-node path is '/'.
162914**
162915**   The value of the path for the left-most child page of the root of
162916**   a b-tree is '/000/'. (Btrees store content ordered from left to right
162917**   so the pages to the left have smaller keys than the pages to the right.)
162918**   The next to left-most child of the root page is
162919**   '/001', and so on, each sibling page identified by a 3-digit hex
162920**   value. The children of the 451st left-most sibling have paths such
162921**   as '/1c2/000/, '/1c2/001/' etc.
162922**
162923**   Overflow pages are specified by appending a '+' character and a
162924**   six-digit hexadecimal value to the path to the cell they are linked
162925**   from. For example, the three overflow pages in a chain linked from
162926**   the left-most cell of the 450th child of the root page are identified
162927**   by the paths:
162928**
162929**      '/1c2/000+000000'         // First page in overflow chain
162930**      '/1c2/000+000001'         // Second page in overflow chain
162931**      '/1c2/000+000002'         // Third page in overflow chain
162932**
162933**   If the paths are sorted using the BINARY collation sequence, then
162934**   the overflow pages associated with a cell will appear earlier in the
162935**   sort-order than its child page:
162936**
162937**      '/1c2/000/'               // Left-most child of 451st child of root
162938*/
162939#define VTAB_SCHEMA                                                         \
162940  "CREATE TABLE xx( "                                                       \
162941  "  name       STRING,           /* Name of table or index */"             \
162942  "  path       INTEGER,          /* Path to page from root */"             \
162943  "  pageno     INTEGER,          /* Page number */"                        \
162944  "  pagetype   STRING,           /* 'internal', 'leaf' or 'overflow' */"   \
162945  "  ncell      INTEGER,          /* Cells on page (0 for overflow) */"     \
162946  "  payload    INTEGER,          /* Bytes of payload on this page */"      \
162947  "  unused     INTEGER,          /* Bytes of unused space on this page */" \
162948  "  mx_payload INTEGER,          /* Largest payload size of all cells */"  \
162949  "  pgoffset   INTEGER,          /* Offset of page in file */"             \
162950  "  pgsize     INTEGER,          /* Size of the page */"                   \
162951  "  schema     TEXT HIDDEN       /* Database schema being analyzed */"     \
162952  ");"
162953
162954
162955typedef struct StatTable StatTable;
162956typedef struct StatCursor StatCursor;
162957typedef struct StatPage StatPage;
162958typedef struct StatCell StatCell;
162959
162960struct StatCell {
162961  int nLocal;                     /* Bytes of local payload */
162962  u32 iChildPg;                   /* Child node (or 0 if this is a leaf) */
162963  int nOvfl;                      /* Entries in aOvfl[] */
162964  u32 *aOvfl;                     /* Array of overflow page numbers */
162965  int nLastOvfl;                  /* Bytes of payload on final overflow page */
162966  int iOvfl;                      /* Iterates through aOvfl[] */
162967};
162968
162969struct StatPage {
162970  u32 iPgno;
162971  DbPage *pPg;
162972  int iCell;
162973
162974  char *zPath;                    /* Path to this page */
162975
162976  /* Variables populated by statDecodePage(): */
162977  u8 flags;                       /* Copy of flags byte */
162978  int nCell;                      /* Number of cells on page */
162979  int nUnused;                    /* Number of unused bytes on page */
162980  StatCell *aCell;                /* Array of parsed cells */
162981  u32 iRightChildPg;              /* Right-child page number (or 0) */
162982  int nMxPayload;                 /* Largest payload of any cell on this page */
162983};
162984
162985struct StatCursor {
162986  sqlite3_vtab_cursor base;
162987  sqlite3_stmt *pStmt;            /* Iterates through set of root pages */
162988  int isEof;                      /* After pStmt has returned SQLITE_DONE */
162989  int iDb;                        /* Schema used for this query */
162990
162991  StatPage aPage[32];
162992  int iPage;                      /* Current entry in aPage[] */
162993
162994  /* Values to return. */
162995  char *zName;                    /* Value of 'name' column */
162996  char *zPath;                    /* Value of 'path' column */
162997  u32 iPageno;                    /* Value of 'pageno' column */
162998  char *zPagetype;                /* Value of 'pagetype' column */
162999  int nCell;                      /* Value of 'ncell' column */
163000  int nPayload;                   /* Value of 'payload' column */
163001  int nUnused;                    /* Value of 'unused' column */
163002  int nMxPayload;                 /* Value of 'mx_payload' column */
163003  i64 iOffset;                    /* Value of 'pgOffset' column */
163004  int szPage;                     /* Value of 'pgSize' column */
163005};
163006
163007struct StatTable {
163008  sqlite3_vtab base;
163009  sqlite3 *db;
163010  int iDb;                        /* Index of database to analyze */
163011};
163012
163013#ifndef get2byte
163014# define get2byte(x)   ((x)[0]<<8 | (x)[1])
163015#endif
163016
163017/*
163018** Connect to or create a statvfs virtual table.
163019*/
163020static int statConnect(
163021  sqlite3 *db,
163022  void *pAux,
163023  int argc, const char *const*argv,
163024  sqlite3_vtab **ppVtab,
163025  char **pzErr
163026){
163027  StatTable *pTab = 0;
163028  int rc = SQLITE_OK;
163029  int iDb;
163030
163031  if( argc>=4 ){
163032    iDb = sqlite3FindDbName(db, argv[3]);
163033    if( iDb<0 ){
163034      *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
163035      return SQLITE_ERROR;
163036    }
163037  }else{
163038    iDb = 0;
163039  }
163040  rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
163041  if( rc==SQLITE_OK ){
163042    pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
163043    if( pTab==0 ) rc = SQLITE_NOMEM;
163044  }
163045
163046  assert( rc==SQLITE_OK || pTab==0 );
163047  if( rc==SQLITE_OK ){
163048    memset(pTab, 0, sizeof(StatTable));
163049    pTab->db = db;
163050    pTab->iDb = iDb;
163051  }
163052
163053  *ppVtab = (sqlite3_vtab*)pTab;
163054  return rc;
163055}
163056
163057/*
163058** Disconnect from or destroy a statvfs virtual table.
163059*/
163060static int statDisconnect(sqlite3_vtab *pVtab){
163061  sqlite3_free(pVtab);
163062  return SQLITE_OK;
163063}
163064
163065/*
163066** There is no "best-index". This virtual table always does a linear
163067** scan.  However, a schema=? constraint should cause this table to
163068** operate on a different database schema, so check for it.
163069**
163070** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
163071*/
163072static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
163073  int i;
163074
163075  pIdxInfo->estimatedCost = 1.0e6;  /* Initial cost estimate */
163076
163077  /* Look for a valid schema=? constraint.  If found, change the idxNum to
163078  ** 1 and request the value of that constraint be sent to xFilter.  And
163079  ** lower the cost estimate to encourage the constrained version to be
163080  ** used.
163081  */
163082  for(i=0; i<pIdxInfo->nConstraint; i++){
163083    if( pIdxInfo->aConstraint[i].usable==0 ) continue;
163084    if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
163085    if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
163086    pIdxInfo->idxNum = 1;
163087    pIdxInfo->estimatedCost = 1.0;
163088    pIdxInfo->aConstraintUsage[i].argvIndex = 1;
163089    pIdxInfo->aConstraintUsage[i].omit = 1;
163090    break;
163091  }
163092
163093
163094  /* Records are always returned in ascending order of (name, path).
163095  ** If this will satisfy the client, set the orderByConsumed flag so that
163096  ** SQLite does not do an external sort.
163097  */
163098  if( ( pIdxInfo->nOrderBy==1
163099     && pIdxInfo->aOrderBy[0].iColumn==0
163100     && pIdxInfo->aOrderBy[0].desc==0
163101     ) ||
163102      ( pIdxInfo->nOrderBy==2
163103     && pIdxInfo->aOrderBy[0].iColumn==0
163104     && pIdxInfo->aOrderBy[0].desc==0
163105     && pIdxInfo->aOrderBy[1].iColumn==1
163106     && pIdxInfo->aOrderBy[1].desc==0
163107     )
163108  ){
163109    pIdxInfo->orderByConsumed = 1;
163110  }
163111
163112  return SQLITE_OK;
163113}
163114
163115/*
163116** Open a new statvfs cursor.
163117*/
163118static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
163119  StatTable *pTab = (StatTable *)pVTab;
163120  StatCursor *pCsr;
163121
163122  pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
163123  if( pCsr==0 ){
163124    return SQLITE_NOMEM;
163125  }else{
163126    memset(pCsr, 0, sizeof(StatCursor));
163127    pCsr->base.pVtab = pVTab;
163128    pCsr->iDb = pTab->iDb;
163129  }
163130
163131  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
163132  return SQLITE_OK;
163133}
163134
163135static void statClearPage(StatPage *p){
163136  int i;
163137  if( p->aCell ){
163138    for(i=0; i<p->nCell; i++){
163139      sqlite3_free(p->aCell[i].aOvfl);
163140    }
163141    sqlite3_free(p->aCell);
163142  }
163143  sqlite3PagerUnref(p->pPg);
163144  sqlite3_free(p->zPath);
163145  memset(p, 0, sizeof(StatPage));
163146}
163147
163148static void statResetCsr(StatCursor *pCsr){
163149  int i;
163150  sqlite3_reset(pCsr->pStmt);
163151  for(i=0; i<ArraySize(pCsr->aPage); i++){
163152    statClearPage(&pCsr->aPage[i]);
163153  }
163154  pCsr->iPage = 0;
163155  sqlite3_free(pCsr->zPath);
163156  pCsr->zPath = 0;
163157  pCsr->isEof = 0;
163158}
163159
163160/*
163161** Close a statvfs cursor.
163162*/
163163static int statClose(sqlite3_vtab_cursor *pCursor){
163164  StatCursor *pCsr = (StatCursor *)pCursor;
163165  statResetCsr(pCsr);
163166  sqlite3_finalize(pCsr->pStmt);
163167  sqlite3_free(pCsr);
163168  return SQLITE_OK;
163169}
163170
163171static void getLocalPayload(
163172  int nUsable,                    /* Usable bytes per page */
163173  u8 flags,                       /* Page flags */
163174  int nTotal,                     /* Total record (payload) size */
163175  int *pnLocal                    /* OUT: Bytes stored locally */
163176){
163177  int nLocal;
163178  int nMinLocal;
163179  int nMaxLocal;
163180
163181  if( flags==0x0D ){              /* Table leaf node */
163182    nMinLocal = (nUsable - 12) * 32 / 255 - 23;
163183    nMaxLocal = nUsable - 35;
163184  }else{                          /* Index interior and leaf nodes */
163185    nMinLocal = (nUsable - 12) * 32 / 255 - 23;
163186    nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
163187  }
163188
163189  nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
163190  if( nLocal>nMaxLocal ) nLocal = nMinLocal;
163191  *pnLocal = nLocal;
163192}
163193
163194static int statDecodePage(Btree *pBt, StatPage *p){
163195  int nUnused;
163196  int iOff;
163197  int nHdr;
163198  int isLeaf;
163199  int szPage;
163200
163201  u8 *aData = sqlite3PagerGetData(p->pPg);
163202  u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
163203
163204  p->flags = aHdr[0];
163205  p->nCell = get2byte(&aHdr[3]);
163206  p->nMxPayload = 0;
163207
163208  isLeaf = (p->flags==0x0A || p->flags==0x0D);
163209  nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
163210
163211  nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
163212  nUnused += (int)aHdr[7];
163213  iOff = get2byte(&aHdr[1]);
163214  while( iOff ){
163215    nUnused += get2byte(&aData[iOff+2]);
163216    iOff = get2byte(&aData[iOff]);
163217  }
163218  p->nUnused = nUnused;
163219  p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
163220  szPage = sqlite3BtreeGetPageSize(pBt);
163221
163222  if( p->nCell ){
163223    int i;                        /* Used to iterate through cells */
163224    int nUsable;                  /* Usable bytes per page */
163225
163226    sqlite3BtreeEnter(pBt);
163227    nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
163228    sqlite3BtreeLeave(pBt);
163229    p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
163230    if( p->aCell==0 ) return SQLITE_NOMEM;
163231    memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
163232
163233    for(i=0; i<p->nCell; i++){
163234      StatCell *pCell = &p->aCell[i];
163235
163236      iOff = get2byte(&aData[nHdr+i*2]);
163237      if( !isLeaf ){
163238        pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
163239        iOff += 4;
163240      }
163241      if( p->flags==0x05 ){
163242        /* A table interior node. nPayload==0. */
163243      }else{
163244        u32 nPayload;             /* Bytes of payload total (local+overflow) */
163245        int nLocal;               /* Bytes of payload stored locally */
163246        iOff += getVarint32(&aData[iOff], nPayload);
163247        if( p->flags==0x0D ){
163248          u64 dummy;
163249          iOff += sqlite3GetVarint(&aData[iOff], &dummy);
163250        }
163251        if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
163252        getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
163253        pCell->nLocal = nLocal;
163254        assert( nLocal>=0 );
163255        assert( nPayload>=(u32)nLocal );
163256        assert( nLocal<=(nUsable-35) );
163257        if( nPayload>(u32)nLocal ){
163258          int j;
163259          int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
163260          pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
163261          pCell->nOvfl = nOvfl;
163262          pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
163263          if( pCell->aOvfl==0 ) return SQLITE_NOMEM;
163264          pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
163265          for(j=1; j<nOvfl; j++){
163266            int rc;
163267            u32 iPrev = pCell->aOvfl[j-1];
163268            DbPage *pPg = 0;
163269            rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg);
163270            if( rc!=SQLITE_OK ){
163271              assert( pPg==0 );
163272              return rc;
163273            }
163274            pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
163275            sqlite3PagerUnref(pPg);
163276          }
163277        }
163278      }
163279    }
163280  }
163281
163282  return SQLITE_OK;
163283}
163284
163285/*
163286** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
163287** the current value of pCsr->iPageno.
163288*/
163289static void statSizeAndOffset(StatCursor *pCsr){
163290  StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
163291  Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
163292  Pager *pPager = sqlite3BtreePager(pBt);
163293  sqlite3_file *fd;
163294  sqlite3_int64 x[2];
163295
163296  /* The default page size and offset */
163297  pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
163298  pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
163299
163300  /* If connected to a ZIPVFS backend, override the page size and
163301  ** offset with actual values obtained from ZIPVFS.
163302  */
163303  fd = sqlite3PagerFile(pPager);
163304  x[0] = pCsr->iPageno;
163305  if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
163306    pCsr->iOffset = x[0];
163307    pCsr->szPage = (int)x[1];
163308  }
163309}
163310
163311/*
163312** Move a statvfs cursor to the next entry in the file.
163313*/
163314static int statNext(sqlite3_vtab_cursor *pCursor){
163315  int rc;
163316  int nPayload;
163317  char *z;
163318  StatCursor *pCsr = (StatCursor *)pCursor;
163319  StatTable *pTab = (StatTable *)pCursor->pVtab;
163320  Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
163321  Pager *pPager = sqlite3BtreePager(pBt);
163322
163323  sqlite3_free(pCsr->zPath);
163324  pCsr->zPath = 0;
163325
163326statNextRestart:
163327  if( pCsr->aPage[0].pPg==0 ){
163328    rc = sqlite3_step(pCsr->pStmt);
163329    if( rc==SQLITE_ROW ){
163330      int nPage;
163331      u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
163332      sqlite3PagerPagecount(pPager, &nPage);
163333      if( nPage==0 ){
163334        pCsr->isEof = 1;
163335        return sqlite3_reset(pCsr->pStmt);
163336      }
163337      rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg);
163338      pCsr->aPage[0].iPgno = iRoot;
163339      pCsr->aPage[0].iCell = 0;
163340      pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
163341      pCsr->iPage = 0;
163342      if( z==0 ) rc = SQLITE_NOMEM;
163343    }else{
163344      pCsr->isEof = 1;
163345      return sqlite3_reset(pCsr->pStmt);
163346    }
163347  }else{
163348
163349    /* Page p itself has already been visited. */
163350    StatPage *p = &pCsr->aPage[pCsr->iPage];
163351
163352    while( p->iCell<p->nCell ){
163353      StatCell *pCell = &p->aCell[p->iCell];
163354      if( pCell->iOvfl<pCell->nOvfl ){
163355        int nUsable;
163356        sqlite3BtreeEnter(pBt);
163357        nUsable = sqlite3BtreeGetPageSize(pBt) -
163358                        sqlite3BtreeGetReserveNoMutex(pBt);
163359        sqlite3BtreeLeave(pBt);
163360        pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
163361        pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
163362        pCsr->zPagetype = "overflow";
163363        pCsr->nCell = 0;
163364        pCsr->nMxPayload = 0;
163365        pCsr->zPath = z = sqlite3_mprintf(
163366            "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
163367        );
163368        if( pCell->iOvfl<pCell->nOvfl-1 ){
163369          pCsr->nUnused = 0;
163370          pCsr->nPayload = nUsable - 4;
163371        }else{
163372          pCsr->nPayload = pCell->nLastOvfl;
163373          pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
163374        }
163375        pCell->iOvfl++;
163376        statSizeAndOffset(pCsr);
163377        return z==0 ? SQLITE_NOMEM : SQLITE_OK;
163378      }
163379      if( p->iRightChildPg ) break;
163380      p->iCell++;
163381    }
163382
163383    if( !p->iRightChildPg || p->iCell>p->nCell ){
163384      statClearPage(p);
163385      if( pCsr->iPage==0 ) return statNext(pCursor);
163386      pCsr->iPage--;
163387      goto statNextRestart; /* Tail recursion */
163388    }
163389    pCsr->iPage++;
163390    assert( p==&pCsr->aPage[pCsr->iPage-1] );
163391
163392    if( p->iCell==p->nCell ){
163393      p[1].iPgno = p->iRightChildPg;
163394    }else{
163395      p[1].iPgno = p->aCell[p->iCell].iChildPg;
163396    }
163397    rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg);
163398    p[1].iCell = 0;
163399    p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
163400    p->iCell++;
163401    if( z==0 ) rc = SQLITE_NOMEM;
163402  }
163403
163404
163405  /* Populate the StatCursor fields with the values to be returned
163406  ** by the xColumn() and xRowid() methods.
163407  */
163408  if( rc==SQLITE_OK ){
163409    int i;
163410    StatPage *p = &pCsr->aPage[pCsr->iPage];
163411    pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
163412    pCsr->iPageno = p->iPgno;
163413
163414    rc = statDecodePage(pBt, p);
163415    if( rc==SQLITE_OK ){
163416      statSizeAndOffset(pCsr);
163417
163418      switch( p->flags ){
163419        case 0x05:             /* table internal */
163420        case 0x02:             /* index internal */
163421          pCsr->zPagetype = "internal";
163422          break;
163423        case 0x0D:             /* table leaf */
163424        case 0x0A:             /* index leaf */
163425          pCsr->zPagetype = "leaf";
163426          break;
163427        default:
163428          pCsr->zPagetype = "corrupted";
163429          break;
163430      }
163431      pCsr->nCell = p->nCell;
163432      pCsr->nUnused = p->nUnused;
163433      pCsr->nMxPayload = p->nMxPayload;
163434      pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
163435      if( z==0 ) rc = SQLITE_NOMEM;
163436      nPayload = 0;
163437      for(i=0; i<p->nCell; i++){
163438        nPayload += p->aCell[i].nLocal;
163439      }
163440      pCsr->nPayload = nPayload;
163441    }
163442  }
163443
163444  return rc;
163445}
163446
163447static int statEof(sqlite3_vtab_cursor *pCursor){
163448  StatCursor *pCsr = (StatCursor *)pCursor;
163449  return pCsr->isEof;
163450}
163451
163452static int statFilter(
163453  sqlite3_vtab_cursor *pCursor,
163454  int idxNum, const char *idxStr,
163455  int argc, sqlite3_value **argv
163456){
163457  StatCursor *pCsr = (StatCursor *)pCursor;
163458  StatTable *pTab = (StatTable*)(pCursor->pVtab);
163459  char *zSql;
163460  int rc = SQLITE_OK;
163461  char *zMaster;
163462
163463  if( idxNum==1 ){
163464    const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
163465    pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
163466    if( pCsr->iDb<0 ){
163467      sqlite3_free(pCursor->pVtab->zErrMsg);
163468      pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
163469      return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
163470    }
163471  }else{
163472    pCsr->iDb = pTab->iDb;
163473  }
163474  statResetCsr(pCsr);
163475  sqlite3_finalize(pCsr->pStmt);
163476  pCsr->pStmt = 0;
163477  zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
163478  zSql = sqlite3_mprintf(
163479      "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
163480      "  UNION ALL  "
163481      "SELECT name, rootpage, type"
163482      "  FROM \"%w\".%s WHERE rootpage!=0"
163483      "  ORDER BY name", pTab->db->aDb[pCsr->iDb].zName, zMaster);
163484  if( zSql==0 ){
163485    return SQLITE_NOMEM;
163486  }else{
163487    rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
163488    sqlite3_free(zSql);
163489  }
163490
163491  if( rc==SQLITE_OK ){
163492    rc = statNext(pCursor);
163493  }
163494  return rc;
163495}
163496
163497static int statColumn(
163498  sqlite3_vtab_cursor *pCursor,
163499  sqlite3_context *ctx,
163500  int i
163501){
163502  StatCursor *pCsr = (StatCursor *)pCursor;
163503  switch( i ){
163504    case 0:            /* name */
163505      sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
163506      break;
163507    case 1:            /* path */
163508      sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
163509      break;
163510    case 2:            /* pageno */
163511      sqlite3_result_int64(ctx, pCsr->iPageno);
163512      break;
163513    case 3:            /* pagetype */
163514      sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
163515      break;
163516    case 4:            /* ncell */
163517      sqlite3_result_int(ctx, pCsr->nCell);
163518      break;
163519    case 5:            /* payload */
163520      sqlite3_result_int(ctx, pCsr->nPayload);
163521      break;
163522    case 6:            /* unused */
163523      sqlite3_result_int(ctx, pCsr->nUnused);
163524      break;
163525    case 7:            /* mx_payload */
163526      sqlite3_result_int(ctx, pCsr->nMxPayload);
163527      break;
163528    case 8:            /* pgoffset */
163529      sqlite3_result_int64(ctx, pCsr->iOffset);
163530      break;
163531    case 9:            /* pgsize */
163532      sqlite3_result_int(ctx, pCsr->szPage);
163533      break;
163534    default: {          /* schema */
163535      sqlite3 *db = sqlite3_context_db_handle(ctx);
163536      int iDb = pCsr->iDb;
163537      sqlite3_result_text(ctx, db->aDb[iDb].zName, -1, SQLITE_STATIC);
163538      break;
163539    }
163540  }
163541  return SQLITE_OK;
163542}
163543
163544static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
163545  StatCursor *pCsr = (StatCursor *)pCursor;
163546  *pRowid = pCsr->iPageno;
163547  return SQLITE_OK;
163548}
163549
163550/*
163551** Invoke this routine to register the "dbstat" virtual table module
163552*/
163553SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
163554  static sqlite3_module dbstat_module = {
163555    0,                            /* iVersion */
163556    statConnect,                  /* xCreate */
163557    statConnect,                  /* xConnect */
163558    statBestIndex,                /* xBestIndex */
163559    statDisconnect,               /* xDisconnect */
163560    statDisconnect,               /* xDestroy */
163561    statOpen,                     /* xOpen - open a cursor */
163562    statClose,                    /* xClose - close a cursor */
163563    statFilter,                   /* xFilter - configure scan constraints */
163564    statNext,                     /* xNext - advance a cursor */
163565    statEof,                      /* xEof - check for end of scan */
163566    statColumn,                   /* xColumn - read data */
163567    statRowid,                    /* xRowid - read data */
163568    0,                            /* xUpdate */
163569    0,                            /* xBegin */
163570    0,                            /* xSync */
163571    0,                            /* xCommit */
163572    0,                            /* xRollback */
163573    0,                            /* xFindMethod */
163574    0,                            /* xRename */
163575  };
163576  return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
163577}
163578#elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
163579SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
163580#endif /* SQLITE_ENABLE_DBSTAT_VTAB */
163581
163582/************** End of dbstat.c **********************************************/
163583/************** Begin file json1.c *******************************************/
163584/*
163585** 2015-08-12
163586**
163587** The author disclaims copyright to this source code.  In place of
163588** a legal notice, here is a blessing:
163589**
163590**    May you do good and not evil.
163591**    May you find forgiveness for yourself and forgive others.
163592**    May you share freely, never taking more than you give.
163593**
163594******************************************************************************
163595**
163596** This SQLite extension implements JSON functions.  The interface is
163597** modeled after MySQL JSON functions:
163598**
163599**     https://dev.mysql.com/doc/refman/5.7/en/json.html
163600**
163601** For the time being, all JSON is stored as pure text.  (We might add
163602** a JSONB type in the future which stores a binary encoding of JSON in
163603** a BLOB, but there is no support for JSONB in the current implementation.
163604** This implementation parses JSON text at 250 MB/s, so it is hard to see
163605** how JSONB might improve on that.)
163606*/
163607#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
163608#if !defined(_SQLITEINT_H_)
163609/* #include "sqlite3ext.h" */
163610#endif
163611SQLITE_EXTENSION_INIT1
163612/* #include <assert.h> */
163613/* #include <string.h> */
163614/* #include <stdlib.h> */
163615/* #include <stdarg.h> */
163616
163617#define UNUSED_PARAM(X)  (void)(X)
163618
163619#ifndef LARGEST_INT64
163620# define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
163621# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
163622#endif
163623
163624/*
163625** Versions of isspace(), isalnum() and isdigit() to which it is safe
163626** to pass signed char values.
163627*/
163628#ifdef sqlite3Isdigit
163629   /* Use the SQLite core versions if this routine is part of the
163630   ** SQLite amalgamation */
163631#  define safe_isdigit(x) sqlite3Isdigit(x)
163632#  define safe_isalnum(x) sqlite3Isalnum(x)
163633#else
163634   /* Use the standard library for separate compilation */
163635#include <ctype.h>  /* amalgamator: keep */
163636#  define safe_isdigit(x) isdigit((unsigned char)(x))
163637#  define safe_isalnum(x) isalnum((unsigned char)(x))
163638#endif
163639
163640/*
163641** Growing our own isspace() routine this way is twice as fast as
163642** the library isspace() function, resulting in a 7% overall performance
163643** increase for the parser.  (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
163644*/
163645static const char jsonIsSpace[] = {
163646  0, 0, 0, 0, 0, 0, 0, 0,     0, 1, 1, 0, 0, 1, 0, 0,
163647  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163648  1, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163649  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163650  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163651  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163652  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163653  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163654  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163655  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163656  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163657  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163658  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163659  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163660  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163661  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
163662};
163663#define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
163664
163665#ifndef SQLITE_AMALGAMATION
163666  /* Unsigned integer types.  These are already defined in the sqliteInt.h,
163667  ** but the definitions need to be repeated for separate compilation. */
163668  typedef sqlite3_uint64 u64;
163669  typedef unsigned int u32;
163670  typedef unsigned char u8;
163671#endif
163672
163673/* Objects */
163674typedef struct JsonString JsonString;
163675typedef struct JsonNode JsonNode;
163676typedef struct JsonParse JsonParse;
163677
163678/* An instance of this object represents a JSON string
163679** under construction.  Really, this is a generic string accumulator
163680** that can be and is used to create strings other than JSON.
163681*/
163682struct JsonString {
163683  sqlite3_context *pCtx;   /* Function context - put error messages here */
163684  char *zBuf;              /* Append JSON content here */
163685  u64 nAlloc;              /* Bytes of storage available in zBuf[] */
163686  u64 nUsed;               /* Bytes of zBuf[] currently used */
163687  u8 bStatic;              /* True if zBuf is static space */
163688  u8 bErr;                 /* True if an error has been encountered */
163689  char zSpace[100];        /* Initial static space */
163690};
163691
163692/* JSON type values
163693*/
163694#define JSON_NULL     0
163695#define JSON_TRUE     1
163696#define JSON_FALSE    2
163697#define JSON_INT      3
163698#define JSON_REAL     4
163699#define JSON_STRING   5
163700#define JSON_ARRAY    6
163701#define JSON_OBJECT   7
163702
163703/* The "subtype" set for JSON values */
163704#define JSON_SUBTYPE  74    /* Ascii for "J" */
163705
163706/*
163707** Names of the various JSON types:
163708*/
163709static const char * const jsonType[] = {
163710  "null", "true", "false", "integer", "real", "text", "array", "object"
163711};
163712
163713/* Bit values for the JsonNode.jnFlag field
163714*/
163715#define JNODE_RAW     0x01         /* Content is raw, not JSON encoded */
163716#define JNODE_ESCAPE  0x02         /* Content is text with \ escapes */
163717#define JNODE_REMOVE  0x04         /* Do not output */
163718#define JNODE_REPLACE 0x08         /* Replace with JsonNode.iVal */
163719#define JNODE_APPEND  0x10         /* More ARRAY/OBJECT entries at u.iAppend */
163720#define JNODE_LABEL   0x20         /* Is a label of an object */
163721
163722
163723/* A single node of parsed JSON
163724*/
163725struct JsonNode {
163726  u8 eType;              /* One of the JSON_ type values */
163727  u8 jnFlags;            /* JNODE flags */
163728  u8 iVal;               /* Replacement value when JNODE_REPLACE */
163729  u32 n;                 /* Bytes of content, or number of sub-nodes */
163730  union {
163731    const char *zJContent; /* Content for INT, REAL, and STRING */
163732    u32 iAppend;           /* More terms for ARRAY and OBJECT */
163733    u32 iKey;              /* Key for ARRAY objects in json_tree() */
163734  } u;
163735};
163736
163737/* A completely parsed JSON string
163738*/
163739struct JsonParse {
163740  u32 nNode;         /* Number of slots of aNode[] used */
163741  u32 nAlloc;        /* Number of slots of aNode[] allocated */
163742  JsonNode *aNode;   /* Array of nodes containing the parse */
163743  const char *zJson; /* Original JSON string */
163744  u32 *aUp;          /* Index of parent of each node */
163745  u8 oom;            /* Set to true if out of memory */
163746  u8 nErr;           /* Number of errors seen */
163747};
163748
163749/**************************************************************************
163750** Utility routines for dealing with JsonString objects
163751**************************************************************************/
163752
163753/* Set the JsonString object to an empty string
163754*/
163755static void jsonZero(JsonString *p){
163756  p->zBuf = p->zSpace;
163757  p->nAlloc = sizeof(p->zSpace);
163758  p->nUsed = 0;
163759  p->bStatic = 1;
163760}
163761
163762/* Initialize the JsonString object
163763*/
163764static void jsonInit(JsonString *p, sqlite3_context *pCtx){
163765  p->pCtx = pCtx;
163766  p->bErr = 0;
163767  jsonZero(p);
163768}
163769
163770
163771/* Free all allocated memory and reset the JsonString object back to its
163772** initial state.
163773*/
163774static void jsonReset(JsonString *p){
163775  if( !p->bStatic ) sqlite3_free(p->zBuf);
163776  jsonZero(p);
163777}
163778
163779
163780/* Report an out-of-memory (OOM) condition
163781*/
163782static void jsonOom(JsonString *p){
163783  p->bErr = 1;
163784  sqlite3_result_error_nomem(p->pCtx);
163785  jsonReset(p);
163786}
163787
163788/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
163789** Return zero on success.  Return non-zero on an OOM error
163790*/
163791static int jsonGrow(JsonString *p, u32 N){
163792  u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
163793  char *zNew;
163794  if( p->bStatic ){
163795    if( p->bErr ) return 1;
163796    zNew = sqlite3_malloc64(nTotal);
163797    if( zNew==0 ){
163798      jsonOom(p);
163799      return SQLITE_NOMEM;
163800    }
163801    memcpy(zNew, p->zBuf, (size_t)p->nUsed);
163802    p->zBuf = zNew;
163803    p->bStatic = 0;
163804  }else{
163805    zNew = sqlite3_realloc64(p->zBuf, nTotal);
163806    if( zNew==0 ){
163807      jsonOom(p);
163808      return SQLITE_NOMEM;
163809    }
163810    p->zBuf = zNew;
163811  }
163812  p->nAlloc = nTotal;
163813  return SQLITE_OK;
163814}
163815
163816/* Append N bytes from zIn onto the end of the JsonString string.
163817*/
163818static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
163819  if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
163820  memcpy(p->zBuf+p->nUsed, zIn, N);
163821  p->nUsed += N;
163822}
163823
163824/* Append formatted text (not to exceed N bytes) to the JsonString.
163825*/
163826static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
163827  va_list ap;
163828  if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
163829  va_start(ap, zFormat);
163830  sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
163831  va_end(ap);
163832  p->nUsed += (int)strlen(p->zBuf+p->nUsed);
163833}
163834
163835/* Append a single character
163836*/
163837static void jsonAppendChar(JsonString *p, char c){
163838  if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
163839  p->zBuf[p->nUsed++] = c;
163840}
163841
163842/* Append a comma separator to the output buffer, if the previous
163843** character is not '[' or '{'.
163844*/
163845static void jsonAppendSeparator(JsonString *p){
163846  char c;
163847  if( p->nUsed==0 ) return;
163848  c = p->zBuf[p->nUsed-1];
163849  if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
163850}
163851
163852/* Append the N-byte string in zIn to the end of the JsonString string
163853** under construction.  Enclose the string in "..." and escape
163854** any double-quotes or backslash characters contained within the
163855** string.
163856*/
163857static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
163858  u32 i;
163859  if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
163860  p->zBuf[p->nUsed++] = '"';
163861  for(i=0; i<N; i++){
163862    char c = zIn[i];
163863    if( c=='"' || c=='\\' ){
163864      if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
163865      p->zBuf[p->nUsed++] = '\\';
163866    }
163867    p->zBuf[p->nUsed++] = c;
163868  }
163869  p->zBuf[p->nUsed++] = '"';
163870  assert( p->nUsed<p->nAlloc );
163871}
163872
163873/*
163874** Append a function parameter value to the JSON string under
163875** construction.
163876*/
163877static void jsonAppendValue(
163878  JsonString *p,                 /* Append to this JSON string */
163879  sqlite3_value *pValue          /* Value to append */
163880){
163881  switch( sqlite3_value_type(pValue) ){
163882    case SQLITE_NULL: {
163883      jsonAppendRaw(p, "null", 4);
163884      break;
163885    }
163886    case SQLITE_INTEGER:
163887    case SQLITE_FLOAT: {
163888      const char *z = (const char*)sqlite3_value_text(pValue);
163889      u32 n = (u32)sqlite3_value_bytes(pValue);
163890      jsonAppendRaw(p, z, n);
163891      break;
163892    }
163893    case SQLITE_TEXT: {
163894      const char *z = (const char*)sqlite3_value_text(pValue);
163895      u32 n = (u32)sqlite3_value_bytes(pValue);
163896      if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
163897        jsonAppendRaw(p, z, n);
163898      }else{
163899        jsonAppendString(p, z, n);
163900      }
163901      break;
163902    }
163903    default: {
163904      if( p->bErr==0 ){
163905        sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
163906        p->bErr = 1;
163907        jsonReset(p);
163908      }
163909      break;
163910    }
163911  }
163912}
163913
163914
163915/* Make the JSON in p the result of the SQL function.
163916*/
163917static void jsonResult(JsonString *p){
163918  if( p->bErr==0 ){
163919    sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
163920                          p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
163921                          SQLITE_UTF8);
163922    jsonZero(p);
163923  }
163924  assert( p->bStatic );
163925}
163926
163927/**************************************************************************
163928** Utility routines for dealing with JsonNode and JsonParse objects
163929**************************************************************************/
163930
163931/*
163932** Return the number of consecutive JsonNode slots need to represent
163933** the parsed JSON at pNode.  The minimum answer is 1.  For ARRAY and
163934** OBJECT types, the number might be larger.
163935**
163936** Appended elements are not counted.  The value returned is the number
163937** by which the JsonNode counter should increment in order to go to the
163938** next peer value.
163939*/
163940static u32 jsonNodeSize(JsonNode *pNode){
163941  return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
163942}
163943
163944/*
163945** Reclaim all memory allocated by a JsonParse object.  But do not
163946** delete the JsonParse object itself.
163947*/
163948static void jsonParseReset(JsonParse *pParse){
163949  sqlite3_free(pParse->aNode);
163950  pParse->aNode = 0;
163951  pParse->nNode = 0;
163952  pParse->nAlloc = 0;
163953  sqlite3_free(pParse->aUp);
163954  pParse->aUp = 0;
163955}
163956
163957/*
163958** Convert the JsonNode pNode into a pure JSON string and
163959** append to pOut.  Subsubstructure is also included.  Return
163960** the number of JsonNode objects that are encoded.
163961*/
163962static void jsonRenderNode(
163963  JsonNode *pNode,               /* The node to render */
163964  JsonString *pOut,              /* Write JSON here */
163965  sqlite3_value **aReplace       /* Replacement values */
163966){
163967  switch( pNode->eType ){
163968    default: {
163969      assert( pNode->eType==JSON_NULL );
163970      jsonAppendRaw(pOut, "null", 4);
163971      break;
163972    }
163973    case JSON_TRUE: {
163974      jsonAppendRaw(pOut, "true", 4);
163975      break;
163976    }
163977    case JSON_FALSE: {
163978      jsonAppendRaw(pOut, "false", 5);
163979      break;
163980    }
163981    case JSON_STRING: {
163982      if( pNode->jnFlags & JNODE_RAW ){
163983        jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
163984        break;
163985      }
163986      /* Fall through into the next case */
163987    }
163988    case JSON_REAL:
163989    case JSON_INT: {
163990      jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
163991      break;
163992    }
163993    case JSON_ARRAY: {
163994      u32 j = 1;
163995      jsonAppendChar(pOut, '[');
163996      for(;;){
163997        while( j<=pNode->n ){
163998          if( pNode[j].jnFlags & (JNODE_REMOVE|JNODE_REPLACE) ){
163999            if( pNode[j].jnFlags & JNODE_REPLACE ){
164000              jsonAppendSeparator(pOut);
164001              jsonAppendValue(pOut, aReplace[pNode[j].iVal]);
164002            }
164003          }else{
164004            jsonAppendSeparator(pOut);
164005            jsonRenderNode(&pNode[j], pOut, aReplace);
164006          }
164007          j += jsonNodeSize(&pNode[j]);
164008        }
164009        if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
164010        pNode = &pNode[pNode->u.iAppend];
164011        j = 1;
164012      }
164013      jsonAppendChar(pOut, ']');
164014      break;
164015    }
164016    case JSON_OBJECT: {
164017      u32 j = 1;
164018      jsonAppendChar(pOut, '{');
164019      for(;;){
164020        while( j<=pNode->n ){
164021          if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
164022            jsonAppendSeparator(pOut);
164023            jsonRenderNode(&pNode[j], pOut, aReplace);
164024            jsonAppendChar(pOut, ':');
164025            if( pNode[j+1].jnFlags & JNODE_REPLACE ){
164026              jsonAppendValue(pOut, aReplace[pNode[j+1].iVal]);
164027            }else{
164028              jsonRenderNode(&pNode[j+1], pOut, aReplace);
164029            }
164030          }
164031          j += 1 + jsonNodeSize(&pNode[j+1]);
164032        }
164033        if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
164034        pNode = &pNode[pNode->u.iAppend];
164035        j = 1;
164036      }
164037      jsonAppendChar(pOut, '}');
164038      break;
164039    }
164040  }
164041}
164042
164043/*
164044** Return a JsonNode and all its descendents as a JSON string.
164045*/
164046static void jsonReturnJson(
164047  JsonNode *pNode,            /* Node to return */
164048  sqlite3_context *pCtx,      /* Return value for this function */
164049  sqlite3_value **aReplace    /* Array of replacement values */
164050){
164051  JsonString s;
164052  jsonInit(&s, pCtx);
164053  jsonRenderNode(pNode, &s, aReplace);
164054  jsonResult(&s);
164055  sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
164056}
164057
164058/*
164059** Make the JsonNode the return value of the function.
164060*/
164061static void jsonReturn(
164062  JsonNode *pNode,            /* Node to return */
164063  sqlite3_context *pCtx,      /* Return value for this function */
164064  sqlite3_value **aReplace    /* Array of replacement values */
164065){
164066  switch( pNode->eType ){
164067    default: {
164068      assert( pNode->eType==JSON_NULL );
164069      sqlite3_result_null(pCtx);
164070      break;
164071    }
164072    case JSON_TRUE: {
164073      sqlite3_result_int(pCtx, 1);
164074      break;
164075    }
164076    case JSON_FALSE: {
164077      sqlite3_result_int(pCtx, 0);
164078      break;
164079    }
164080    case JSON_INT: {
164081      sqlite3_int64 i = 0;
164082      const char *z = pNode->u.zJContent;
164083      if( z[0]=='-' ){ z++; }
164084      while( z[0]>='0' && z[0]<='9' ){
164085        unsigned v = *(z++) - '0';
164086        if( i>=LARGEST_INT64/10 ){
164087          if( i>LARGEST_INT64/10 ) goto int_as_real;
164088          if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
164089          if( v==9 ) goto int_as_real;
164090          if( v==8 ){
164091            if( pNode->u.zJContent[0]=='-' ){
164092              sqlite3_result_int64(pCtx, SMALLEST_INT64);
164093              goto int_done;
164094            }else{
164095              goto int_as_real;
164096            }
164097          }
164098        }
164099        i = i*10 + v;
164100      }
164101      if( pNode->u.zJContent[0]=='-' ){ i = -i; }
164102      sqlite3_result_int64(pCtx, i);
164103      int_done:
164104      break;
164105      int_as_real: /* fall through to real */;
164106    }
164107    case JSON_REAL: {
164108      double r;
164109#ifdef SQLITE_AMALGAMATION
164110      const char *z = pNode->u.zJContent;
164111      sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
164112#else
164113      r = strtod(pNode->u.zJContent, 0);
164114#endif
164115      sqlite3_result_double(pCtx, r);
164116      break;
164117    }
164118    case JSON_STRING: {
164119#if 0 /* Never happens because JNODE_RAW is only set by json_set(),
164120      ** json_insert() and json_replace() and those routines do not
164121      ** call jsonReturn() */
164122      if( pNode->jnFlags & JNODE_RAW ){
164123        sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
164124                            SQLITE_TRANSIENT);
164125      }else
164126#endif
164127      assert( (pNode->jnFlags & JNODE_RAW)==0 );
164128      if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
164129        /* JSON formatted without any backslash-escapes */
164130        sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
164131                            SQLITE_TRANSIENT);
164132      }else{
164133        /* Translate JSON formatted string into raw text */
164134        u32 i;
164135        u32 n = pNode->n;
164136        const char *z = pNode->u.zJContent;
164137        char *zOut;
164138        u32 j;
164139        zOut = sqlite3_malloc( n+1 );
164140        if( zOut==0 ){
164141          sqlite3_result_error_nomem(pCtx);
164142          break;
164143        }
164144        for(i=1, j=0; i<n-1; i++){
164145          char c = z[i];
164146          if( c!='\\' ){
164147            zOut[j++] = c;
164148          }else{
164149            c = z[++i];
164150            if( c=='u' ){
164151              u32 v = 0, k;
164152              for(k=0; k<4 && i<n-2; i++, k++){
164153                c = z[i+1];
164154                if( c>='0' && c<='9' ) v = v*16 + c - '0';
164155                else if( c>='A' && c<='F' ) v = v*16 + c - 'A' + 10;
164156                else if( c>='a' && c<='f' ) v = v*16 + c - 'a' + 10;
164157                else break;
164158              }
164159              if( v==0 ) break;
164160              if( v<=0x7f ){
164161                zOut[j++] = (char)v;
164162              }else if( v<=0x7ff ){
164163                zOut[j++] = (char)(0xc0 | (v>>6));
164164                zOut[j++] = 0x80 | (v&0x3f);
164165              }else{
164166                zOut[j++] = (char)(0xe0 | (v>>12));
164167                zOut[j++] = 0x80 | ((v>>6)&0x3f);
164168                zOut[j++] = 0x80 | (v&0x3f);
164169              }
164170            }else{
164171              if( c=='b' ){
164172                c = '\b';
164173              }else if( c=='f' ){
164174                c = '\f';
164175              }else if( c=='n' ){
164176                c = '\n';
164177              }else if( c=='r' ){
164178                c = '\r';
164179              }else if( c=='t' ){
164180                c = '\t';
164181              }
164182              zOut[j++] = c;
164183            }
164184          }
164185        }
164186        zOut[j] = 0;
164187        sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
164188      }
164189      break;
164190    }
164191    case JSON_ARRAY:
164192    case JSON_OBJECT: {
164193      jsonReturnJson(pNode, pCtx, aReplace);
164194      break;
164195    }
164196  }
164197}
164198
164199/* Forward reference */
164200static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
164201
164202/*
164203** A macro to hint to the compiler that a function should not be
164204** inlined.
164205*/
164206#if defined(__GNUC__)
164207#  define JSON_NOINLINE  __attribute__((noinline))
164208#elif defined(_MSC_VER) && _MSC_VER>=1310
164209#  define JSON_NOINLINE  __declspec(noinline)
164210#else
164211#  define JSON_NOINLINE
164212#endif
164213
164214
164215static JSON_NOINLINE int jsonParseAddNodeExpand(
164216  JsonParse *pParse,        /* Append the node to this object */
164217  u32 eType,                /* Node type */
164218  u32 n,                    /* Content size or sub-node count */
164219  const char *zContent      /* Content */
164220){
164221  u32 nNew;
164222  JsonNode *pNew;
164223  assert( pParse->nNode>=pParse->nAlloc );
164224  if( pParse->oom ) return -1;
164225  nNew = pParse->nAlloc*2 + 10;
164226  pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
164227  if( pNew==0 ){
164228    pParse->oom = 1;
164229    return -1;
164230  }
164231  pParse->nAlloc = nNew;
164232  pParse->aNode = pNew;
164233  assert( pParse->nNode<pParse->nAlloc );
164234  return jsonParseAddNode(pParse, eType, n, zContent);
164235}
164236
164237/*
164238** Create a new JsonNode instance based on the arguments and append that
164239** instance to the JsonParse.  Return the index in pParse->aNode[] of the
164240** new node, or -1 if a memory allocation fails.
164241*/
164242static int jsonParseAddNode(
164243  JsonParse *pParse,        /* Append the node to this object */
164244  u32 eType,                /* Node type */
164245  u32 n,                    /* Content size or sub-node count */
164246  const char *zContent      /* Content */
164247){
164248  JsonNode *p;
164249  if( pParse->nNode>=pParse->nAlloc ){
164250    return jsonParseAddNodeExpand(pParse, eType, n, zContent);
164251  }
164252  p = &pParse->aNode[pParse->nNode];
164253  p->eType = (u8)eType;
164254  p->jnFlags = 0;
164255  p->iVal = 0;
164256  p->n = n;
164257  p->u.zJContent = zContent;
164258  return pParse->nNode++;
164259}
164260
164261/*
164262** Parse a single JSON value which begins at pParse->zJson[i].  Return the
164263** index of the first character past the end of the value parsed.
164264**
164265** Return negative for a syntax error.  Special cases:  return -2 if the
164266** first non-whitespace character is '}' and return -3 if the first
164267** non-whitespace character is ']'.
164268*/
164269static int jsonParseValue(JsonParse *pParse, u32 i){
164270  char c;
164271  u32 j;
164272  int iThis;
164273  int x;
164274  JsonNode *pNode;
164275  while( safe_isspace(pParse->zJson[i]) ){ i++; }
164276  if( (c = pParse->zJson[i])=='{' ){
164277    /* Parse object */
164278    iThis = jsonParseAddNode(pParse, JSON_OBJECT, 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==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
164285        return -1;
164286      }
164287      if( pParse->oom ) return -1;
164288      pNode = &pParse->aNode[pParse->nNode-1];
164289      if( pNode->eType!=JSON_STRING ) return -1;
164290      pNode->jnFlags |= JNODE_LABEL;
164291      j = x;
164292      while( safe_isspace(pParse->zJson[j]) ){ j++; }
164293      if( pParse->zJson[j]!=':' ) return -1;
164294      j++;
164295      x = jsonParseValue(pParse, j);
164296      if( x<0 ) return -1;
164297      j = x;
164298      while( safe_isspace(pParse->zJson[j]) ){ j++; }
164299      c = pParse->zJson[j];
164300      if( c==',' ) continue;
164301      if( c!='}' ) return -1;
164302      break;
164303    }
164304    pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
164305    return j+1;
164306  }else if( c=='[' ){
164307    /* Parse array */
164308    iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
164309    if( iThis<0 ) return -1;
164310    for(j=i+1;;j++){
164311      while( safe_isspace(pParse->zJson[j]) ){ j++; }
164312      x = jsonParseValue(pParse, j);
164313      if( x<0 ){
164314        if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
164315        return -1;
164316      }
164317      j = x;
164318      while( safe_isspace(pParse->zJson[j]) ){ j++; }
164319      c = pParse->zJson[j];
164320      if( c==',' ) continue;
164321      if( c!=']' ) return -1;
164322      break;
164323    }
164324    pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
164325    return j+1;
164326  }else if( c=='"' ){
164327    /* Parse string */
164328    u8 jnFlags = 0;
164329    j = i+1;
164330    for(;;){
164331      c = pParse->zJson[j];
164332      if( c==0 ) return -1;
164333      if( c=='\\' ){
164334        c = pParse->zJson[++j];
164335        if( c==0 ) return -1;
164336        jnFlags = JNODE_ESCAPE;
164337      }else if( c=='"' ){
164338        break;
164339      }
164340      j++;
164341    }
164342    jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]);
164343    if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
164344    return j+1;
164345  }else if( c=='n'
164346         && strncmp(pParse->zJson+i,"null",4)==0
164347         && !safe_isalnum(pParse->zJson[i+4]) ){
164348    jsonParseAddNode(pParse, JSON_NULL, 0, 0);
164349    return i+4;
164350  }else if( c=='t'
164351         && strncmp(pParse->zJson+i,"true",4)==0
164352         && !safe_isalnum(pParse->zJson[i+4]) ){
164353    jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
164354    return i+4;
164355  }else if( c=='f'
164356         && strncmp(pParse->zJson+i,"false",5)==0
164357         && !safe_isalnum(pParse->zJson[i+5]) ){
164358    jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
164359    return i+5;
164360  }else if( c=='-' || (c>='0' && c<='9') ){
164361    /* Parse number */
164362    u8 seenDP = 0;
164363    u8 seenE = 0;
164364    j = i+1;
164365    for(;; j++){
164366      c = pParse->zJson[j];
164367      if( c>='0' && c<='9' ) continue;
164368      if( c=='.' ){
164369        if( pParse->zJson[j-1]=='-' ) return -1;
164370        if( seenDP ) return -1;
164371        seenDP = 1;
164372        continue;
164373      }
164374      if( c=='e' || c=='E' ){
164375        if( pParse->zJson[j-1]<'0' ) return -1;
164376        if( seenE ) return -1;
164377        seenDP = seenE = 1;
164378        c = pParse->zJson[j+1];
164379        if( c=='+' || c=='-' ){
164380          j++;
164381          c = pParse->zJson[j+1];
164382        }
164383        if( c<'0' || c>'9' ) return -1;
164384        continue;
164385      }
164386      break;
164387    }
164388    if( pParse->zJson[j-1]<'0' ) return -1;
164389    jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
164390                        j - i, &pParse->zJson[i]);
164391    return j;
164392  }else if( c=='}' ){
164393    return -2;  /* End of {...} */
164394  }else if( c==']' ){
164395    return -3;  /* End of [...] */
164396  }else if( c==0 ){
164397    return 0;   /* End of file */
164398  }else{
164399    return -1;  /* Syntax error */
164400  }
164401}
164402
164403/*
164404** Parse a complete JSON string.  Return 0 on success or non-zero if there
164405** are any errors.  If an error occurs, free all memory associated with
164406** pParse.
164407**
164408** pParse is uninitialized when this routine is called.
164409*/
164410static int jsonParse(
164411  JsonParse *pParse,           /* Initialize and fill this JsonParse object */
164412  sqlite3_context *pCtx,       /* Report errors here */
164413  const char *zJson            /* Input JSON text to be parsed */
164414){
164415  int i;
164416  memset(pParse, 0, sizeof(*pParse));
164417  if( zJson==0 ) return 1;
164418  pParse->zJson = zJson;
164419  i = jsonParseValue(pParse, 0);
164420  if( pParse->oom ) i = -1;
164421  if( i>0 ){
164422    while( safe_isspace(zJson[i]) ) i++;
164423    if( zJson[i] ) i = -1;
164424  }
164425  if( i<=0 ){
164426    if( pCtx!=0 ){
164427      if( pParse->oom ){
164428        sqlite3_result_error_nomem(pCtx);
164429      }else{
164430        sqlite3_result_error(pCtx, "malformed JSON", -1);
164431      }
164432    }
164433    jsonParseReset(pParse);
164434    return 1;
164435  }
164436  return 0;
164437}
164438
164439/* Mark node i of pParse as being a child of iParent.  Call recursively
164440** to fill in all the descendants of node i.
164441*/
164442static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
164443  JsonNode *pNode = &pParse->aNode[i];
164444  u32 j;
164445  pParse->aUp[i] = iParent;
164446  switch( pNode->eType ){
164447    case JSON_ARRAY: {
164448      for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
164449        jsonParseFillInParentage(pParse, i+j, i);
164450      }
164451      break;
164452    }
164453    case JSON_OBJECT: {
164454      for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
164455        pParse->aUp[i+j] = i;
164456        jsonParseFillInParentage(pParse, i+j+1, i);
164457      }
164458      break;
164459    }
164460    default: {
164461      break;
164462    }
164463  }
164464}
164465
164466/*
164467** Compute the parentage of all nodes in a completed parse.
164468*/
164469static int jsonParseFindParents(JsonParse *pParse){
164470  u32 *aUp;
164471  assert( pParse->aUp==0 );
164472  aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
164473  if( aUp==0 ){
164474    pParse->oom = 1;
164475    return SQLITE_NOMEM;
164476  }
164477  jsonParseFillInParentage(pParse, 0, 0);
164478  return SQLITE_OK;
164479}
164480
164481/*
164482** Compare the OBJECT label at pNode against zKey,nKey.  Return true on
164483** a match.
164484*/
164485static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
164486  if( pNode->jnFlags & JNODE_RAW ){
164487    if( pNode->n!=nKey ) return 0;
164488    return strncmp(pNode->u.zJContent, zKey, nKey)==0;
164489  }else{
164490    if( pNode->n!=nKey+2 ) return 0;
164491    return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
164492  }
164493}
164494
164495/* forward declaration */
164496static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
164497
164498/*
164499** Search along zPath to find the node specified.  Return a pointer
164500** to that node, or NULL if zPath is malformed or if there is no such
164501** node.
164502**
164503** If pApnd!=0, then try to append new nodes to complete zPath if it is
164504** possible to do so and if no existing node corresponds to zPath.  If
164505** new nodes are appended *pApnd is set to 1.
164506*/
164507static JsonNode *jsonLookupStep(
164508  JsonParse *pParse,      /* The JSON to search */
164509  u32 iRoot,              /* Begin the search at this node */
164510  const char *zPath,      /* The path to search */
164511  int *pApnd,             /* Append nodes to complete path if not NULL */
164512  const char **pzErr      /* Make *pzErr point to any syntax error in zPath */
164513){
164514  u32 i, j, nKey;
164515  const char *zKey;
164516  JsonNode *pRoot = &pParse->aNode[iRoot];
164517  if( zPath[0]==0 ) return pRoot;
164518  if( zPath[0]=='.' ){
164519    if( pRoot->eType!=JSON_OBJECT ) return 0;
164520    zPath++;
164521    if( zPath[0]=='"' ){
164522      zKey = zPath + 1;
164523      for(i=1; zPath[i] && zPath[i]!='"'; i++){}
164524      nKey = i-1;
164525      if( zPath[i] ){
164526        i++;
164527      }else{
164528        *pzErr = zPath;
164529        return 0;
164530      }
164531    }else{
164532      zKey = zPath;
164533      for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
164534      nKey = i;
164535    }
164536    if( nKey==0 ){
164537      *pzErr = zPath;
164538      return 0;
164539    }
164540    j = 1;
164541    for(;;){
164542      while( j<=pRoot->n ){
164543        if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
164544          return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
164545        }
164546        j++;
164547        j += jsonNodeSize(&pRoot[j]);
164548      }
164549      if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
164550      iRoot += pRoot->u.iAppend;
164551      pRoot = &pParse->aNode[iRoot];
164552      j = 1;
164553    }
164554    if( pApnd ){
164555      u32 iStart, iLabel;
164556      JsonNode *pNode;
164557      iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
164558      iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
164559      zPath += i;
164560      pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
164561      if( pParse->oom ) return 0;
164562      if( pNode ){
164563        pRoot = &pParse->aNode[iRoot];
164564        pRoot->u.iAppend = iStart - iRoot;
164565        pRoot->jnFlags |= JNODE_APPEND;
164566        pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
164567      }
164568      return pNode;
164569    }
164570  }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
164571    if( pRoot->eType!=JSON_ARRAY ) return 0;
164572    i = 0;
164573    j = 1;
164574    while( safe_isdigit(zPath[j]) ){
164575      i = i*10 + zPath[j] - '0';
164576      j++;
164577    }
164578    if( zPath[j]!=']' ){
164579      *pzErr = zPath;
164580      return 0;
164581    }
164582    zPath += j + 1;
164583    j = 1;
164584    for(;;){
164585      while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
164586        if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
164587        j += jsonNodeSize(&pRoot[j]);
164588      }
164589      if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
164590      iRoot += pRoot->u.iAppend;
164591      pRoot = &pParse->aNode[iRoot];
164592      j = 1;
164593    }
164594    if( j<=pRoot->n ){
164595      return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
164596    }
164597    if( i==0 && pApnd ){
164598      u32 iStart;
164599      JsonNode *pNode;
164600      iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
164601      pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
164602      if( pParse->oom ) return 0;
164603      if( pNode ){
164604        pRoot = &pParse->aNode[iRoot];
164605        pRoot->u.iAppend = iStart - iRoot;
164606        pRoot->jnFlags |= JNODE_APPEND;
164607      }
164608      return pNode;
164609    }
164610  }else{
164611    *pzErr = zPath;
164612  }
164613  return 0;
164614}
164615
164616/*
164617** Append content to pParse that will complete zPath.  Return a pointer
164618** to the inserted node, or return NULL if the append fails.
164619*/
164620static JsonNode *jsonLookupAppend(
164621  JsonParse *pParse,     /* Append content to the JSON parse */
164622  const char *zPath,     /* Description of content to append */
164623  int *pApnd,            /* Set this flag to 1 */
164624  const char **pzErr     /* Make this point to any syntax error */
164625){
164626  *pApnd = 1;
164627  if( zPath[0]==0 ){
164628    jsonParseAddNode(pParse, JSON_NULL, 0, 0);
164629    return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
164630  }
164631  if( zPath[0]=='.' ){
164632    jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
164633  }else if( strncmp(zPath,"[0]",3)==0 ){
164634    jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
164635  }else{
164636    return 0;
164637  }
164638  if( pParse->oom ) return 0;
164639  return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
164640}
164641
164642/*
164643** Return the text of a syntax error message on a JSON path.  Space is
164644** obtained from sqlite3_malloc().
164645*/
164646static char *jsonPathSyntaxError(const char *zErr){
164647  return sqlite3_mprintf("JSON path error near '%q'", zErr);
164648}
164649
164650/*
164651** Do a node lookup using zPath.  Return a pointer to the node on success.
164652** Return NULL if not found or if there is an error.
164653**
164654** On an error, write an error message into pCtx and increment the
164655** pParse->nErr counter.
164656**
164657** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
164658** nodes are appended.
164659*/
164660static JsonNode *jsonLookup(
164661  JsonParse *pParse,      /* The JSON to search */
164662  const char *zPath,      /* The path to search */
164663  int *pApnd,             /* Append nodes to complete path if not NULL */
164664  sqlite3_context *pCtx   /* Report errors here, if not NULL */
164665){
164666  const char *zErr = 0;
164667  JsonNode *pNode = 0;
164668  char *zMsg;
164669
164670  if( zPath==0 ) return 0;
164671  if( zPath[0]!='$' ){
164672    zErr = zPath;
164673    goto lookup_err;
164674  }
164675  zPath++;
164676  pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
164677  if( zErr==0 ) return pNode;
164678
164679lookup_err:
164680  pParse->nErr++;
164681  assert( zErr!=0 && pCtx!=0 );
164682  zMsg = jsonPathSyntaxError(zErr);
164683  if( zMsg ){
164684    sqlite3_result_error(pCtx, zMsg, -1);
164685    sqlite3_free(zMsg);
164686  }else{
164687    sqlite3_result_error_nomem(pCtx);
164688  }
164689  return 0;
164690}
164691
164692
164693/*
164694** Report the wrong number of arguments for json_insert(), json_replace()
164695** or json_set().
164696*/
164697static void jsonWrongNumArgs(
164698  sqlite3_context *pCtx,
164699  const char *zFuncName
164700){
164701  char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
164702                               zFuncName);
164703  sqlite3_result_error(pCtx, zMsg, -1);
164704  sqlite3_free(zMsg);
164705}
164706
164707
164708/****************************************************************************
164709** SQL functions used for testing and debugging
164710****************************************************************************/
164711
164712#ifdef SQLITE_DEBUG
164713/*
164714** The json_parse(JSON) function returns a string which describes
164715** a parse of the JSON provided.  Or it returns NULL if JSON is not
164716** well-formed.
164717*/
164718static void jsonParseFunc(
164719  sqlite3_context *ctx,
164720  int argc,
164721  sqlite3_value **argv
164722){
164723  JsonString s;       /* Output string - not real JSON */
164724  JsonParse x;        /* The parse */
164725  u32 i;
164726
164727  assert( argc==1 );
164728  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
164729  jsonParseFindParents(&x);
164730  jsonInit(&s, ctx);
164731  for(i=0; i<x.nNode; i++){
164732    const char *zType;
164733    if( x.aNode[i].jnFlags & JNODE_LABEL ){
164734      assert( x.aNode[i].eType==JSON_STRING );
164735      zType = "label";
164736    }else{
164737      zType = jsonType[x.aNode[i].eType];
164738    }
164739    jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
164740               i, zType, x.aNode[i].n, x.aUp[i]);
164741    if( x.aNode[i].u.zJContent!=0 ){
164742      jsonAppendRaw(&s, " ", 1);
164743      jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
164744    }
164745    jsonAppendRaw(&s, "\n", 1);
164746  }
164747  jsonParseReset(&x);
164748  jsonResult(&s);
164749}
164750
164751/*
164752** The json_test1(JSON) function return true (1) if the input is JSON
164753** text generated by another json function.  It returns (0) if the input
164754** is not known to be JSON.
164755*/
164756static void jsonTest1Func(
164757  sqlite3_context *ctx,
164758  int argc,
164759  sqlite3_value **argv
164760){
164761  UNUSED_PARAM(argc);
164762  sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
164763}
164764#endif /* SQLITE_DEBUG */
164765
164766/****************************************************************************
164767** SQL function implementations
164768****************************************************************************/
164769
164770/*
164771** Implementation of the json_array(VALUE,...) function.  Return a JSON
164772** array that contains all values given in arguments.  Or if any argument
164773** is a BLOB, throw an error.
164774*/
164775static void jsonArrayFunc(
164776  sqlite3_context *ctx,
164777  int argc,
164778  sqlite3_value **argv
164779){
164780  int i;
164781  JsonString jx;
164782
164783  jsonInit(&jx, ctx);
164784  jsonAppendChar(&jx, '[');
164785  for(i=0; i<argc; i++){
164786    jsonAppendSeparator(&jx);
164787    jsonAppendValue(&jx, argv[i]);
164788  }
164789  jsonAppendChar(&jx, ']');
164790  jsonResult(&jx);
164791  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
164792}
164793
164794
164795/*
164796** json_array_length(JSON)
164797** json_array_length(JSON, PATH)
164798**
164799** Return the number of elements in the top-level JSON array.
164800** Return 0 if the input is not a well-formed JSON array.
164801*/
164802static void jsonArrayLengthFunc(
164803  sqlite3_context *ctx,
164804  int argc,
164805  sqlite3_value **argv
164806){
164807  JsonParse x;          /* The parse */
164808  sqlite3_int64 n = 0;
164809  u32 i;
164810  JsonNode *pNode;
164811
164812  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
164813  assert( x.nNode );
164814  if( argc==2 ){
164815    const char *zPath = (const char*)sqlite3_value_text(argv[1]);
164816    pNode = jsonLookup(&x, zPath, 0, ctx);
164817  }else{
164818    pNode = x.aNode;
164819  }
164820  if( pNode==0 ){
164821    x.nErr = 1;
164822  }else if( pNode->eType==JSON_ARRAY ){
164823    assert( (pNode->jnFlags & JNODE_APPEND)==0 );
164824    for(i=1; i<=pNode->n; n++){
164825      i += jsonNodeSize(&pNode[i]);
164826    }
164827  }
164828  if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
164829  jsonParseReset(&x);
164830}
164831
164832/*
164833** json_extract(JSON, PATH, ...)
164834**
164835** Return the element described by PATH.  Return NULL if there is no
164836** PATH element.  If there are multiple PATHs, then return a JSON array
164837** with the result from each path.  Throw an error if the JSON or any PATH
164838** is malformed.
164839*/
164840static void jsonExtractFunc(
164841  sqlite3_context *ctx,
164842  int argc,
164843  sqlite3_value **argv
164844){
164845  JsonParse x;          /* The parse */
164846  JsonNode *pNode;
164847  const char *zPath;
164848  JsonString jx;
164849  int i;
164850
164851  if( argc<2 ) return;
164852  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
164853  jsonInit(&jx, ctx);
164854  jsonAppendChar(&jx, '[');
164855  for(i=1; i<argc; i++){
164856    zPath = (const char*)sqlite3_value_text(argv[i]);
164857    pNode = jsonLookup(&x, zPath, 0, ctx);
164858    if( x.nErr ) break;
164859    if( argc>2 ){
164860      jsonAppendSeparator(&jx);
164861      if( pNode ){
164862        jsonRenderNode(pNode, &jx, 0);
164863      }else{
164864        jsonAppendRaw(&jx, "null", 4);
164865      }
164866    }else if( pNode ){
164867      jsonReturn(pNode, ctx, 0);
164868    }
164869  }
164870  if( argc>2 && i==argc ){
164871    jsonAppendChar(&jx, ']');
164872    jsonResult(&jx);
164873    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
164874  }
164875  jsonReset(&jx);
164876  jsonParseReset(&x);
164877}
164878
164879/*
164880** Implementation of the json_object(NAME,VALUE,...) function.  Return a JSON
164881** object that contains all name/value given in arguments.  Or if any name
164882** is not a string or if any value is a BLOB, throw an error.
164883*/
164884static void jsonObjectFunc(
164885  sqlite3_context *ctx,
164886  int argc,
164887  sqlite3_value **argv
164888){
164889  int i;
164890  JsonString jx;
164891  const char *z;
164892  u32 n;
164893
164894  if( argc&1 ){
164895    sqlite3_result_error(ctx, "json_object() requires an even number "
164896                                  "of arguments", -1);
164897    return;
164898  }
164899  jsonInit(&jx, ctx);
164900  jsonAppendChar(&jx, '{');
164901  for(i=0; i<argc; i+=2){
164902    if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
164903      sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
164904      jsonReset(&jx);
164905      return;
164906    }
164907    jsonAppendSeparator(&jx);
164908    z = (const char*)sqlite3_value_text(argv[i]);
164909    n = (u32)sqlite3_value_bytes(argv[i]);
164910    jsonAppendString(&jx, z, n);
164911    jsonAppendChar(&jx, ':');
164912    jsonAppendValue(&jx, argv[i+1]);
164913  }
164914  jsonAppendChar(&jx, '}');
164915  jsonResult(&jx);
164916  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
164917}
164918
164919
164920/*
164921** json_remove(JSON, PATH, ...)
164922**
164923** Remove the named elements from JSON and return the result.  malformed
164924** JSON or PATH arguments result in an error.
164925*/
164926static void jsonRemoveFunc(
164927  sqlite3_context *ctx,
164928  int argc,
164929  sqlite3_value **argv
164930){
164931  JsonParse x;          /* The parse */
164932  JsonNode *pNode;
164933  const char *zPath;
164934  u32 i;
164935
164936  if( argc<1 ) return;
164937  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
164938  assert( x.nNode );
164939  for(i=1; i<(u32)argc; i++){
164940    zPath = (const char*)sqlite3_value_text(argv[i]);
164941    if( zPath==0 ) goto remove_done;
164942    pNode = jsonLookup(&x, zPath, 0, ctx);
164943    if( x.nErr ) goto remove_done;
164944    if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
164945  }
164946  if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
164947    jsonReturnJson(x.aNode, ctx, 0);
164948  }
164949remove_done:
164950  jsonParseReset(&x);
164951}
164952
164953/*
164954** json_replace(JSON, PATH, VALUE, ...)
164955**
164956** Replace the value at PATH with VALUE.  If PATH does not already exist,
164957** this routine is a no-op.  If JSON or PATH is malformed, throw an error.
164958*/
164959static void jsonReplaceFunc(
164960  sqlite3_context *ctx,
164961  int argc,
164962  sqlite3_value **argv
164963){
164964  JsonParse x;          /* The parse */
164965  JsonNode *pNode;
164966  const char *zPath;
164967  u32 i;
164968
164969  if( argc<1 ) return;
164970  if( (argc&1)==0 ) {
164971    jsonWrongNumArgs(ctx, "replace");
164972    return;
164973  }
164974  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
164975  assert( x.nNode );
164976  for(i=1; i<(u32)argc; i+=2){
164977    zPath = (const char*)sqlite3_value_text(argv[i]);
164978    pNode = jsonLookup(&x, zPath, 0, ctx);
164979    if( x.nErr ) goto replace_err;
164980    if( pNode ){
164981      pNode->jnFlags |= (u8)JNODE_REPLACE;
164982      pNode->iVal = (u8)(i+1);
164983    }
164984  }
164985  if( x.aNode[0].jnFlags & JNODE_REPLACE ){
164986    sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
164987  }else{
164988    jsonReturnJson(x.aNode, ctx, argv);
164989  }
164990replace_err:
164991  jsonParseReset(&x);
164992}
164993
164994/*
164995** json_set(JSON, PATH, VALUE, ...)
164996**
164997** Set the value at PATH to VALUE.  Create the PATH if it does not already
164998** exist.  Overwrite existing values that do exist.
164999** If JSON or PATH is malformed, throw an error.
165000**
165001** json_insert(JSON, PATH, VALUE, ...)
165002**
165003** Create PATH and initialize it to VALUE.  If PATH already exists, this
165004** routine is a no-op.  If JSON or PATH is malformed, throw an error.
165005*/
165006static void jsonSetFunc(
165007  sqlite3_context *ctx,
165008  int argc,
165009  sqlite3_value **argv
165010){
165011  JsonParse x;          /* The parse */
165012  JsonNode *pNode;
165013  const char *zPath;
165014  u32 i;
165015  int bApnd;
165016  int bIsSet = *(int*)sqlite3_user_data(ctx);
165017
165018  if( argc<1 ) return;
165019  if( (argc&1)==0 ) {
165020    jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
165021    return;
165022  }
165023  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
165024  assert( x.nNode );
165025  for(i=1; i<(u32)argc; i+=2){
165026    zPath = (const char*)sqlite3_value_text(argv[i]);
165027    bApnd = 0;
165028    pNode = jsonLookup(&x, zPath, &bApnd, ctx);
165029    if( x.oom ){
165030      sqlite3_result_error_nomem(ctx);
165031      goto jsonSetDone;
165032    }else if( x.nErr ){
165033      goto jsonSetDone;
165034    }else if( pNode && (bApnd || bIsSet) ){
165035      pNode->jnFlags |= (u8)JNODE_REPLACE;
165036      pNode->iVal = (u8)(i+1);
165037    }
165038  }
165039  if( x.aNode[0].jnFlags & JNODE_REPLACE ){
165040    sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
165041  }else{
165042    jsonReturnJson(x.aNode, ctx, argv);
165043  }
165044jsonSetDone:
165045  jsonParseReset(&x);
165046}
165047
165048/*
165049** json_type(JSON)
165050** json_type(JSON, PATH)
165051**
165052** Return the top-level "type" of a JSON string.  Throw an error if
165053** either the JSON or PATH inputs are not well-formed.
165054*/
165055static void jsonTypeFunc(
165056  sqlite3_context *ctx,
165057  int argc,
165058  sqlite3_value **argv
165059){
165060  JsonParse x;          /* The parse */
165061  const char *zPath;
165062  JsonNode *pNode;
165063
165064  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
165065  assert( x.nNode );
165066  if( argc==2 ){
165067    zPath = (const char*)sqlite3_value_text(argv[1]);
165068    pNode = jsonLookup(&x, zPath, 0, ctx);
165069  }else{
165070    pNode = x.aNode;
165071  }
165072  if( pNode ){
165073    sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
165074  }
165075  jsonParseReset(&x);
165076}
165077
165078/*
165079** json_valid(JSON)
165080**
165081** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
165082** Return 0 otherwise.
165083*/
165084static void jsonValidFunc(
165085  sqlite3_context *ctx,
165086  int argc,
165087  sqlite3_value **argv
165088){
165089  JsonParse x;          /* The parse */
165090  int rc = 0;
165091
165092  UNUSED_PARAM(argc);
165093  if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
165094    rc = 1;
165095  }
165096  jsonParseReset(&x);
165097  sqlite3_result_int(ctx, rc);
165098}
165099
165100#ifndef SQLITE_OMIT_VIRTUALTABLE
165101/****************************************************************************
165102** The json_each virtual table
165103****************************************************************************/
165104typedef struct JsonEachCursor JsonEachCursor;
165105struct JsonEachCursor {
165106  sqlite3_vtab_cursor base;  /* Base class - must be first */
165107  u32 iRowid;                /* The rowid */
165108  u32 iBegin;                /* The first node of the scan */
165109  u32 i;                     /* Index in sParse.aNode[] of current row */
165110  u32 iEnd;                  /* EOF when i equals or exceeds this value */
165111  u8 eType;                  /* Type of top-level element */
165112  u8 bRecursive;             /* True for json_tree().  False for json_each() */
165113  char *zJson;               /* Input JSON */
165114  char *zRoot;               /* Path by which to filter zJson */
165115  JsonParse sParse;          /* Parse of the input JSON */
165116};
165117
165118/* Constructor for the json_each virtual table */
165119static int jsonEachConnect(
165120  sqlite3 *db,
165121  void *pAux,
165122  int argc, const char *const*argv,
165123  sqlite3_vtab **ppVtab,
165124  char **pzErr
165125){
165126  sqlite3_vtab *pNew;
165127  int rc;
165128
165129/* Column numbers */
165130#define JEACH_KEY     0
165131#define JEACH_VALUE   1
165132#define JEACH_TYPE    2
165133#define JEACH_ATOM    3
165134#define JEACH_ID      4
165135#define JEACH_PARENT  5
165136#define JEACH_FULLKEY 6
165137#define JEACH_PATH    7
165138#define JEACH_JSON    8
165139#define JEACH_ROOT    9
165140
165141  UNUSED_PARAM(pzErr);
165142  UNUSED_PARAM(argv);
165143  UNUSED_PARAM(argc);
165144  UNUSED_PARAM(pAux);
165145  rc = sqlite3_declare_vtab(db,
165146     "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
165147                    "json HIDDEN,root HIDDEN)");
165148  if( rc==SQLITE_OK ){
165149    pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
165150    if( pNew==0 ) return SQLITE_NOMEM;
165151    memset(pNew, 0, sizeof(*pNew));
165152  }
165153  return rc;
165154}
165155
165156/* destructor for json_each virtual table */
165157static int jsonEachDisconnect(sqlite3_vtab *pVtab){
165158  sqlite3_free(pVtab);
165159  return SQLITE_OK;
165160}
165161
165162/* constructor for a JsonEachCursor object for json_each(). */
165163static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
165164  JsonEachCursor *pCur;
165165
165166  UNUSED_PARAM(p);
165167  pCur = sqlite3_malloc( sizeof(*pCur) );
165168  if( pCur==0 ) return SQLITE_NOMEM;
165169  memset(pCur, 0, sizeof(*pCur));
165170  *ppCursor = &pCur->base;
165171  return SQLITE_OK;
165172}
165173
165174/* constructor for a JsonEachCursor object for json_tree(). */
165175static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
165176  int rc = jsonEachOpenEach(p, ppCursor);
165177  if( rc==SQLITE_OK ){
165178    JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
165179    pCur->bRecursive = 1;
165180  }
165181  return rc;
165182}
165183
165184/* Reset a JsonEachCursor back to its original state.  Free any memory
165185** held. */
165186static void jsonEachCursorReset(JsonEachCursor *p){
165187  sqlite3_free(p->zJson);
165188  sqlite3_free(p->zRoot);
165189  jsonParseReset(&p->sParse);
165190  p->iRowid = 0;
165191  p->i = 0;
165192  p->iEnd = 0;
165193  p->eType = 0;
165194  p->zJson = 0;
165195  p->zRoot = 0;
165196}
165197
165198/* Destructor for a jsonEachCursor object */
165199static int jsonEachClose(sqlite3_vtab_cursor *cur){
165200  JsonEachCursor *p = (JsonEachCursor*)cur;
165201  jsonEachCursorReset(p);
165202  sqlite3_free(cur);
165203  return SQLITE_OK;
165204}
165205
165206/* Return TRUE if the jsonEachCursor object has been advanced off the end
165207** of the JSON object */
165208static int jsonEachEof(sqlite3_vtab_cursor *cur){
165209  JsonEachCursor *p = (JsonEachCursor*)cur;
165210  return p->i >= p->iEnd;
165211}
165212
165213/* Advance the cursor to the next element for json_tree() */
165214static int jsonEachNext(sqlite3_vtab_cursor *cur){
165215  JsonEachCursor *p = (JsonEachCursor*)cur;
165216  if( p->bRecursive ){
165217    if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
165218    p->i++;
165219    p->iRowid++;
165220    if( p->i<p->iEnd ){
165221      u32 iUp = p->sParse.aUp[p->i];
165222      JsonNode *pUp = &p->sParse.aNode[iUp];
165223      p->eType = pUp->eType;
165224      if( pUp->eType==JSON_ARRAY ){
165225        if( iUp==p->i-1 ){
165226          pUp->u.iKey = 0;
165227        }else{
165228          pUp->u.iKey++;
165229        }
165230      }
165231    }
165232  }else{
165233    switch( p->eType ){
165234      case JSON_ARRAY: {
165235        p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
165236        p->iRowid++;
165237        break;
165238      }
165239      case JSON_OBJECT: {
165240        p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
165241        p->iRowid++;
165242        break;
165243      }
165244      default: {
165245        p->i = p->iEnd;
165246        break;
165247      }
165248    }
165249  }
165250  return SQLITE_OK;
165251}
165252
165253/* Append the name of the path for element i to pStr
165254*/
165255static void jsonEachComputePath(
165256  JsonEachCursor *p,       /* The cursor */
165257  JsonString *pStr,        /* Write the path here */
165258  u32 i                    /* Path to this element */
165259){
165260  JsonNode *pNode, *pUp;
165261  u32 iUp;
165262  if( i==0 ){
165263    jsonAppendChar(pStr, '$');
165264    return;
165265  }
165266  iUp = p->sParse.aUp[i];
165267  jsonEachComputePath(p, pStr, iUp);
165268  pNode = &p->sParse.aNode[i];
165269  pUp = &p->sParse.aNode[iUp];
165270  if( pUp->eType==JSON_ARRAY ){
165271    jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
165272  }else{
165273    assert( pUp->eType==JSON_OBJECT );
165274    if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
165275    assert( pNode->eType==JSON_STRING );
165276    assert( pNode->jnFlags & JNODE_LABEL );
165277    jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
165278  }
165279}
165280
165281/* Return the value of a column */
165282static int jsonEachColumn(
165283  sqlite3_vtab_cursor *cur,   /* The cursor */
165284  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
165285  int i                       /* Which column to return */
165286){
165287  JsonEachCursor *p = (JsonEachCursor*)cur;
165288  JsonNode *pThis = &p->sParse.aNode[p->i];
165289  switch( i ){
165290    case JEACH_KEY: {
165291      if( p->i==0 ) break;
165292      if( p->eType==JSON_OBJECT ){
165293        jsonReturn(pThis, ctx, 0);
165294      }else if( p->eType==JSON_ARRAY ){
165295        u32 iKey;
165296        if( p->bRecursive ){
165297          if( p->iRowid==0 ) break;
165298          iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
165299        }else{
165300          iKey = p->iRowid;
165301        }
165302        sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
165303      }
165304      break;
165305    }
165306    case JEACH_VALUE: {
165307      if( pThis->jnFlags & JNODE_LABEL ) pThis++;
165308      jsonReturn(pThis, ctx, 0);
165309      break;
165310    }
165311    case JEACH_TYPE: {
165312      if( pThis->jnFlags & JNODE_LABEL ) pThis++;
165313      sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
165314      break;
165315    }
165316    case JEACH_ATOM: {
165317      if( pThis->jnFlags & JNODE_LABEL ) pThis++;
165318      if( pThis->eType>=JSON_ARRAY ) break;
165319      jsonReturn(pThis, ctx, 0);
165320      break;
165321    }
165322    case JEACH_ID: {
165323      sqlite3_result_int64(ctx,
165324         (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
165325      break;
165326    }
165327    case JEACH_PARENT: {
165328      if( p->i>p->iBegin && p->bRecursive ){
165329        sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
165330      }
165331      break;
165332    }
165333    case JEACH_FULLKEY: {
165334      JsonString x;
165335      jsonInit(&x, ctx);
165336      if( p->bRecursive ){
165337        jsonEachComputePath(p, &x, p->i);
165338      }else{
165339        if( p->zRoot ){
165340          jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
165341        }else{
165342          jsonAppendChar(&x, '$');
165343        }
165344        if( p->eType==JSON_ARRAY ){
165345          jsonPrintf(30, &x, "[%d]", p->iRowid);
165346        }else{
165347          jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
165348        }
165349      }
165350      jsonResult(&x);
165351      break;
165352    }
165353    case JEACH_PATH: {
165354      if( p->bRecursive ){
165355        JsonString x;
165356        jsonInit(&x, ctx);
165357        jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
165358        jsonResult(&x);
165359        break;
165360      }
165361      /* For json_each() path and root are the same so fall through
165362      ** into the root case */
165363    }
165364    case JEACH_ROOT: {
165365      const char *zRoot = p->zRoot;
165366       if( zRoot==0 ) zRoot = "$";
165367      sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
165368      break;
165369    }
165370    case JEACH_JSON: {
165371      assert( i==JEACH_JSON );
165372      sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
165373      break;
165374    }
165375  }
165376  return SQLITE_OK;
165377}
165378
165379/* Return the current rowid value */
165380static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
165381  JsonEachCursor *p = (JsonEachCursor*)cur;
165382  *pRowid = p->iRowid;
165383  return SQLITE_OK;
165384}
165385
165386/* The query strategy is to look for an equality constraint on the json
165387** column.  Without such a constraint, the table cannot operate.  idxNum is
165388** 1 if the constraint is found, 3 if the constraint and zRoot are found,
165389** and 0 otherwise.
165390*/
165391static int jsonEachBestIndex(
165392  sqlite3_vtab *tab,
165393  sqlite3_index_info *pIdxInfo
165394){
165395  int i;
165396  int jsonIdx = -1;
165397  int rootIdx = -1;
165398  const struct sqlite3_index_constraint *pConstraint;
165399
165400  UNUSED_PARAM(tab);
165401  pConstraint = pIdxInfo->aConstraint;
165402  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
165403    if( pConstraint->usable==0 ) continue;
165404    if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
165405    switch( pConstraint->iColumn ){
165406      case JEACH_JSON:   jsonIdx = i;    break;
165407      case JEACH_ROOT:   rootIdx = i;    break;
165408      default:           /* no-op */     break;
165409    }
165410  }
165411  if( jsonIdx<0 ){
165412    pIdxInfo->idxNum = 0;
165413    pIdxInfo->estimatedCost = 1e99;
165414  }else{
165415    pIdxInfo->estimatedCost = 1.0;
165416    pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
165417    pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
165418    if( rootIdx<0 ){
165419      pIdxInfo->idxNum = 1;
165420    }else{
165421      pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
165422      pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
165423      pIdxInfo->idxNum = 3;
165424    }
165425  }
165426  return SQLITE_OK;
165427}
165428
165429/* Start a search on a new JSON string */
165430static int jsonEachFilter(
165431  sqlite3_vtab_cursor *cur,
165432  int idxNum, const char *idxStr,
165433  int argc, sqlite3_value **argv
165434){
165435  JsonEachCursor *p = (JsonEachCursor*)cur;
165436  const char *z;
165437  const char *zRoot = 0;
165438  sqlite3_int64 n;
165439
165440  UNUSED_PARAM(idxStr);
165441  UNUSED_PARAM(argc);
165442  jsonEachCursorReset(p);
165443  if( idxNum==0 ) return SQLITE_OK;
165444  z = (const char*)sqlite3_value_text(argv[0]);
165445  if( z==0 ) return SQLITE_OK;
165446  n = sqlite3_value_bytes(argv[0]);
165447  p->zJson = sqlite3_malloc64( n+1 );
165448  if( p->zJson==0 ) return SQLITE_NOMEM;
165449  memcpy(p->zJson, z, (size_t)n+1);
165450  if( jsonParse(&p->sParse, 0, p->zJson) ){
165451    int rc = SQLITE_NOMEM;
165452    if( p->sParse.oom==0 ){
165453      sqlite3_free(cur->pVtab->zErrMsg);
165454      cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
165455      if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
165456    }
165457    jsonEachCursorReset(p);
165458    return rc;
165459  }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
165460    jsonEachCursorReset(p);
165461    return SQLITE_NOMEM;
165462  }else{
165463    JsonNode *pNode = 0;
165464    if( idxNum==3 ){
165465      const char *zErr = 0;
165466      zRoot = (const char*)sqlite3_value_text(argv[1]);
165467      if( zRoot==0 ) return SQLITE_OK;
165468      n = sqlite3_value_bytes(argv[1]);
165469      p->zRoot = sqlite3_malloc64( n+1 );
165470      if( p->zRoot==0 ) return SQLITE_NOMEM;
165471      memcpy(p->zRoot, zRoot, (size_t)n+1);
165472      if( zRoot[0]!='$' ){
165473        zErr = zRoot;
165474      }else{
165475        pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
165476      }
165477      if( zErr ){
165478        sqlite3_free(cur->pVtab->zErrMsg);
165479        cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
165480        jsonEachCursorReset(p);
165481        return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
165482      }else if( pNode==0 ){
165483        return SQLITE_OK;
165484      }
165485    }else{
165486      pNode = p->sParse.aNode;
165487    }
165488    p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
165489    p->eType = pNode->eType;
165490    if( p->eType>=JSON_ARRAY ){
165491      pNode->u.iKey = 0;
165492      p->iEnd = p->i + pNode->n + 1;
165493      if( p->bRecursive ){
165494        p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
165495        if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
165496          p->i--;
165497        }
165498      }else{
165499        p->i++;
165500      }
165501    }else{
165502      p->iEnd = p->i+1;
165503    }
165504  }
165505  return SQLITE_OK;
165506}
165507
165508/* The methods of the json_each virtual table */
165509static sqlite3_module jsonEachModule = {
165510  0,                         /* iVersion */
165511  0,                         /* xCreate */
165512  jsonEachConnect,           /* xConnect */
165513  jsonEachBestIndex,         /* xBestIndex */
165514  jsonEachDisconnect,        /* xDisconnect */
165515  0,                         /* xDestroy */
165516  jsonEachOpenEach,          /* xOpen - open a cursor */
165517  jsonEachClose,             /* xClose - close a cursor */
165518  jsonEachFilter,            /* xFilter - configure scan constraints */
165519  jsonEachNext,              /* xNext - advance a cursor */
165520  jsonEachEof,               /* xEof - check for end of scan */
165521  jsonEachColumn,            /* xColumn - read data */
165522  jsonEachRowid,             /* xRowid - read data */
165523  0,                         /* xUpdate */
165524  0,                         /* xBegin */
165525  0,                         /* xSync */
165526  0,                         /* xCommit */
165527  0,                         /* xRollback */
165528  0,                         /* xFindMethod */
165529  0,                         /* xRename */
165530  0,                         /* xSavepoint */
165531  0,                         /* xRelease */
165532  0                          /* xRollbackTo */
165533};
165534
165535/* The methods of the json_tree virtual table. */
165536static sqlite3_module jsonTreeModule = {
165537  0,                         /* iVersion */
165538  0,                         /* xCreate */
165539  jsonEachConnect,           /* xConnect */
165540  jsonEachBestIndex,         /* xBestIndex */
165541  jsonEachDisconnect,        /* xDisconnect */
165542  0,                         /* xDestroy */
165543  jsonEachOpenTree,          /* xOpen - open a cursor */
165544  jsonEachClose,             /* xClose - close a cursor */
165545  jsonEachFilter,            /* xFilter - configure scan constraints */
165546  jsonEachNext,              /* xNext - advance a cursor */
165547  jsonEachEof,               /* xEof - check for end of scan */
165548  jsonEachColumn,            /* xColumn - read data */
165549  jsonEachRowid,             /* xRowid - read data */
165550  0,                         /* xUpdate */
165551  0,                         /* xBegin */
165552  0,                         /* xSync */
165553  0,                         /* xCommit */
165554  0,                         /* xRollback */
165555  0,                         /* xFindMethod */
165556  0,                         /* xRename */
165557  0,                         /* xSavepoint */
165558  0,                         /* xRelease */
165559  0                          /* xRollbackTo */
165560};
165561#endif /* SQLITE_OMIT_VIRTUALTABLE */
165562
165563/****************************************************************************
165564** The following routines are the only publically visible identifiers in this
165565** file.  Call the following routines in order to register the various SQL
165566** functions and the virtual table implemented by this file.
165567****************************************************************************/
165568
165569SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
165570  int rc = SQLITE_OK;
165571  unsigned int i;
165572  static const struct {
165573     const char *zName;
165574     int nArg;
165575     int flag;
165576     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
165577  } aFunc[] = {
165578    { "json",                 1, 0,   jsonRemoveFunc        },
165579    { "json_array",          -1, 0,   jsonArrayFunc         },
165580    { "json_array_length",    1, 0,   jsonArrayLengthFunc   },
165581    { "json_array_length",    2, 0,   jsonArrayLengthFunc   },
165582    { "json_extract",        -1, 0,   jsonExtractFunc       },
165583    { "json_insert",         -1, 0,   jsonSetFunc           },
165584    { "json_object",         -1, 0,   jsonObjectFunc        },
165585    { "json_remove",         -1, 0,   jsonRemoveFunc        },
165586    { "json_replace",        -1, 0,   jsonReplaceFunc       },
165587    { "json_set",            -1, 1,   jsonSetFunc           },
165588    { "json_type",            1, 0,   jsonTypeFunc          },
165589    { "json_type",            2, 0,   jsonTypeFunc          },
165590    { "json_valid",           1, 0,   jsonValidFunc         },
165591
165592#if SQLITE_DEBUG
165593    /* DEBUG and TESTING functions */
165594    { "json_parse",           1, 0,   jsonParseFunc         },
165595    { "json_test1",           1, 0,   jsonTest1Func         },
165596#endif
165597  };
165598#ifndef SQLITE_OMIT_VIRTUALTABLE
165599  static const struct {
165600     const char *zName;
165601     sqlite3_module *pModule;
165602  } aMod[] = {
165603    { "json_each",            &jsonEachModule               },
165604    { "json_tree",            &jsonTreeModule               },
165605  };
165606#endif
165607  for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
165608    rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
165609                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
165610                                 (void*)&aFunc[i].flag,
165611                                 aFunc[i].xFunc, 0, 0);
165612  }
165613#ifndef SQLITE_OMIT_VIRTUALTABLE
165614  for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
165615    rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
165616  }
165617#endif
165618  return rc;
165619}
165620
165621
165622#ifndef SQLITE_CORE
165623#ifdef _WIN32
165624__declspec(dllexport)
165625#endif
165626SQLITE_API int SQLITE_STDCALL sqlite3_json_init(
165627  sqlite3 *db,
165628  char **pzErrMsg,
165629  const sqlite3_api_routines *pApi
165630){
165631  SQLITE_EXTENSION_INIT2(pApi);
165632  (void)pzErrMsg;  /* Unused parameter */
165633  return sqlite3Json1Init(db);
165634}
165635#endif
165636#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
165637
165638/************** End of json1.c ***********************************************/
165639/************** Begin file fts5.c ********************************************/
165640
165641
165642#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
165643
165644#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
165645# define NDEBUG 1
165646#endif
165647#if defined(NDEBUG) && defined(SQLITE_DEBUG)
165648# undef NDEBUG
165649#endif
165650
165651/*
165652** 2014 May 31
165653**
165654** The author disclaims copyright to this source code.  In place of
165655** a legal notice, here is a blessing:
165656**
165657**    May you do good and not evil.
165658**    May you find forgiveness for yourself and forgive others.
165659**    May you share freely, never taking more than you give.
165660**
165661******************************************************************************
165662**
165663** Interfaces to extend FTS5. Using the interfaces defined in this file,
165664** FTS5 may be extended with:
165665**
165666**     * custom tokenizers, and
165667**     * custom auxiliary functions.
165668*/
165669
165670
165671#ifndef _FTS5_H
165672#define _FTS5_H
165673
165674/* #include "sqlite3.h" */
165675
165676#if 0
165677extern "C" {
165678#endif
165679
165680/*************************************************************************
165681** CUSTOM AUXILIARY FUNCTIONS
165682**
165683** Virtual table implementations may overload SQL functions by implementing
165684** the sqlite3_module.xFindFunction() method.
165685*/
165686
165687typedef struct Fts5ExtensionApi Fts5ExtensionApi;
165688typedef struct Fts5Context Fts5Context;
165689typedef struct Fts5PhraseIter Fts5PhraseIter;
165690
165691typedef void (*fts5_extension_function)(
165692  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
165693  Fts5Context *pFts,              /* First arg to pass to pApi functions */
165694  sqlite3_context *pCtx,          /* Context for returning result/error */
165695  int nVal,                       /* Number of values in apVal[] array */
165696  sqlite3_value **apVal           /* Array of trailing arguments */
165697);
165698
165699struct Fts5PhraseIter {
165700  const unsigned char *a;
165701  const unsigned char *b;
165702};
165703
165704/*
165705** EXTENSION API FUNCTIONS
165706**
165707** xUserData(pFts):
165708**   Return a copy of the context pointer the extension function was
165709**   registered with.
165710**
165711** xColumnTotalSize(pFts, iCol, pnToken):
165712**   If parameter iCol is less than zero, set output variable *pnToken
165713**   to the total number of tokens in the FTS5 table. Or, if iCol is
165714**   non-negative but less than the number of columns in the table, return
165715**   the total number of tokens in column iCol, considering all rows in
165716**   the FTS5 table.
165717**
165718**   If parameter iCol is greater than or equal to the number of columns
165719**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
165720**   an OOM condition or IO error), an appropriate SQLite error code is
165721**   returned.
165722**
165723** xColumnCount(pFts):
165724**   Return the number of columns in the table.
165725**
165726** xColumnSize(pFts, iCol, pnToken):
165727**   If parameter iCol is less than zero, set output variable *pnToken
165728**   to the total number of tokens in the current row. Or, if iCol is
165729**   non-negative but less than the number of columns in the table, set
165730**   *pnToken to the number of tokens in column iCol of the current row.
165731**
165732**   If parameter iCol is greater than or equal to the number of columns
165733**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
165734**   an OOM condition or IO error), an appropriate SQLite error code is
165735**   returned.
165736**
165737** xColumnText:
165738**   This function attempts to retrieve the text of column iCol of the
165739**   current document. If successful, (*pz) is set to point to a buffer
165740**   containing the text in utf-8 encoding, (*pn) is set to the size in bytes
165741**   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
165742**   if an error occurs, an SQLite error code is returned and the final values
165743**   of (*pz) and (*pn) are undefined.
165744**
165745** xPhraseCount:
165746**   Returns the number of phrases in the current query expression.
165747**
165748** xPhraseSize:
165749**   Returns the number of tokens in phrase iPhrase of the query. Phrases
165750**   are numbered starting from zero.
165751**
165752** xInstCount:
165753**   Set *pnInst to the total number of occurrences of all phrases within
165754**   the query within the current row. Return SQLITE_OK if successful, or
165755**   an error code (i.e. SQLITE_NOMEM) if an error occurs.
165756**
165757** xInst:
165758**   Query for the details of phrase match iIdx within the current row.
165759**   Phrase matches are numbered starting from zero, so the iIdx argument
165760**   should be greater than or equal to zero and smaller than the value
165761**   output by xInstCount().
165762**
165763**   Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
165764**   if an error occurs.
165765**
165766** xRowid:
165767**   Returns the rowid of the current row.
165768**
165769** xTokenize:
165770**   Tokenize text using the tokenizer belonging to the FTS5 table.
165771**
165772** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
165773**   This API function is used to query the FTS table for phrase iPhrase
165774**   of the current query. Specifically, a query equivalent to:
165775**
165776**       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
165777**
165778**   with $p set to a phrase equivalent to the phrase iPhrase of the
165779**   current query is executed. For each row visited, the callback function
165780**   passed as the fourth argument is invoked. The context and API objects
165781**   passed to the callback function may be used to access the properties of
165782**   each matched row. Invoking Api.xUserData() returns a copy of the pointer
165783**   passed as the third argument to pUserData.
165784**
165785**   If the callback function returns any value other than SQLITE_OK, the
165786**   query is abandoned and the xQueryPhrase function returns immediately.
165787**   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
165788**   Otherwise, the error code is propagated upwards.
165789**
165790**   If the query runs to completion without incident, SQLITE_OK is returned.
165791**   Or, if some error occurs before the query completes or is aborted by
165792**   the callback, an SQLite error code is returned.
165793**
165794**
165795** xSetAuxdata(pFts5, pAux, xDelete)
165796**
165797**   Save the pointer passed as the second argument as the extension functions
165798**   "auxiliary data". The pointer may then be retrieved by the current or any
165799**   future invocation of the same fts5 extension function made as part of
165800**   of the same MATCH query using the xGetAuxdata() API.
165801**
165802**   Each extension function is allocated a single auxiliary data slot for
165803**   each FTS query (MATCH expression). If the extension function is invoked
165804**   more than once for a single FTS query, then all invocations share a
165805**   single auxiliary data context.
165806**
165807**   If there is already an auxiliary data pointer when this function is
165808**   invoked, then it is replaced by the new pointer. If an xDelete callback
165809**   was specified along with the original pointer, it is invoked at this
165810**   point.
165811**
165812**   The xDelete callback, if one is specified, is also invoked on the
165813**   auxiliary data pointer after the FTS5 query has finished.
165814**
165815**   If an error (e.g. an OOM condition) occurs within this function, an
165816**   the auxiliary data is set to NULL and an error code returned. If the
165817**   xDelete parameter was not NULL, it is invoked on the auxiliary data
165818**   pointer before returning.
165819**
165820**
165821** xGetAuxdata(pFts5, bClear)
165822**
165823**   Returns the current auxiliary data pointer for the fts5 extension
165824**   function. See the xSetAuxdata() method for details.
165825**
165826**   If the bClear argument is non-zero, then the auxiliary data is cleared
165827**   (set to NULL) before this function returns. In this case the xDelete,
165828**   if any, is not invoked.
165829**
165830**
165831** xRowCount(pFts5, pnRow)
165832**
165833**   This function is used to retrieve the total number of rows in the table.
165834**   In other words, the same value that would be returned by:
165835**
165836**        SELECT count(*) FROM ftstable;
165837**
165838** xPhraseFirst()
165839**   This function is used, along with type Fts5PhraseIter and the xPhraseNext
165840**   method, to iterate through all instances of a single query phrase within
165841**   the current row. This is the same information as is accessible via the
165842**   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
165843**   to use, this API may be faster under some circumstances. To iterate
165844**   through instances of phrase iPhrase, use the following code:
165845**
165846**       Fts5PhraseIter iter;
165847**       int iCol, iOff;
165848**       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
165849**           iOff>=0;
165850**           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
165851**       ){
165852**         // An instance of phrase iPhrase at offset iOff of column iCol
165853**       }
165854**
165855**   The Fts5PhraseIter structure is defined above. Applications should not
165856**   modify this structure directly - it should only be used as shown above
165857**   with the xPhraseFirst() and xPhraseNext() API methods.
165858**
165859** xPhraseNext()
165860**   See xPhraseFirst above.
165861*/
165862struct Fts5ExtensionApi {
165863  int iVersion;                   /* Currently always set to 1 */
165864
165865  void *(*xUserData)(Fts5Context*);
165866
165867  int (*xColumnCount)(Fts5Context*);
165868  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
165869  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
165870
165871  int (*xTokenize)(Fts5Context*,
165872    const char *pText, int nText, /* Text to tokenize */
165873    void *pCtx,                   /* Context passed to xToken() */
165874    int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
165875  );
165876
165877  int (*xPhraseCount)(Fts5Context*);
165878  int (*xPhraseSize)(Fts5Context*, int iPhrase);
165879
165880  int (*xInstCount)(Fts5Context*, int *pnInst);
165881  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
165882
165883  sqlite3_int64 (*xRowid)(Fts5Context*);
165884  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
165885  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
165886
165887  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
165888    int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
165889  );
165890  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
165891  void *(*xGetAuxdata)(Fts5Context*, int bClear);
165892
165893  void (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
165894  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
165895};
165896
165897/*
165898** CUSTOM AUXILIARY FUNCTIONS
165899*************************************************************************/
165900
165901/*************************************************************************
165902** CUSTOM TOKENIZERS
165903**
165904** Applications may also register custom tokenizer types. A tokenizer
165905** is registered by providing fts5 with a populated instance of the
165906** following structure. All structure methods must be defined, setting
165907** any member of the fts5_tokenizer struct to NULL leads to undefined
165908** behaviour. The structure methods are expected to function as follows:
165909**
165910** xCreate:
165911**   This function is used to allocate and inititalize a tokenizer instance.
165912**   A tokenizer instance is required to actually tokenize text.
165913**
165914**   The first argument passed to this function is a copy of the (void*)
165915**   pointer provided by the application when the fts5_tokenizer object
165916**   was registered with FTS5 (the third argument to xCreateTokenizer()).
165917**   The second and third arguments are an array of nul-terminated strings
165918**   containing the tokenizer arguments, if any, specified following the
165919**   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
165920**   to create the FTS5 table.
165921**
165922**   The final argument is an output variable. If successful, (*ppOut)
165923**   should be set to point to the new tokenizer handle and SQLITE_OK
165924**   returned. If an error occurs, some value other than SQLITE_OK should
165925**   be returned. In this case, fts5 assumes that the final value of *ppOut
165926**   is undefined.
165927**
165928** xDelete:
165929**   This function is invoked to delete a tokenizer handle previously
165930**   allocated using xCreate(). Fts5 guarantees that this function will
165931**   be invoked exactly once for each successful call to xCreate().
165932**
165933** xTokenize:
165934**   This function is expected to tokenize the nText byte string indicated
165935**   by argument pText. pText may or may not be nul-terminated. The first
165936**   argument passed to this function is a pointer to an Fts5Tokenizer object
165937**   returned by an earlier call to xCreate().
165938**
165939**   The second argument indicates the reason that FTS5 is requesting
165940**   tokenization of the supplied text. This is always one of the following
165941**   four values:
165942**
165943**   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
165944**            or removed from the FTS table. The tokenizer is being invoked to
165945**            determine the set of tokens to add to (or delete from) the
165946**            FTS index.
165947**
165948**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
165949**            against the FTS index. The tokenizer is being called to tokenize
165950**            a bareword or quoted string specified as part of the query.
165951**
165952**       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
165953**            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
165954**            followed by a "*" character, indicating that the last token
165955**            returned by the tokenizer will be treated as a token prefix.
165956**
165957**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
165958**            satisfy an fts5_api.xTokenize() request made by an auxiliary
165959**            function. Or an fts5_api.xColumnSize() request made by the same
165960**            on a columnsize=0 database.
165961**   </ul>
165962**
165963**   For each token in the input string, the supplied callback xToken() must
165964**   be invoked. The first argument to it should be a copy of the pointer
165965**   passed as the second argument to xTokenize(). The third and fourth
165966**   arguments are a pointer to a buffer containing the token text, and the
165967**   size of the token in bytes. The 4th and 5th arguments are the byte offsets
165968**   of the first byte of and first byte immediately following the text from
165969**   which the token is derived within the input.
165970**
165971**   The second argument passed to the xToken() callback ("tflags") should
165972**   normally be set to 0. The exception is if the tokenizer supports
165973**   synonyms. In this case see the discussion below for details.
165974**
165975**   FTS5 assumes the xToken() callback is invoked for each token in the
165976**   order that they occur within the input text.
165977**
165978**   If an xToken() callback returns any value other than SQLITE_OK, then
165979**   the tokenization should be abandoned and the xTokenize() method should
165980**   immediately return a copy of the xToken() return value. Or, if the
165981**   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
165982**   if an error occurs with the xTokenize() implementation itself, it
165983**   may abandon the tokenization and return any error code other than
165984**   SQLITE_OK or SQLITE_DONE.
165985**
165986** SYNONYM SUPPORT
165987**
165988**   Custom tokenizers may also support synonyms. Consider a case in which a
165989**   user wishes to query for a phrase such as "first place". Using the
165990**   built-in tokenizers, the FTS5 query 'first + place' will match instances
165991**   of "first place" within the document set, but not alternative forms
165992**   such as "1st place". In some applications, it would be better to match
165993**   all instances of "first place" or "1st place" regardless of which form
165994**   the user specified in the MATCH query text.
165995**
165996**   There are several ways to approach this in FTS5:
165997**
165998**   <ol><li> By mapping all synonyms to a single token. In this case, the
165999**            In the above example, this means that the tokenizer returns the
166000**            same token for inputs "first" and "1st". Say that token is in
166001**            fact "first", so that when the user inserts the document "I won
166002**            1st place" entries are added to the index for tokens "i", "won",
166003**            "first" and "place". If the user then queries for '1st + place',
166004**            the tokenizer substitutes "first" for "1st" and the query works
166005**            as expected.
166006**
166007**       <li> By adding multiple synonyms for a single term to the FTS index.
166008**            In this case, when tokenizing query text, the tokenizer may
166009**            provide multiple synonyms for a single term within the document.
166010**            FTS5 then queries the index for each synonym individually. For
166011**            example, faced with the query:
166012**
166013**   <codeblock>
166014**     ... MATCH 'first place'</codeblock>
166015**
166016**            the tokenizer offers both "1st" and "first" as synonyms for the
166017**            first token in the MATCH query and FTS5 effectively runs a query
166018**            similar to:
166019**
166020**   <codeblock>
166021**     ... MATCH '(first OR 1st) place'</codeblock>
166022**
166023**            except that, for the purposes of auxiliary functions, the query
166024**            still appears to contain just two phrases - "(first OR 1st)"
166025**            being treated as a single phrase.
166026**
166027**       <li> By adding multiple synonyms for a single term to the FTS index.
166028**            Using this method, when tokenizing document text, the tokenizer
166029**            provides multiple synonyms for each token. So that when a
166030**            document such as "I won first place" is tokenized, entries are
166031**            added to the FTS index for "i", "won", "first", "1st" and
166032**            "place".
166033**
166034**            This way, even if the tokenizer does not provide synonyms
166035**            when tokenizing query text (it should not - to do would be
166036**            inefficient), it doesn't matter if the user queries for
166037**            'first + place' or '1st + place', as there are entires in the
166038**            FTS index corresponding to both forms of the first token.
166039**   </ol>
166040**
166041**   Whether it is parsing document or query text, any call to xToken that
166042**   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
166043**   is considered to supply a synonym for the previous token. For example,
166044**   when parsing the document "I won first place", a tokenizer that supports
166045**   synonyms would call xToken() 5 times, as follows:
166046**
166047**   <codeblock>
166048**       xToken(pCtx, 0, "i",                      1,  0,  1);
166049**       xToken(pCtx, 0, "won",                    3,  2,  5);
166050**       xToken(pCtx, 0, "first",                  5,  6, 11);
166051**       xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3,  6, 11);
166052**       xToken(pCtx, 0, "place",                  5, 12, 17);
166053**</codeblock>
166054**
166055**   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
166056**   xToken() is called. Multiple synonyms may be specified for a single token
166057**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
166058**   There is no limit to the number of synonyms that may be provided for a
166059**   single token.
166060**
166061**   In many cases, method (1) above is the best approach. It does not add
166062**   extra data to the FTS index or require FTS5 to query for multiple terms,
166063**   so it is efficient in terms of disk space and query speed. However, it
166064**   does not support prefix queries very well. If, as suggested above, the
166065**   token "first" is subsituted for "1st" by the tokenizer, then the query:
166066**
166067**   <codeblock>
166068**     ... MATCH '1s*'</codeblock>
166069**
166070**   will not match documents that contain the token "1st" (as the tokenizer
166071**   will probably not map "1s" to any prefix of "first").
166072**
166073**   For full prefix support, method (3) may be preferred. In this case,
166074**   because the index contains entries for both "first" and "1st", prefix
166075**   queries such as 'fi*' or '1s*' will match correctly. However, because
166076**   extra entries are added to the FTS index, this method uses more space
166077**   within the database.
166078**
166079**   Method (2) offers a midpoint between (1) and (3). Using this method,
166080**   a query such as '1s*' will match documents that contain the literal
166081**   token "1st", but not "first" (assuming the tokenizer is not able to
166082**   provide synonyms for prefixes). However, a non-prefix query like '1st'
166083**   will match against "1st" and "first". This method does not require
166084**   extra disk space, as no extra entries are added to the FTS index.
166085**   On the other hand, it may require more CPU cycles to run MATCH queries,
166086**   as separate queries of the FTS index are required for each synonym.
166087**
166088**   When using methods (2) or (3), it is important that the tokenizer only
166089**   provide synonyms when tokenizing document text (method (2)) or query
166090**   text (method (3)), not both. Doing so will not cause any errors, but is
166091**   inefficient.
166092*/
166093typedef struct Fts5Tokenizer Fts5Tokenizer;
166094typedef struct fts5_tokenizer fts5_tokenizer;
166095struct fts5_tokenizer {
166096  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
166097  void (*xDelete)(Fts5Tokenizer*);
166098  int (*xTokenize)(Fts5Tokenizer*,
166099      void *pCtx,
166100      int flags,            /* Mask of FTS5_TOKENIZE_* flags */
166101      const char *pText, int nText,
166102      int (*xToken)(
166103        void *pCtx,         /* Copy of 2nd argument to xTokenize() */
166104        int tflags,         /* Mask of FTS5_TOKEN_* flags */
166105        const char *pToken, /* Pointer to buffer containing token */
166106        int nToken,         /* Size of token in bytes */
166107        int iStart,         /* Byte offset of token within input text */
166108        int iEnd            /* Byte offset of end of token within input text */
166109      )
166110  );
166111};
166112
166113/* Flags that may be passed as the third argument to xTokenize() */
166114#define FTS5_TOKENIZE_QUERY     0x0001
166115#define FTS5_TOKENIZE_PREFIX    0x0002
166116#define FTS5_TOKENIZE_DOCUMENT  0x0004
166117#define FTS5_TOKENIZE_AUX       0x0008
166118
166119/* Flags that may be passed by the tokenizer implementation back to FTS5
166120** as the third argument to the supplied xToken callback. */
166121#define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */
166122
166123/*
166124** END OF CUSTOM TOKENIZERS
166125*************************************************************************/
166126
166127/*************************************************************************
166128** FTS5 EXTENSION REGISTRATION API
166129*/
166130typedef struct fts5_api fts5_api;
166131struct fts5_api {
166132  int iVersion;                   /* Currently always set to 2 */
166133
166134  /* Create a new tokenizer */
166135  int (*xCreateTokenizer)(
166136    fts5_api *pApi,
166137    const char *zName,
166138    void *pContext,
166139    fts5_tokenizer *pTokenizer,
166140    void (*xDestroy)(void*)
166141  );
166142
166143  /* Find an existing tokenizer */
166144  int (*xFindTokenizer)(
166145    fts5_api *pApi,
166146    const char *zName,
166147    void **ppContext,
166148    fts5_tokenizer *pTokenizer
166149  );
166150
166151  /* Create a new auxiliary function */
166152  int (*xCreateFunction)(
166153    fts5_api *pApi,
166154    const char *zName,
166155    void *pContext,
166156    fts5_extension_function xFunction,
166157    void (*xDestroy)(void*)
166158  );
166159};
166160
166161/*
166162** END OF REGISTRATION API
166163*************************************************************************/
166164
166165#if 0
166166}  /* end of the 'extern "C"' block */
166167#endif
166168
166169#endif /* _FTS5_H */
166170
166171
166172/*
166173** 2014 May 31
166174**
166175** The author disclaims copyright to this source code.  In place of
166176** a legal notice, here is a blessing:
166177**
166178**    May you do good and not evil.
166179**    May you find forgiveness for yourself and forgive others.
166180**    May you share freely, never taking more than you give.
166181**
166182******************************************************************************
166183**
166184*/
166185#ifndef _FTS5INT_H
166186#define _FTS5INT_H
166187
166188/* #include "sqlite3ext.h" */
166189SQLITE_EXTENSION_INIT1
166190
166191/* #include <string.h> */
166192/* #include <assert.h> */
166193
166194#ifndef SQLITE_AMALGAMATION
166195
166196typedef unsigned char  u8;
166197typedef unsigned int   u32;
166198typedef unsigned short u16;
166199typedef sqlite3_int64 i64;
166200typedef sqlite3_uint64 u64;
166201
166202#define ArraySize(x) (sizeof(x) / sizeof(x[0]))
166203
166204#define testcase(x)
166205#define ALWAYS(x) 1
166206#define NEVER(x) 0
166207
166208#define MIN(x,y) (((x) < (y)) ? (x) : (y))
166209#define MAX(x,y) (((x) > (y)) ? (x) : (y))
166210
166211/*
166212** Constants for the largest and smallest possible 64-bit signed integers.
166213*/
166214# define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
166215# define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
166216
166217#endif
166218
166219
166220/*
166221** Maximum number of prefix indexes on single FTS5 table. This must be
166222** less than 32. If it is set to anything large than that, an #error
166223** directive in fts5_index.c will cause the build to fail.
166224*/
166225#define FTS5_MAX_PREFIX_INDEXES 31
166226
166227#define FTS5_DEFAULT_NEARDIST 10
166228#define FTS5_DEFAULT_RANK     "bm25"
166229
166230/* Name of rank and rowid columns */
166231#define FTS5_RANK_NAME "rank"
166232#define FTS5_ROWID_NAME "rowid"
166233
166234#ifdef SQLITE_DEBUG
166235# define FTS5_CORRUPT sqlite3Fts5Corrupt()
166236static int sqlite3Fts5Corrupt(void);
166237#else
166238# define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
166239#endif
166240
166241/*
166242** The assert_nc() macro is similar to the assert() macro, except that it
166243** is used for assert() conditions that are true only if it can be
166244** guranteed that the database is not corrupt.
166245*/
166246#ifdef SQLITE_DEBUG
166247SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
166248# define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
166249#else
166250# define assert_nc(x) assert(x)
166251#endif
166252
166253typedef struct Fts5Global Fts5Global;
166254typedef struct Fts5Colset Fts5Colset;
166255
166256/* If a NEAR() clump or phrase may only match a specific set of columns,
166257** then an object of the following type is used to record the set of columns.
166258** Each entry in the aiCol[] array is a column that may be matched.
166259**
166260** This object is used by fts5_expr.c and fts5_index.c.
166261*/
166262struct Fts5Colset {
166263  int nCol;
166264  int aiCol[1];
166265};
166266
166267
166268
166269/**************************************************************************
166270** Interface to code in fts5_config.c. fts5_config.c contains contains code
166271** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
166272*/
166273
166274typedef struct Fts5Config Fts5Config;
166275
166276/*
166277** An instance of the following structure encodes all information that can
166278** be gleaned from the CREATE VIRTUAL TABLE statement.
166279**
166280** And all information loaded from the %_config table.
166281**
166282** nAutomerge:
166283**   The minimum number of segments that an auto-merge operation should
166284**   attempt to merge together. A value of 1 sets the object to use the
166285**   compile time default. Zero disables auto-merge altogether.
166286**
166287** zContent:
166288**
166289** zContentRowid:
166290**   The value of the content_rowid= option, if one was specified. Or
166291**   the string "rowid" otherwise. This text is not quoted - if it is
166292**   used as part of an SQL statement it needs to be quoted appropriately.
166293**
166294** zContentExprlist:
166295**
166296** pzErrmsg:
166297**   This exists in order to allow the fts5_index.c module to return a
166298**   decent error message if it encounters a file-format version it does
166299**   not understand.
166300**
166301** bColumnsize:
166302**   True if the %_docsize table is created.
166303**
166304** bPrefixIndex:
166305**   This is only used for debugging. If set to false, any prefix indexes
166306**   are ignored. This value is configured using:
166307**
166308**       INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
166309**
166310*/
166311struct Fts5Config {
166312  sqlite3 *db;                    /* Database handle */
166313  char *zDb;                      /* Database holding FTS index (e.g. "main") */
166314  char *zName;                    /* Name of FTS index */
166315  int nCol;                       /* Number of columns */
166316  char **azCol;                   /* Column names */
166317  u8 *abUnindexed;                /* True for unindexed columns */
166318  int nPrefix;                    /* Number of prefix indexes */
166319  int *aPrefix;                   /* Sizes in bytes of nPrefix prefix indexes */
166320  int eContent;                   /* An FTS5_CONTENT value */
166321  char *zContent;                 /* content table */
166322  char *zContentRowid;            /* "content_rowid=" option value */
166323  int bColumnsize;                /* "columnsize=" option value (dflt==1) */
166324  char *zContentExprlist;
166325  Fts5Tokenizer *pTok;
166326  fts5_tokenizer *pTokApi;
166327
166328  /* Values loaded from the %_config table */
166329  int iCookie;                    /* Incremented when %_config is modified */
166330  int pgsz;                       /* Approximate page size used in %_data */
166331  int nAutomerge;                 /* 'automerge' setting */
166332  int nCrisisMerge;               /* Maximum allowed segments per level */
166333  char *zRank;                    /* Name of rank function */
166334  char *zRankArgs;                /* Arguments to rank function */
166335
166336  /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
166337  char **pzErrmsg;
166338
166339#ifdef SQLITE_DEBUG
166340  int bPrefixIndex;               /* True to use prefix-indexes */
166341#endif
166342};
166343
166344/* Current expected value of %_config table 'version' field */
166345#define FTS5_CURRENT_VERSION 4
166346
166347#define FTS5_CONTENT_NORMAL   0
166348#define FTS5_CONTENT_NONE     1
166349#define FTS5_CONTENT_EXTERNAL 2
166350
166351
166352
166353
166354static int sqlite3Fts5ConfigParse(
166355    Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
166356);
166357static void sqlite3Fts5ConfigFree(Fts5Config*);
166358
166359static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
166360
166361static int sqlite3Fts5Tokenize(
166362  Fts5Config *pConfig,            /* FTS5 Configuration object */
166363  int flags,                      /* FTS5_TOKENIZE_* flags */
166364  const char *pText, int nText,   /* Text to tokenize */
166365  void *pCtx,                     /* Context passed to xToken() */
166366  int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
166367);
166368
166369static void sqlite3Fts5Dequote(char *z);
166370
166371/* Load the contents of the %_config table */
166372static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
166373
166374/* Set the value of a single config attribute */
166375static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
166376
166377static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
166378
166379/*
166380** End of interface to code in fts5_config.c.
166381**************************************************************************/
166382
166383/**************************************************************************
166384** Interface to code in fts5_buffer.c.
166385*/
166386
166387/*
166388** Buffer object for the incremental building of string data.
166389*/
166390typedef struct Fts5Buffer Fts5Buffer;
166391struct Fts5Buffer {
166392  u8 *p;
166393  int n;
166394  int nSpace;
166395};
166396
166397static int sqlite3Fts5BufferGrow(int*, Fts5Buffer*, int);
166398static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
166399static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, int, const u8*);
166400static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
166401static void sqlite3Fts5BufferFree(Fts5Buffer*);
166402static void sqlite3Fts5BufferZero(Fts5Buffer*);
166403static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
166404static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
166405static void sqlite3Fts5BufferAppend32(int*, Fts5Buffer*, int);
166406
166407static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
166408
166409#define fts5BufferZero(x)             sqlite3Fts5BufferZero(x)
166410#define fts5BufferGrow(a,b,c)         sqlite3Fts5BufferGrow(a,b,c)
166411#define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
166412#define fts5BufferFree(a)             sqlite3Fts5BufferFree(a)
166413#define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
166414#define fts5BufferSet(a,b,c,d)        sqlite3Fts5BufferSet(a,b,c,d)
166415#define fts5BufferAppend32(a,b,c)     sqlite3Fts5BufferAppend32(a,b,c)
166416
166417/* Write and decode big-endian 32-bit integer values */
166418static void sqlite3Fts5Put32(u8*, int);
166419static int sqlite3Fts5Get32(const u8*);
166420
166421#define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
166422#define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
166423
166424typedef struct Fts5PoslistReader Fts5PoslistReader;
166425struct Fts5PoslistReader {
166426  /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
166427  const u8 *a;                    /* Position list to iterate through */
166428  int n;                          /* Size of buffer at a[] in bytes */
166429  int i;                          /* Current offset in a[] */
166430
166431  u8 bFlag;                       /* For client use (any custom purpose) */
166432
166433  /* Output variables */
166434  u8 bEof;                        /* Set to true at EOF */
166435  i64 iPos;                       /* (iCol<<32) + iPos */
166436};
166437static int sqlite3Fts5PoslistReaderInit(
166438  const u8 *a, int n,             /* Poslist buffer to iterate through */
166439  Fts5PoslistReader *pIter        /* Iterator object to initialize */
166440);
166441static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
166442
166443typedef struct Fts5PoslistWriter Fts5PoslistWriter;
166444struct Fts5PoslistWriter {
166445  i64 iPrev;
166446};
166447static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
166448
166449static int sqlite3Fts5PoslistNext64(
166450  const u8 *a, int n,             /* Buffer containing poslist */
166451  int *pi,                        /* IN/OUT: Offset within a[] */
166452  i64 *piOff                      /* IN/OUT: Current offset */
166453);
166454
166455/* Malloc utility */
166456static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
166457static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
166458
166459/* Character set tests (like isspace(), isalpha() etc.) */
166460static int sqlite3Fts5IsBareword(char t);
166461
166462/*
166463** End of interface to code in fts5_buffer.c.
166464**************************************************************************/
166465
166466/**************************************************************************
166467** Interface to code in fts5_index.c. fts5_index.c contains contains code
166468** to access the data stored in the %_data table.
166469*/
166470
166471typedef struct Fts5Index Fts5Index;
166472typedef struct Fts5IndexIter Fts5IndexIter;
166473
166474/*
166475** Values used as part of the flags argument passed to IndexQuery().
166476*/
166477#define FTS5INDEX_QUERY_PREFIX     0x0001   /* Prefix query */
166478#define FTS5INDEX_QUERY_DESC       0x0002   /* Docs in descending rowid order */
166479#define FTS5INDEX_QUERY_TEST_NOIDX 0x0004   /* Do not use prefix index */
166480#define FTS5INDEX_QUERY_SCAN       0x0008   /* Scan query (fts5vocab) */
166481
166482/*
166483** Create/destroy an Fts5Index object.
166484*/
166485static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
166486static int sqlite3Fts5IndexClose(Fts5Index *p);
166487
166488/*
166489** for(
166490**   sqlite3Fts5IndexQuery(p, "token", 5, 0, 0, &pIter);
166491**   0==sqlite3Fts5IterEof(pIter);
166492**   sqlite3Fts5IterNext(pIter)
166493** ){
166494**   i64 iRowid = sqlite3Fts5IterRowid(pIter);
166495** }
166496*/
166497
166498/*
166499** Open a new iterator to iterate though all rowids that match the
166500** specified token or token prefix.
166501*/
166502static int sqlite3Fts5IndexQuery(
166503  Fts5Index *p,                   /* FTS index to query */
166504  const char *pToken, int nToken, /* Token (or prefix) to query for */
166505  int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
166506  Fts5Colset *pColset,            /* Match these columns only */
166507  Fts5IndexIter **ppIter          /* OUT: New iterator object */
166508);
166509
166510/*
166511** The various operations on open token or token prefix iterators opened
166512** using sqlite3Fts5IndexQuery().
166513*/
166514static int sqlite3Fts5IterEof(Fts5IndexIter*);
166515static int sqlite3Fts5IterNext(Fts5IndexIter*);
166516static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
166517static i64 sqlite3Fts5IterRowid(Fts5IndexIter*);
166518static int sqlite3Fts5IterPoslist(Fts5IndexIter*,Fts5Colset*, const u8**, int*, i64*);
166519static int sqlite3Fts5IterPoslistBuffer(Fts5IndexIter *pIter, Fts5Buffer *pBuf);
166520
166521/*
166522** Close an iterator opened by sqlite3Fts5IndexQuery().
166523*/
166524static void sqlite3Fts5IterClose(Fts5IndexIter*);
166525
166526/*
166527** This interface is used by the fts5vocab module.
166528*/
166529static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
166530static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
166531
166532
166533/*
166534** Insert or remove data to or from the index. Each time a document is
166535** added to or removed from the index, this function is called one or more
166536** times.
166537**
166538** For an insert, it must be called once for each token in the new document.
166539** If the operation is a delete, it must be called (at least) once for each
166540** unique token in the document with an iCol value less than zero. The iPos
166541** argument is ignored for a delete.
166542*/
166543static int sqlite3Fts5IndexWrite(
166544  Fts5Index *p,                   /* Index to write to */
166545  int iCol,                       /* Column token appears in (-ve -> delete) */
166546  int iPos,                       /* Position of token within column */
166547  const char *pToken, int nToken  /* Token to add or remove to or from index */
166548);
166549
166550/*
166551** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
166552** document iDocid.
166553*/
166554static int sqlite3Fts5IndexBeginWrite(
166555  Fts5Index *p,                   /* Index to write to */
166556  int bDelete,                    /* True if current operation is a delete */
166557  i64 iDocid                      /* Docid to add or remove data from */
166558);
166559
166560/*
166561** Flush any data stored in the in-memory hash tables to the database.
166562** If the bCommit flag is true, also close any open blob handles.
166563*/
166564static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit);
166565
166566/*
166567** Discard any data stored in the in-memory hash tables. Do not write it
166568** to the database. Additionally, assume that the contents of the %_data
166569** table may have changed on disk. So any in-memory caches of %_data
166570** records must be invalidated.
166571*/
166572static int sqlite3Fts5IndexRollback(Fts5Index *p);
166573
166574/*
166575** Get or set the "averages" values.
166576*/
166577static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
166578static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
166579
166580/*
166581** Functions called by the storage module as part of integrity-check.
166582*/
166583static u64 sqlite3Fts5IndexCksum(Fts5Config*,i64,int,int,const char*,int);
166584static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
166585
166586/*
166587** Called during virtual module initialization to register UDF
166588** fts5_decode() with SQLite
166589*/
166590static int sqlite3Fts5IndexInit(sqlite3*);
166591
166592static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
166593
166594/*
166595** Return the total number of entries read from the %_data table by
166596** this connection since it was created.
166597*/
166598static int sqlite3Fts5IndexReads(Fts5Index *p);
166599
166600static int sqlite3Fts5IndexReinit(Fts5Index *p);
166601static int sqlite3Fts5IndexOptimize(Fts5Index *p);
166602static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
166603
166604static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
166605
166606/*
166607** End of interface to code in fts5_index.c.
166608**************************************************************************/
166609
166610/**************************************************************************
166611** Interface to code in fts5_varint.c.
166612*/
166613static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
166614static int sqlite3Fts5GetVarintLen(u32 iVal);
166615static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
166616static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
166617
166618#define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
166619#define fts5GetVarint    sqlite3Fts5GetVarint
166620
166621#define fts5FastGetVarint32(a, iOff, nVal) {      \
166622  nVal = (a)[iOff++];                             \
166623  if( nVal & 0x80 ){                              \
166624    iOff--;                                       \
166625    iOff += fts5GetVarint32(&(a)[iOff], nVal);    \
166626  }                                               \
166627}
166628
166629
166630/*
166631** End of interface to code in fts5_varint.c.
166632**************************************************************************/
166633
166634
166635/**************************************************************************
166636** Interface to code in fts5.c.
166637*/
166638
166639static int sqlite3Fts5GetTokenizer(
166640  Fts5Global*,
166641  const char **azArg,
166642  int nArg,
166643  Fts5Tokenizer**,
166644  fts5_tokenizer**,
166645  char **pzErr
166646);
166647
166648static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, int*);
166649
166650/*
166651** End of interface to code in fts5.c.
166652**************************************************************************/
166653
166654/**************************************************************************
166655** Interface to code in fts5_hash.c.
166656*/
166657typedef struct Fts5Hash Fts5Hash;
166658
166659/*
166660** Create a hash table, free a hash table.
166661*/
166662static int sqlite3Fts5HashNew(Fts5Hash**, int *pnSize);
166663static void sqlite3Fts5HashFree(Fts5Hash*);
166664
166665static int sqlite3Fts5HashWrite(
166666  Fts5Hash*,
166667  i64 iRowid,                     /* Rowid for this entry */
166668  int iCol,                       /* Column token appears in (-ve -> delete) */
166669  int iPos,                       /* Position of token within column */
166670  char bByte,
166671  const char *pToken, int nToken  /* Token to add or remove to or from index */
166672);
166673
166674/*
166675** Empty (but do not delete) a hash table.
166676*/
166677static void sqlite3Fts5HashClear(Fts5Hash*);
166678
166679static int sqlite3Fts5HashQuery(
166680  Fts5Hash*,                      /* Hash table to query */
166681  const char *pTerm, int nTerm,   /* Query term */
166682  const u8 **ppDoclist,           /* OUT: Pointer to doclist for pTerm */
166683  int *pnDoclist                  /* OUT: Size of doclist in bytes */
166684);
166685
166686static int sqlite3Fts5HashScanInit(
166687  Fts5Hash*,                      /* Hash table to query */
166688  const char *pTerm, int nTerm    /* Query prefix */
166689);
166690static void sqlite3Fts5HashScanNext(Fts5Hash*);
166691static int sqlite3Fts5HashScanEof(Fts5Hash*);
166692static void sqlite3Fts5HashScanEntry(Fts5Hash *,
166693  const char **pzTerm,            /* OUT: term (nul-terminated) */
166694  const u8 **ppDoclist,           /* OUT: pointer to doclist */
166695  int *pnDoclist                  /* OUT: size of doclist in bytes */
166696);
166697
166698
166699/*
166700** End of interface to code in fts5_hash.c.
166701**************************************************************************/
166702
166703/**************************************************************************
166704** Interface to code in fts5_storage.c. fts5_storage.c contains contains
166705** code to access the data stored in the %_content and %_docsize tables.
166706*/
166707
166708#define FTS5_STMT_SCAN_ASC  0     /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
166709#define FTS5_STMT_SCAN_DESC 1     /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
166710#define FTS5_STMT_LOOKUP    2     /* SELECT rowid, * FROM ... WHERE rowid=? */
166711
166712typedef struct Fts5Storage Fts5Storage;
166713
166714static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
166715static int sqlite3Fts5StorageClose(Fts5Storage *p);
166716static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
166717
166718static int sqlite3Fts5DropAll(Fts5Config*);
166719static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
166720
166721static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64);
166722static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
166723static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
166724
166725static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
166726
166727static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
166728static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
166729
166730static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
166731static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
166732static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
166733
166734static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit);
166735static int sqlite3Fts5StorageRollback(Fts5Storage *p);
166736
166737static int sqlite3Fts5StorageConfigValue(
166738    Fts5Storage *p, const char*, sqlite3_value*, int
166739);
166740
166741static int sqlite3Fts5StorageSpecialDelete(Fts5Storage *p, i64 iDel, sqlite3_value**);
166742
166743static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
166744static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
166745static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
166746static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
166747
166748/*
166749** End of interface to code in fts5_storage.c.
166750**************************************************************************/
166751
166752
166753/**************************************************************************
166754** Interface to code in fts5_expr.c.
166755*/
166756typedef struct Fts5Expr Fts5Expr;
166757typedef struct Fts5ExprNode Fts5ExprNode;
166758typedef struct Fts5Parse Fts5Parse;
166759typedef struct Fts5Token Fts5Token;
166760typedef struct Fts5ExprPhrase Fts5ExprPhrase;
166761typedef struct Fts5ExprNearset Fts5ExprNearset;
166762
166763struct Fts5Token {
166764  const char *p;                  /* Token text (not NULL terminated) */
166765  int n;                          /* Size of buffer p in bytes */
166766};
166767
166768/* Parse a MATCH expression. */
166769static int sqlite3Fts5ExprNew(
166770  Fts5Config *pConfig,
166771  const char *zExpr,
166772  Fts5Expr **ppNew,
166773  char **pzErr
166774);
166775
166776/*
166777** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
166778**     rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
166779**     rc = sqlite3Fts5ExprNext(pExpr)
166780** ){
166781**   // The document with rowid iRowid matches the expression!
166782**   i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
166783** }
166784*/
166785static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
166786static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
166787static int sqlite3Fts5ExprEof(Fts5Expr*);
166788static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
166789
166790static void sqlite3Fts5ExprFree(Fts5Expr*);
166791
166792/* Called during startup to register a UDF with SQLite */
166793static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
166794
166795static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
166796static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
166797static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
166798
166799static int sqlite3Fts5ExprClonePhrase(Fts5Config*, Fts5Expr*, int, Fts5Expr**);
166800
166801/*******************************************
166802** The fts5_expr.c API above this point is used by the other hand-written
166803** C code in this module. The interfaces below this point are called by
166804** the parser code in fts5parse.y.  */
166805
166806static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
166807
166808static Fts5ExprNode *sqlite3Fts5ParseNode(
166809  Fts5Parse *pParse,
166810  int eType,
166811  Fts5ExprNode *pLeft,
166812  Fts5ExprNode *pRight,
166813  Fts5ExprNearset *pNear
166814);
166815
166816static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
166817  Fts5Parse *pParse,
166818  Fts5ExprPhrase *pPhrase,
166819  Fts5Token *pToken,
166820  int bPrefix
166821);
166822
166823static Fts5ExprNearset *sqlite3Fts5ParseNearset(
166824  Fts5Parse*,
166825  Fts5ExprNearset*,
166826  Fts5ExprPhrase*
166827);
166828
166829static Fts5Colset *sqlite3Fts5ParseColset(
166830  Fts5Parse*,
166831  Fts5Colset*,
166832  Fts5Token *
166833);
166834
166835static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
166836static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
166837static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
166838
166839static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
166840static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNearset*, Fts5Colset*);
166841static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
166842static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
166843
166844/*
166845** End of interface to code in fts5_expr.c.
166846**************************************************************************/
166847
166848
166849
166850/**************************************************************************
166851** Interface to code in fts5_aux.c.
166852*/
166853
166854static int sqlite3Fts5AuxInit(fts5_api*);
166855/*
166856** End of interface to code in fts5_aux.c.
166857**************************************************************************/
166858
166859/**************************************************************************
166860** Interface to code in fts5_tokenizer.c.
166861*/
166862
166863static int sqlite3Fts5TokenizerInit(fts5_api*);
166864/*
166865** End of interface to code in fts5_tokenizer.c.
166866**************************************************************************/
166867
166868/**************************************************************************
166869** Interface to code in fts5_vocab.c.
166870*/
166871
166872static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
166873
166874/*
166875** End of interface to code in fts5_vocab.c.
166876**************************************************************************/
166877
166878
166879/**************************************************************************
166880** Interface to automatically generated code in fts5_unicode2.c.
166881*/
166882static int sqlite3Fts5UnicodeIsalnum(int c);
166883static int sqlite3Fts5UnicodeIsdiacritic(int c);
166884static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
166885/*
166886** End of interface to code in fts5_unicode2.c.
166887**************************************************************************/
166888
166889#endif
166890
166891#define FTS5_OR                               1
166892#define FTS5_AND                              2
166893#define FTS5_NOT                              3
166894#define FTS5_TERM                             4
166895#define FTS5_COLON                            5
166896#define FTS5_LP                               6
166897#define FTS5_RP                               7
166898#define FTS5_LCP                              8
166899#define FTS5_RCP                              9
166900#define FTS5_STRING                          10
166901#define FTS5_COMMA                           11
166902#define FTS5_PLUS                            12
166903#define FTS5_STAR                            13
166904
166905/* Driver template for the LEMON parser generator.
166906** The author disclaims copyright to this source code.
166907**
166908** This version of "lempar.c" is modified, slightly, for use by SQLite.
166909** The only modifications are the addition of a couple of NEVER()
166910** macros to disable tests that are needed in the case of a general
166911** LALR(1) grammar but which are always false in the
166912** specific grammar used by SQLite.
166913*/
166914/* First off, code is included that follows the "include" declaration
166915** in the input grammar file. */
166916/* #include <stdio.h> */
166917
166918
166919/*
166920** Disable all error recovery processing in the parser push-down
166921** automaton.
166922*/
166923#define fts5YYNOERRORRECOVERY 1
166924
166925/*
166926** Make fts5yytestcase() the same as testcase()
166927*/
166928#define fts5yytestcase(X) testcase(X)
166929
166930/* Next is all token values, in a form suitable for use by makeheaders.
166931** This section will be null unless lemon is run with the -m switch.
166932*/
166933/*
166934** These constants (all generated automatically by the parser generator)
166935** specify the various kinds of tokens (terminals) that the parser
166936** understands.
166937**
166938** Each symbol here is a terminal symbol in the grammar.
166939*/
166940/* Make sure the INTERFACE macro is defined.
166941*/
166942#ifndef INTERFACE
166943# define INTERFACE 1
166944#endif
166945/* The next thing included is series of defines which control
166946** various aspects of the generated parser.
166947**    fts5YYCODETYPE         is the data type used for storing terminal
166948**                       and nonterminal numbers.  "unsigned char" is
166949**                       used if there are fewer than 250 terminals
166950**                       and nonterminals.  "int" is used otherwise.
166951**    fts5YYNOCODE           is a number of type fts5YYCODETYPE which corresponds
166952**                       to no legal terminal or nonterminal number.  This
166953**                       number is used to fill in empty slots of the hash
166954**                       table.
166955**    fts5YYFALLBACK         If defined, this indicates that one or more tokens
166956**                       have fall-back values which should be used if the
166957**                       original value of the token will not parse.
166958**    fts5YYACTIONTYPE       is the data type used for storing terminal
166959**                       and nonterminal numbers.  "unsigned char" is
166960**                       used if there are fewer than 250 rules and
166961**                       states combined.  "int" is used otherwise.
166962**    sqlite3Fts5ParserFTS5TOKENTYPE     is the data type used for minor tokens given
166963**                       directly to the parser from the tokenizer.
166964**    fts5YYMINORTYPE        is the data type used for all minor tokens.
166965**                       This is typically a union of many types, one of
166966**                       which is sqlite3Fts5ParserFTS5TOKENTYPE.  The entry in the union
166967**                       for base tokens is called "fts5yy0".
166968**    fts5YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
166969**                       zero the stack is dynamically sized using realloc()
166970**    sqlite3Fts5ParserARG_SDECL     A static variable declaration for the %extra_argument
166971**    sqlite3Fts5ParserARG_PDECL     A parameter declaration for the %extra_argument
166972**    sqlite3Fts5ParserARG_STORE     Code to store %extra_argument into fts5yypParser
166973**    sqlite3Fts5ParserARG_FETCH     Code to extract %extra_argument from fts5yypParser
166974**    fts5YYERRORSYMBOL      is the code number of the error symbol.  If not
166975**                       defined, then do no error processing.
166976**    fts5YYNSTATE           the combined number of states.
166977**    fts5YYNRULE            the number of rules in the grammar
166978**    fts5YY_MAX_SHIFT       Maximum value for shift actions
166979**    fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
166980**    fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
166981**    fts5YY_MIN_REDUCE      Maximum value for reduce actions
166982**    fts5YY_ERROR_ACTION    The fts5yy_action[] code for syntax error
166983**    fts5YY_ACCEPT_ACTION   The fts5yy_action[] code for accept
166984**    fts5YY_NO_ACTION       The fts5yy_action[] code for no-op
166985*/
166986#define fts5YYCODETYPE unsigned char
166987#define fts5YYNOCODE 27
166988#define fts5YYACTIONTYPE unsigned char
166989#define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
166990typedef union {
166991  int fts5yyinit;
166992  sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
166993  Fts5Colset* fts5yy3;
166994  Fts5ExprPhrase* fts5yy11;
166995  Fts5ExprNode* fts5yy18;
166996  int fts5yy20;
166997  Fts5ExprNearset* fts5yy26;
166998} fts5YYMINORTYPE;
166999#ifndef fts5YYSTACKDEPTH
167000#define fts5YYSTACKDEPTH 100
167001#endif
167002#define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
167003#define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
167004#define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse
167005#define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse
167006#define fts5YYNSTATE             26
167007#define fts5YYNRULE              24
167008#define fts5YY_MAX_SHIFT         25
167009#define fts5YY_MIN_SHIFTREDUCE   40
167010#define fts5YY_MAX_SHIFTREDUCE   63
167011#define fts5YY_MIN_REDUCE        64
167012#define fts5YY_MAX_REDUCE        87
167013#define fts5YY_ERROR_ACTION      88
167014#define fts5YY_ACCEPT_ACTION     89
167015#define fts5YY_NO_ACTION         90
167016
167017/* The fts5yyzerominor constant is used to initialize instances of
167018** fts5YYMINORTYPE objects to zero. */
167019static const fts5YYMINORTYPE fts5yyzerominor = { 0 };
167020
167021/* Define the fts5yytestcase() macro to be a no-op if is not already defined
167022** otherwise.
167023**
167024** Applications can choose to define fts5yytestcase() in the %include section
167025** to a macro that can assist in verifying code coverage.  For production
167026** code the fts5yytestcase() macro should be turned off.  But it is useful
167027** for testing.
167028*/
167029#ifndef fts5yytestcase
167030# define fts5yytestcase(X)
167031#endif
167032
167033
167034/* Next are the tables used to determine what action to take based on the
167035** current state and lookahead token.  These tables are used to implement
167036** functions that take a state number and lookahead value and return an
167037** action integer.
167038**
167039** Suppose the action integer is N.  Then the action is determined as
167040** follows
167041**
167042**   0 <= N <= fts5YY_MAX_SHIFT             Shift N.  That is, push the lookahead
167043**                                      token onto the stack and goto state N.
167044**
167045**   N between fts5YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
167046**     and fts5YY_MAX_SHIFTREDUCE           reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
167047**
167048**   N between fts5YY_MIN_REDUCE            Reduce by rule N-fts5YY_MIN_REDUCE
167049**     and fts5YY_MAX_REDUCE
167050
167051**   N == fts5YY_ERROR_ACTION               A syntax error has occurred.
167052**
167053**   N == fts5YY_ACCEPT_ACTION              The parser accepts its input.
167054**
167055**   N == fts5YY_NO_ACTION                  No such action.  Denotes unused
167056**                                      slots in the fts5yy_action[] table.
167057**
167058** The action table is constructed as a single large table named fts5yy_action[].
167059** Given state S and lookahead X, the action is computed as
167060**
167061**      fts5yy_action[ fts5yy_shift_ofst[S] + X ]
167062**
167063** If the index value fts5yy_shift_ofst[S]+X is out of range or if the value
167064** fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X or if fts5yy_shift_ofst[S]
167065** is equal to fts5YY_SHIFT_USE_DFLT, it means that the action is not in the table
167066** and that fts5yy_default[S] should be used instead.
167067**
167068** The formula above is for computing the action when the lookahead is
167069** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
167070** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
167071** the fts5yy_shift_ofst[] array and fts5YY_REDUCE_USE_DFLT is used in place of
167072** fts5YY_SHIFT_USE_DFLT.
167073**
167074** The following are the tables generated in this section:
167075**
167076**  fts5yy_action[]        A single table containing all actions.
167077**  fts5yy_lookahead[]     A table containing the lookahead for each entry in
167078**                     fts5yy_action.  Used to detect hash collisions.
167079**  fts5yy_shift_ofst[]    For each state, the offset into fts5yy_action for
167080**                     shifting terminals.
167081**  fts5yy_reduce_ofst[]   For each state, the offset into fts5yy_action for
167082**                     shifting non-terminals after a reduce.
167083**  fts5yy_default[]       Default action for each state.
167084*/
167085#define fts5YY_ACTTAB_COUNT (78)
167086static const fts5YYACTIONTYPE fts5yy_action[] = {
167087 /*     0 */    89,   15,   46,    5,   48,   24,   12,   19,   23,   14,
167088 /*    10 */    46,    5,   48,   24,   20,   21,   23,   43,   46,    5,
167089 /*    20 */    48,   24,    6,   18,   23,   17,   46,    5,   48,   24,
167090 /*    30 */    75,    7,   23,   25,   46,    5,   48,   24,   62,   47,
167091 /*    40 */    23,   48,   24,    7,   11,   23,    9,    3,    4,    2,
167092 /*    50 */    62,   50,   52,   44,   64,    3,    4,    2,   49,    4,
167093 /*    60 */     2,    1,   23,   11,   16,    9,   12,    2,   10,   61,
167094 /*    70 */    53,   59,   62,   60,   22,   13,   55,    8,
167095};
167096static const fts5YYCODETYPE fts5yy_lookahead[] = {
167097 /*     0 */    15,   16,   17,   18,   19,   20,   10,   11,   23,   16,
167098 /*    10 */    17,   18,   19,   20,   23,   24,   23,   16,   17,   18,
167099 /*    20 */    19,   20,   22,   23,   23,   16,   17,   18,   19,   20,
167100 /*    30 */     5,    6,   23,   16,   17,   18,   19,   20,   13,   17,
167101 /*    40 */    23,   19,   20,    6,    8,   23,   10,    1,    2,    3,
167102 /*    50 */    13,    9,   10,    7,    0,    1,    2,    3,   19,    2,
167103 /*    60 */     3,    6,   23,    8,   21,   10,   10,    3,   10,   25,
167104 /*    70 */    10,   10,   13,   25,   12,   10,    7,    5,
167105};
167106#define fts5YY_SHIFT_USE_DFLT (-5)
167107#define fts5YY_SHIFT_COUNT (25)
167108#define fts5YY_SHIFT_MIN   (-4)
167109#define fts5YY_SHIFT_MAX   (72)
167110static const signed char fts5yy_shift_ofst[] = {
167111 /*     0 */    55,   55,   55,   55,   55,   36,   -4,   56,   58,   25,
167112 /*    10 */    37,   60,   59,   59,   46,   54,   42,   57,   62,   61,
167113 /*    20 */    62,   69,   65,   62,   72,   64,
167114};
167115#define fts5YY_REDUCE_USE_DFLT (-16)
167116#define fts5YY_REDUCE_COUNT (13)
167117#define fts5YY_REDUCE_MIN   (-15)
167118#define fts5YY_REDUCE_MAX   (48)
167119static const signed char fts5yy_reduce_ofst[] = {
167120 /*     0 */   -15,   -7,    1,    9,   17,   22,   -9,    0,   39,   44,
167121 /*    10 */    44,   43,   44,   48,
167122};
167123static const fts5YYACTIONTYPE fts5yy_default[] = {
167124 /*     0 */    88,   88,   88,   88,   88,   69,   82,   88,   88,   87,
167125 /*    10 */    87,   88,   87,   87,   88,   88,   88,   66,   80,   88,
167126 /*    20 */    81,   88,   88,   78,   88,   65,
167127};
167128
167129/* The next table maps tokens into fallback tokens.  If a construct
167130** like the following:
167131**
167132**      %fallback ID X Y Z.
167133**
167134** appears in the grammar, then ID becomes a fallback token for X, Y,
167135** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
167136** but it does not parse, the type of the token is changed to ID and
167137** the parse is retried before an error is thrown.
167138*/
167139#ifdef fts5YYFALLBACK
167140static const fts5YYCODETYPE fts5yyFallback[] = {
167141};
167142#endif /* fts5YYFALLBACK */
167143
167144/* The following structure represents a single element of the
167145** parser's stack.  Information stored includes:
167146**
167147**   +  The state number for the parser at this level of the stack.
167148**
167149**   +  The value of the token stored at this level of the stack.
167150**      (In other words, the "major" token.)
167151**
167152**   +  The semantic value stored at this level of the stack.  This is
167153**      the information used by the action routines in the grammar.
167154**      It is sometimes called the "minor" token.
167155**
167156** After the "shift" half of a SHIFTREDUCE action, the stateno field
167157** actually contains the reduce action for the second half of the
167158** SHIFTREDUCE.
167159*/
167160struct fts5yyStackEntry {
167161  fts5YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
167162  fts5YYCODETYPE major;      /* The major token value.  This is the code
167163                         ** number for the token at this stack level */
167164  fts5YYMINORTYPE minor;     /* The user-supplied minor token value.  This
167165                         ** is the value of the token  */
167166};
167167typedef struct fts5yyStackEntry fts5yyStackEntry;
167168
167169/* The state of the parser is completely contained in an instance of
167170** the following structure */
167171struct fts5yyParser {
167172  int fts5yyidx;                    /* Index of top element in stack */
167173#ifdef fts5YYTRACKMAXSTACKDEPTH
167174  int fts5yyidxMax;                 /* Maximum value of fts5yyidx */
167175#endif
167176  int fts5yyerrcnt;                 /* Shifts left before out of the error */
167177  sqlite3Fts5ParserARG_SDECL                /* A place to hold %extra_argument */
167178#if fts5YYSTACKDEPTH<=0
167179  int fts5yystksz;                  /* Current side of the stack */
167180  fts5yyStackEntry *fts5yystack;        /* The parser's stack */
167181#else
167182  fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH];  /* The parser's stack */
167183#endif
167184};
167185typedef struct fts5yyParser fts5yyParser;
167186
167187#ifndef NDEBUG
167188/* #include <stdio.h> */
167189static FILE *fts5yyTraceFILE = 0;
167190static char *fts5yyTracePrompt = 0;
167191#endif /* NDEBUG */
167192
167193#ifndef NDEBUG
167194/*
167195** Turn parser tracing on by giving a stream to which to write the trace
167196** and a prompt to preface each trace message.  Tracing is turned off
167197** by making either argument NULL
167198**
167199** Inputs:
167200** <ul>
167201** <li> A FILE* to which trace output should be written.
167202**      If NULL, then tracing is turned off.
167203** <li> A prefix string written at the beginning of every
167204**      line of trace output.  If NULL, then tracing is
167205**      turned off.
167206** </ul>
167207**
167208** Outputs:
167209** None.
167210*/
167211static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
167212  fts5yyTraceFILE = TraceFILE;
167213  fts5yyTracePrompt = zTracePrompt;
167214  if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
167215  else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
167216}
167217#endif /* NDEBUG */
167218
167219#ifndef NDEBUG
167220/* For tracing shifts, the names of all terminals and nonterminals
167221** are required.  The following table supplies these names */
167222static const char *const fts5yyTokenName[] = {
167223  "$",             "OR",            "AND",           "NOT",
167224  "TERM",          "COLON",         "LP",            "RP",
167225  "LCP",           "RCP",           "STRING",        "COMMA",
167226  "PLUS",          "STAR",          "error",         "input",
167227  "expr",          "cnearset",      "exprlist",      "nearset",
167228  "colset",        "colsetlist",    "nearphrases",   "phrase",
167229  "neardist_opt",  "star_opt",
167230};
167231#endif /* NDEBUG */
167232
167233#ifndef NDEBUG
167234/* For tracing reduce actions, the names of all rules are required.
167235*/
167236static const char *const fts5yyRuleName[] = {
167237 /*   0 */ "input ::= expr",
167238 /*   1 */ "expr ::= expr AND expr",
167239 /*   2 */ "expr ::= expr OR expr",
167240 /*   3 */ "expr ::= expr NOT expr",
167241 /*   4 */ "expr ::= LP expr RP",
167242 /*   5 */ "expr ::= exprlist",
167243 /*   6 */ "exprlist ::= cnearset",
167244 /*   7 */ "exprlist ::= exprlist cnearset",
167245 /*   8 */ "cnearset ::= nearset",
167246 /*   9 */ "cnearset ::= colset COLON nearset",
167247 /*  10 */ "colset ::= LCP colsetlist RCP",
167248 /*  11 */ "colset ::= STRING",
167249 /*  12 */ "colsetlist ::= colsetlist STRING",
167250 /*  13 */ "colsetlist ::= STRING",
167251 /*  14 */ "nearset ::= phrase",
167252 /*  15 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
167253 /*  16 */ "nearphrases ::= phrase",
167254 /*  17 */ "nearphrases ::= nearphrases phrase",
167255 /*  18 */ "neardist_opt ::=",
167256 /*  19 */ "neardist_opt ::= COMMA STRING",
167257 /*  20 */ "phrase ::= phrase PLUS STRING star_opt",
167258 /*  21 */ "phrase ::= STRING star_opt",
167259 /*  22 */ "star_opt ::= STAR",
167260 /*  23 */ "star_opt ::=",
167261};
167262#endif /* NDEBUG */
167263
167264
167265#if fts5YYSTACKDEPTH<=0
167266/*
167267** Try to increase the size of the parser stack.
167268*/
167269static void fts5yyGrowStack(fts5yyParser *p){
167270  int newSize;
167271  fts5yyStackEntry *pNew;
167272
167273  newSize = p->fts5yystksz*2 + 100;
167274  pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
167275  if( pNew ){
167276    p->fts5yystack = pNew;
167277    p->fts5yystksz = newSize;
167278#ifndef NDEBUG
167279    if( fts5yyTraceFILE ){
167280      fprintf(fts5yyTraceFILE,"%sStack grows to %d entries!\n",
167281              fts5yyTracePrompt, p->fts5yystksz);
167282    }
167283#endif
167284  }
167285}
167286#endif
167287
167288/*
167289** This function allocates a new parser.
167290** The only argument is a pointer to a function which works like
167291** malloc.
167292**
167293** Inputs:
167294** A pointer to the function used to allocate memory.
167295**
167296** Outputs:
167297** A pointer to a parser.  This pointer is used in subsequent calls
167298** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
167299*/
167300static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64)){
167301  fts5yyParser *pParser;
167302  pParser = (fts5yyParser*)(*mallocProc)( (u64)sizeof(fts5yyParser) );
167303  if( pParser ){
167304    pParser->fts5yyidx = -1;
167305#ifdef fts5YYTRACKMAXSTACKDEPTH
167306    pParser->fts5yyidxMax = 0;
167307#endif
167308#if fts5YYSTACKDEPTH<=0
167309    pParser->fts5yystack = NULL;
167310    pParser->fts5yystksz = 0;
167311    fts5yyGrowStack(pParser);
167312#endif
167313  }
167314  return pParser;
167315}
167316
167317/* The following function deletes the value associated with a
167318** symbol.  The symbol can be either a terminal or nonterminal.
167319** "fts5yymajor" is the symbol code, and "fts5yypminor" is a pointer to
167320** the value.
167321*/
167322static void fts5yy_destructor(
167323  fts5yyParser *fts5yypParser,    /* The parser */
167324  fts5YYCODETYPE fts5yymajor,     /* Type code for object to destroy */
167325  fts5YYMINORTYPE *fts5yypminor   /* The object to be destroyed */
167326){
167327  sqlite3Fts5ParserARG_FETCH;
167328  switch( fts5yymajor ){
167329    /* Here is inserted the actions which take place when a
167330    ** terminal or non-terminal is destroyed.  This can happen
167331    ** when the symbol is popped from the stack during a
167332    ** reduce or during error processing or when a parser is
167333    ** being destroyed before it is finished parsing.
167334    **
167335    ** Note: during a reduce, the only symbols destroyed are those
167336    ** which appear on the RHS of the rule, but which are not used
167337    ** inside the C code.
167338    */
167339    case 15: /* input */
167340{
167341 (void)pParse;
167342}
167343      break;
167344    case 16: /* expr */
167345    case 17: /* cnearset */
167346    case 18: /* exprlist */
167347{
167348 sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy18));
167349}
167350      break;
167351    case 19: /* nearset */
167352    case 22: /* nearphrases */
167353{
167354 sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy26));
167355}
167356      break;
167357    case 20: /* colset */
167358    case 21: /* colsetlist */
167359{
167360 sqlite3_free((fts5yypminor->fts5yy3));
167361}
167362      break;
167363    case 23: /* phrase */
167364{
167365 sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy11));
167366}
167367      break;
167368    default:  break;   /* If no destructor action specified: do nothing */
167369  }
167370}
167371
167372/*
167373** Pop the parser's stack once.
167374**
167375** If there is a destructor routine associated with the token which
167376** is popped from the stack, then call it.
167377**
167378** Return the major token number for the symbol popped.
167379*/
167380static int fts5yy_pop_parser_stack(fts5yyParser *pParser){
167381  fts5YYCODETYPE fts5yymajor;
167382  fts5yyStackEntry *fts5yytos = &pParser->fts5yystack[pParser->fts5yyidx];
167383
167384  /* There is no mechanism by which the parser stack can be popped below
167385  ** empty in SQLite.  */
167386  assert( pParser->fts5yyidx>=0 );
167387#ifndef NDEBUG
167388  if( fts5yyTraceFILE && pParser->fts5yyidx>=0 ){
167389    fprintf(fts5yyTraceFILE,"%sPopping %s\n",
167390      fts5yyTracePrompt,
167391      fts5yyTokenName[fts5yytos->major]);
167392  }
167393#endif
167394  fts5yymajor = fts5yytos->major;
167395  fts5yy_destructor(pParser, fts5yymajor, &fts5yytos->minor);
167396  pParser->fts5yyidx--;
167397  return fts5yymajor;
167398}
167399
167400/*
167401** Deallocate and destroy a parser.  Destructors are all called for
167402** all stack elements before shutting the parser down.
167403**
167404** Inputs:
167405** <ul>
167406** <li>  A pointer to the parser.  This should be a pointer
167407**       obtained from sqlite3Fts5ParserAlloc.
167408** <li>  A pointer to a function used to reclaim memory obtained
167409**       from malloc.
167410** </ul>
167411*/
167412static void sqlite3Fts5ParserFree(
167413  void *p,                    /* The parser to be deleted */
167414  void (*freeProc)(void*)     /* Function used to reclaim memory */
167415){
167416  fts5yyParser *pParser = (fts5yyParser*)p;
167417  /* In SQLite, we never try to destroy a parser that was not successfully
167418  ** created in the first place. */
167419  if( NEVER(pParser==0) ) return;
167420  while( pParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(pParser);
167421#if fts5YYSTACKDEPTH<=0
167422  free(pParser->fts5yystack);
167423#endif
167424  (*freeProc)((void*)pParser);
167425}
167426
167427/*
167428** Return the peak depth of the stack for a parser.
167429*/
167430#ifdef fts5YYTRACKMAXSTACKDEPTH
167431static int sqlite3Fts5ParserStackPeak(void *p){
167432  fts5yyParser *pParser = (fts5yyParser*)p;
167433  return pParser->fts5yyidxMax;
167434}
167435#endif
167436
167437/*
167438** Find the appropriate action for a parser given the terminal
167439** look-ahead token iLookAhead.
167440**
167441** If the look-ahead token is fts5YYNOCODE, then check to see if the action is
167442** independent of the look-ahead.  If it is, return the action, otherwise
167443** return fts5YY_NO_ACTION.
167444*/
167445static int fts5yy_find_shift_action(
167446  fts5yyParser *pParser,        /* The parser */
167447  fts5YYCODETYPE iLookAhead     /* The look-ahead token */
167448){
167449  int i;
167450  int stateno = pParser->fts5yystack[pParser->fts5yyidx].stateno;
167451
167452  if( stateno>=fts5YY_MIN_REDUCE ) return stateno;
167453  assert( stateno <= fts5YY_SHIFT_COUNT );
167454  i = fts5yy_shift_ofst[stateno];
167455  if( i==fts5YY_SHIFT_USE_DFLT ) return fts5yy_default[stateno];
167456  assert( iLookAhead!=fts5YYNOCODE );
167457  i += iLookAhead;
167458  if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
167459    if( iLookAhead>0 ){
167460#ifdef fts5YYFALLBACK
167461      fts5YYCODETYPE iFallback;            /* Fallback token */
167462      if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
167463             && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
167464#ifndef NDEBUG
167465        if( fts5yyTraceFILE ){
167466          fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
167467             fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
167468        }
167469#endif
167470        return fts5yy_find_shift_action(pParser, iFallback);
167471      }
167472#endif
167473#ifdef fts5YYWILDCARD
167474      {
167475        int j = i - iLookAhead + fts5YYWILDCARD;
167476        if(
167477#if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
167478          j>=0 &&
167479#endif
167480#if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
167481          j<fts5YY_ACTTAB_COUNT &&
167482#endif
167483          fts5yy_lookahead[j]==fts5YYWILDCARD
167484        ){
167485#ifndef NDEBUG
167486          if( fts5yyTraceFILE ){
167487            fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
167488               fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[fts5YYWILDCARD]);
167489          }
167490#endif /* NDEBUG */
167491          return fts5yy_action[j];
167492        }
167493      }
167494#endif /* fts5YYWILDCARD */
167495    }
167496    return fts5yy_default[stateno];
167497  }else{
167498    return fts5yy_action[i];
167499  }
167500}
167501
167502/*
167503** Find the appropriate action for a parser given the non-terminal
167504** look-ahead token iLookAhead.
167505**
167506** If the look-ahead token is fts5YYNOCODE, then check to see if the action is
167507** independent of the look-ahead.  If it is, return the action, otherwise
167508** return fts5YY_NO_ACTION.
167509*/
167510static int fts5yy_find_reduce_action(
167511  int stateno,              /* Current state number */
167512  fts5YYCODETYPE iLookAhead     /* The look-ahead token */
167513){
167514  int i;
167515#ifdef fts5YYERRORSYMBOL
167516  if( stateno>fts5YY_REDUCE_COUNT ){
167517    return fts5yy_default[stateno];
167518  }
167519#else
167520  assert( stateno<=fts5YY_REDUCE_COUNT );
167521#endif
167522  i = fts5yy_reduce_ofst[stateno];
167523  assert( i!=fts5YY_REDUCE_USE_DFLT );
167524  assert( iLookAhead!=fts5YYNOCODE );
167525  i += iLookAhead;
167526#ifdef fts5YYERRORSYMBOL
167527  if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
167528    return fts5yy_default[stateno];
167529  }
167530#else
167531  assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
167532  assert( fts5yy_lookahead[i]==iLookAhead );
167533#endif
167534  return fts5yy_action[i];
167535}
167536
167537/*
167538** The following routine is called if the stack overflows.
167539*/
167540static void fts5yyStackOverflow(fts5yyParser *fts5yypParser, fts5YYMINORTYPE *fts5yypMinor){
167541   sqlite3Fts5ParserARG_FETCH;
167542   fts5yypParser->fts5yyidx--;
167543#ifndef NDEBUG
167544   if( fts5yyTraceFILE ){
167545     fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
167546   }
167547#endif
167548   while( fts5yypParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(fts5yypParser);
167549   /* Here code is inserted which will execute if the parser
167550   ** stack every overflows */
167551
167552  assert( 0 );
167553   sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
167554}
167555
167556/*
167557** Print tracing information for a SHIFT action
167558*/
167559#ifndef NDEBUG
167560static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState){
167561  if( fts5yyTraceFILE ){
167562    int i;
167563    if( fts5yyNewState<fts5YYNSTATE ){
167564      fprintf(fts5yyTraceFILE,"%sShift %d\n",fts5yyTracePrompt,fts5yyNewState);
167565      fprintf(fts5yyTraceFILE,"%sStack:",fts5yyTracePrompt);
167566      for(i=1; i<=fts5yypParser->fts5yyidx; i++)
167567        fprintf(fts5yyTraceFILE," %s",fts5yyTokenName[fts5yypParser->fts5yystack[i].major]);
167568      fprintf(fts5yyTraceFILE,"\n");
167569    }else{
167570      fprintf(fts5yyTraceFILE,"%sShift *\n",fts5yyTracePrompt);
167571    }
167572  }
167573}
167574#else
167575# define fts5yyTraceShift(X,Y)
167576#endif
167577
167578/*
167579** Perform a shift action.  Return the number of errors.
167580*/
167581static void fts5yy_shift(
167582  fts5yyParser *fts5yypParser,          /* The parser to be shifted */
167583  int fts5yyNewState,               /* The new state to shift in */
167584  int fts5yyMajor,                  /* The major token to shift in */
167585  fts5YYMINORTYPE *fts5yypMinor         /* Pointer to the minor token to shift in */
167586){
167587  fts5yyStackEntry *fts5yytos;
167588  fts5yypParser->fts5yyidx++;
167589#ifdef fts5YYTRACKMAXSTACKDEPTH
167590  if( fts5yypParser->fts5yyidx>fts5yypParser->fts5yyidxMax ){
167591    fts5yypParser->fts5yyidxMax = fts5yypParser->fts5yyidx;
167592  }
167593#endif
167594#if fts5YYSTACKDEPTH>0
167595  if( fts5yypParser->fts5yyidx>=fts5YYSTACKDEPTH ){
167596    fts5yyStackOverflow(fts5yypParser, fts5yypMinor);
167597    return;
167598  }
167599#else
167600  if( fts5yypParser->fts5yyidx>=fts5yypParser->fts5yystksz ){
167601    fts5yyGrowStack(fts5yypParser);
167602    if( fts5yypParser->fts5yyidx>=fts5yypParser->fts5yystksz ){
167603      fts5yyStackOverflow(fts5yypParser, fts5yypMinor);
167604      return;
167605    }
167606  }
167607#endif
167608  fts5yytos = &fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx];
167609  fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState;
167610  fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor;
167611  fts5yytos->minor = *fts5yypMinor;
167612  fts5yyTraceShift(fts5yypParser, fts5yyNewState);
167613}
167614
167615/* The following table contains information about every rule that
167616** is used during the reduce.
167617*/
167618static const struct {
167619  fts5YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
167620  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
167621} fts5yyRuleInfo[] = {
167622  { 15, 1 },
167623  { 16, 3 },
167624  { 16, 3 },
167625  { 16, 3 },
167626  { 16, 3 },
167627  { 16, 1 },
167628  { 18, 1 },
167629  { 18, 2 },
167630  { 17, 1 },
167631  { 17, 3 },
167632  { 20, 3 },
167633  { 20, 1 },
167634  { 21, 2 },
167635  { 21, 1 },
167636  { 19, 1 },
167637  { 19, 5 },
167638  { 22, 1 },
167639  { 22, 2 },
167640  { 24, 0 },
167641  { 24, 2 },
167642  { 23, 4 },
167643  { 23, 2 },
167644  { 25, 1 },
167645  { 25, 0 },
167646};
167647
167648static void fts5yy_accept(fts5yyParser*);  /* Forward Declaration */
167649
167650/*
167651** Perform a reduce action and the shift that must immediately
167652** follow the reduce.
167653*/
167654static void fts5yy_reduce(
167655  fts5yyParser *fts5yypParser,         /* The parser */
167656  int fts5yyruleno                 /* Number of the rule by which to reduce */
167657){
167658  int fts5yygoto;                     /* The next state */
167659  int fts5yyact;                      /* The next action */
167660  fts5YYMINORTYPE fts5yygotominor;        /* The LHS of the rule reduced */
167661  fts5yyStackEntry *fts5yymsp;            /* The top of the parser's stack */
167662  int fts5yysize;                     /* Amount to pop the stack */
167663  sqlite3Fts5ParserARG_FETCH;
167664  fts5yymsp = &fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx];
167665#ifndef NDEBUG
167666  if( fts5yyTraceFILE && fts5yyruleno>=0
167667        && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
167668    fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
167669    fprintf(fts5yyTraceFILE, "%sReduce [%s] -> state %d.\n", fts5yyTracePrompt,
167670      fts5yyRuleName[fts5yyruleno], fts5yymsp[-fts5yysize].stateno);
167671  }
167672#endif /* NDEBUG */
167673
167674  /* Silence complaints from purify about fts5yygotominor being uninitialized
167675  ** in some cases when it is copied into the stack after the following
167676  ** switch.  fts5yygotominor is uninitialized when a rule reduces that does
167677  ** not set the value of its left-hand side nonterminal.  Leaving the
167678  ** value of the nonterminal uninitialized is utterly harmless as long
167679  ** as the value is never used.  So really the only thing this code
167680  ** accomplishes is to quieten purify.
167681  **
167682  ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
167683  ** without this code, their parser segfaults.  I'm not sure what there
167684  ** parser is doing to make this happen.  This is the second bug report
167685  ** from wireshark this week.  Clearly they are stressing Lemon in ways
167686  ** that it has not been previously stressed...  (SQLite ticket #2172)
167687  */
167688  /*memset(&fts5yygotominor, 0, sizeof(fts5yygotominor));*/
167689  fts5yygotominor = fts5yyzerominor;
167690
167691
167692  switch( fts5yyruleno ){
167693  /* Beginning here are the reduction cases.  A typical example
167694  ** follows:
167695  **   case 0:
167696  **  #line <lineno> <grammarfile>
167697  **     { ... }           // User supplied code
167698  **  #line <lineno> <thisfile>
167699  **     break;
167700  */
167701      case 0: /* input ::= expr */
167702{ sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy18); }
167703        break;
167704      case 1: /* expr ::= expr AND expr */
167705{
167706  fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
167707}
167708        break;
167709      case 2: /* expr ::= expr OR expr */
167710{
167711  fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
167712}
167713        break;
167714      case 3: /* expr ::= expr NOT expr */
167715{
167716  fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
167717}
167718        break;
167719      case 4: /* expr ::= LP expr RP */
167720{fts5yygotominor.fts5yy18 = fts5yymsp[-1].minor.fts5yy18;}
167721        break;
167722      case 5: /* expr ::= exprlist */
167723      case 6: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==6);
167724{fts5yygotominor.fts5yy18 = fts5yymsp[0].minor.fts5yy18;}
167725        break;
167726      case 7: /* exprlist ::= exprlist cnearset */
167727{
167728  fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-1].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
167729}
167730        break;
167731      case 8: /* cnearset ::= nearset */
167732{
167733  fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy26);
167734}
167735        break;
167736      case 9: /* cnearset ::= colset COLON nearset */
167737{
167738  sqlite3Fts5ParseSetColset(pParse, fts5yymsp[0].minor.fts5yy26, fts5yymsp[-2].minor.fts5yy3);
167739  fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy26);
167740}
167741        break;
167742      case 10: /* colset ::= LCP colsetlist RCP */
167743{ fts5yygotominor.fts5yy3 = fts5yymsp[-1].minor.fts5yy3; }
167744        break;
167745      case 11: /* colset ::= STRING */
167746{
167747  fts5yygotominor.fts5yy3 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
167748}
167749        break;
167750      case 12: /* colsetlist ::= colsetlist STRING */
167751{
167752  fts5yygotominor.fts5yy3 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy3, &fts5yymsp[0].minor.fts5yy0); }
167753        break;
167754      case 13: /* colsetlist ::= STRING */
167755{
167756  fts5yygotominor.fts5yy3 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
167757}
167758        break;
167759      case 14: /* nearset ::= phrase */
167760{ fts5yygotominor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11); }
167761        break;
167762      case 15: /* nearset ::= STRING LP nearphrases neardist_opt RP */
167763{
167764  sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
167765  sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy26, &fts5yymsp[-1].minor.fts5yy0);
167766  fts5yygotominor.fts5yy26 = fts5yymsp[-2].minor.fts5yy26;
167767}
167768        break;
167769      case 16: /* nearphrases ::= phrase */
167770{
167771  fts5yygotominor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11);
167772}
167773        break;
167774      case 17: /* nearphrases ::= nearphrases phrase */
167775{
167776  fts5yygotominor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy26, fts5yymsp[0].minor.fts5yy11);
167777}
167778        break;
167779      case 18: /* neardist_opt ::= */
167780{ fts5yygotominor.fts5yy0.p = 0; fts5yygotominor.fts5yy0.n = 0; }
167781        break;
167782      case 19: /* neardist_opt ::= COMMA STRING */
167783{ fts5yygotominor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
167784        break;
167785      case 20: /* phrase ::= phrase PLUS STRING star_opt */
167786{
167787  fts5yygotominor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy11, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy20);
167788}
167789        break;
167790      case 21: /* phrase ::= STRING star_opt */
167791{
167792  fts5yygotominor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy20);
167793}
167794        break;
167795      case 22: /* star_opt ::= STAR */
167796{ fts5yygotominor.fts5yy20 = 1; }
167797        break;
167798      case 23: /* star_opt ::= */
167799{ fts5yygotominor.fts5yy20 = 0; }
167800        break;
167801      default:
167802        break;
167803  };
167804  assert( fts5yyruleno>=0 && fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
167805  fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
167806  fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
167807  fts5yypParser->fts5yyidx -= fts5yysize;
167808  fts5yyact = fts5yy_find_reduce_action(fts5yymsp[-fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
167809  if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
167810    if( fts5yyact>fts5YY_MAX_SHIFT ) fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
167811    /* If the reduce action popped at least
167812    ** one element off the stack, then we can push the new element back
167813    ** onto the stack here, and skip the stack overflow test in fts5yy_shift().
167814    ** That gives a significant speed improvement. */
167815    if( fts5yysize ){
167816      fts5yypParser->fts5yyidx++;
167817      fts5yymsp -= fts5yysize-1;
167818      fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
167819      fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
167820      fts5yymsp->minor = fts5yygotominor;
167821      fts5yyTraceShift(fts5yypParser, fts5yyact);
167822    }else{
167823      fts5yy_shift(fts5yypParser,fts5yyact,fts5yygoto,&fts5yygotominor);
167824    }
167825  }else{
167826    assert( fts5yyact == fts5YY_ACCEPT_ACTION );
167827    fts5yy_accept(fts5yypParser);
167828  }
167829}
167830
167831/*
167832** The following code executes when the parse fails
167833*/
167834#ifndef fts5YYNOERRORRECOVERY
167835static void fts5yy_parse_failed(
167836  fts5yyParser *fts5yypParser           /* The parser */
167837){
167838  sqlite3Fts5ParserARG_FETCH;
167839#ifndef NDEBUG
167840  if( fts5yyTraceFILE ){
167841    fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
167842  }
167843#endif
167844  while( fts5yypParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(fts5yypParser);
167845  /* Here code is inserted which will be executed whenever the
167846  ** parser fails */
167847  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
167848}
167849#endif /* fts5YYNOERRORRECOVERY */
167850
167851/*
167852** The following code executes when a syntax error first occurs.
167853*/
167854static void fts5yy_syntax_error(
167855  fts5yyParser *fts5yypParser,           /* The parser */
167856  int fts5yymajor,                   /* The major type of the error token */
167857  fts5YYMINORTYPE fts5yyminor            /* The minor type of the error token */
167858){
167859  sqlite3Fts5ParserARG_FETCH;
167860#define FTS5TOKEN (fts5yyminor.fts5yy0)
167861
167862  sqlite3Fts5ParseError(
167863    pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
167864  );
167865  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
167866}
167867
167868/*
167869** The following is executed when the parser accepts
167870*/
167871static void fts5yy_accept(
167872  fts5yyParser *fts5yypParser           /* The parser */
167873){
167874  sqlite3Fts5ParserARG_FETCH;
167875#ifndef NDEBUG
167876  if( fts5yyTraceFILE ){
167877    fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
167878  }
167879#endif
167880  while( fts5yypParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(fts5yypParser);
167881  /* Here code is inserted which will be executed whenever the
167882  ** parser accepts */
167883  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
167884}
167885
167886/* The main parser program.
167887** The first argument is a pointer to a structure obtained from
167888** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
167889** The second argument is the major token number.  The third is
167890** the minor token.  The fourth optional argument is whatever the
167891** user wants (and specified in the grammar) and is available for
167892** use by the action routines.
167893**
167894** Inputs:
167895** <ul>
167896** <li> A pointer to the parser (an opaque structure.)
167897** <li> The major token number.
167898** <li> The minor token number.
167899** <li> An option argument of a grammar-specified type.
167900** </ul>
167901**
167902** Outputs:
167903** None.
167904*/
167905static void sqlite3Fts5Parser(
167906  void *fts5yyp,                   /* The parser */
167907  int fts5yymajor,                 /* The major token code number */
167908  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor       /* The value for the token */
167909  sqlite3Fts5ParserARG_PDECL               /* Optional %extra_argument parameter */
167910){
167911  fts5YYMINORTYPE fts5yyminorunion;
167912  int fts5yyact;            /* The parser action. */
167913#if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
167914  int fts5yyendofinput;     /* True if we are at the end of input */
167915#endif
167916#ifdef fts5YYERRORSYMBOL
167917  int fts5yyerrorhit = 0;   /* True if fts5yymajor has invoked an error */
167918#endif
167919  fts5yyParser *fts5yypParser;  /* The parser */
167920
167921  /* (re)initialize the parser, if necessary */
167922  fts5yypParser = (fts5yyParser*)fts5yyp;
167923  if( fts5yypParser->fts5yyidx<0 ){
167924#if fts5YYSTACKDEPTH<=0
167925    if( fts5yypParser->fts5yystksz <=0 ){
167926      /*memset(&fts5yyminorunion, 0, sizeof(fts5yyminorunion));*/
167927      fts5yyminorunion = fts5yyzerominor;
167928      fts5yyStackOverflow(fts5yypParser, &fts5yyminorunion);
167929      return;
167930    }
167931#endif
167932    fts5yypParser->fts5yyidx = 0;
167933    fts5yypParser->fts5yyerrcnt = -1;
167934    fts5yypParser->fts5yystack[0].stateno = 0;
167935    fts5yypParser->fts5yystack[0].major = 0;
167936  }
167937  fts5yyminorunion.fts5yy0 = fts5yyminor;
167938#if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
167939  fts5yyendofinput = (fts5yymajor==0);
167940#endif
167941  sqlite3Fts5ParserARG_STORE;
167942
167943#ifndef NDEBUG
167944  if( fts5yyTraceFILE ){
167945    fprintf(fts5yyTraceFILE,"%sInput %s\n",fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
167946  }
167947#endif
167948
167949  do{
167950    fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor);
167951    if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
167952      if( fts5yyact > fts5YY_MAX_SHIFT ) fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
167953      fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,&fts5yyminorunion);
167954      fts5yypParser->fts5yyerrcnt--;
167955      fts5yymajor = fts5YYNOCODE;
167956    }else if( fts5yyact <= fts5YY_MAX_REDUCE ){
167957      fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE);
167958    }else{
167959      assert( fts5yyact == fts5YY_ERROR_ACTION );
167960#ifdef fts5YYERRORSYMBOL
167961      int fts5yymx;
167962#endif
167963#ifndef NDEBUG
167964      if( fts5yyTraceFILE ){
167965        fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
167966      }
167967#endif
167968#ifdef fts5YYERRORSYMBOL
167969      /* A syntax error has occurred.
167970      ** The response to an error depends upon whether or not the
167971      ** grammar defines an error token "ERROR".
167972      **
167973      ** This is what we do if the grammar does define ERROR:
167974      **
167975      **  * Call the %syntax_error function.
167976      **
167977      **  * Begin popping the stack until we enter a state where
167978      **    it is legal to shift the error symbol, then shift
167979      **    the error symbol.
167980      **
167981      **  * Set the error count to three.
167982      **
167983      **  * Begin accepting and shifting new tokens.  No new error
167984      **    processing will occur until three tokens have been
167985      **    shifted successfully.
167986      **
167987      */
167988      if( fts5yypParser->fts5yyerrcnt<0 ){
167989        fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminorunion);
167990      }
167991      fts5yymx = fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx].major;
167992      if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
167993#ifndef NDEBUG
167994        if( fts5yyTraceFILE ){
167995          fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
167996             fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
167997        }
167998#endif
167999        fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
168000        fts5yymajor = fts5YYNOCODE;
168001      }else{
168002         while(
168003          fts5yypParser->fts5yyidx >= 0 &&
168004          fts5yymx != fts5YYERRORSYMBOL &&
168005          (fts5yyact = fts5yy_find_reduce_action(
168006                        fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx].stateno,
168007                        fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE
168008        ){
168009          fts5yy_pop_parser_stack(fts5yypParser);
168010        }
168011        if( fts5yypParser->fts5yyidx < 0 || fts5yymajor==0 ){
168012          fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
168013          fts5yy_parse_failed(fts5yypParser);
168014          fts5yymajor = fts5YYNOCODE;
168015        }else if( fts5yymx!=fts5YYERRORSYMBOL ){
168016          fts5YYMINORTYPE u2;
168017          u2.fts5YYERRSYMDT = 0;
168018          fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,&u2);
168019        }
168020      }
168021      fts5yypParser->fts5yyerrcnt = 3;
168022      fts5yyerrorhit = 1;
168023#elif defined(fts5YYNOERRORRECOVERY)
168024      /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
168025      ** do any kind of error recovery.  Instead, simply invoke the syntax
168026      ** error routine and continue going as if nothing had happened.
168027      **
168028      ** Applications can set this macro (for example inside %include) if
168029      ** they intend to abandon the parse upon the first syntax error seen.
168030      */
168031      fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminorunion);
168032      fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
168033      fts5yymajor = fts5YYNOCODE;
168034
168035#else  /* fts5YYERRORSYMBOL is not defined */
168036      /* This is what we do if the grammar does not define ERROR:
168037      **
168038      **  * Report an error message, and throw away the input token.
168039      **
168040      **  * If the input token is $, then fail the parse.
168041      **
168042      ** As before, subsequent error messages are suppressed until
168043      ** three input tokens have been successfully shifted.
168044      */
168045      if( fts5yypParser->fts5yyerrcnt<=0 ){
168046        fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminorunion);
168047      }
168048      fts5yypParser->fts5yyerrcnt = 3;
168049      fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
168050      if( fts5yyendofinput ){
168051        fts5yy_parse_failed(fts5yypParser);
168052      }
168053      fts5yymajor = fts5YYNOCODE;
168054#endif
168055    }
168056  }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yyidx>=0 );
168057#ifndef NDEBUG
168058  if( fts5yyTraceFILE ){
168059    fprintf(fts5yyTraceFILE,"%sReturn\n",fts5yyTracePrompt);
168060  }
168061#endif
168062  return;
168063}
168064
168065/*
168066** 2014 May 31
168067**
168068** The author disclaims copyright to this source code.  In place of
168069** a legal notice, here is a blessing:
168070**
168071**    May you do good and not evil.
168072**    May you find forgiveness for yourself and forgive others.
168073**    May you share freely, never taking more than you give.
168074**
168075******************************************************************************
168076*/
168077
168078
168079#include <math.h>                 /* amalgamator: keep */
168080
168081/*
168082** Object used to iterate through all "coalesced phrase instances" in
168083** a single column of the current row. If the phrase instances in the
168084** column being considered do not overlap, this object simply iterates
168085** through them. Or, if they do overlap (share one or more tokens in
168086** common), each set of overlapping instances is treated as a single
168087** match. See documentation for the highlight() auxiliary function for
168088** details.
168089**
168090** Usage is:
168091**
168092**   for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
168093**      (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
168094**      rc = fts5CInstIterNext(&iter)
168095**   ){
168096**     printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
168097**   }
168098**
168099*/
168100typedef struct CInstIter CInstIter;
168101struct CInstIter {
168102  const Fts5ExtensionApi *pApi;   /* API offered by current FTS version */
168103  Fts5Context *pFts;              /* First arg to pass to pApi functions */
168104  int iCol;                       /* Column to search */
168105  int iInst;                      /* Next phrase instance index */
168106  int nInst;                      /* Total number of phrase instances */
168107
168108  /* Output variables */
168109  int iStart;                     /* First token in coalesced phrase instance */
168110  int iEnd;                       /* Last token in coalesced phrase instance */
168111};
168112
168113/*
168114** Advance the iterator to the next coalesced phrase instance. Return
168115** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
168116*/
168117static int fts5CInstIterNext(CInstIter *pIter){
168118  int rc = SQLITE_OK;
168119  pIter->iStart = -1;
168120  pIter->iEnd = -1;
168121
168122  while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
168123    int ip; int ic; int io;
168124    rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
168125    if( rc==SQLITE_OK ){
168126      if( ic==pIter->iCol ){
168127        int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
168128        if( pIter->iStart<0 ){
168129          pIter->iStart = io;
168130          pIter->iEnd = iEnd;
168131        }else if( io<=pIter->iEnd ){
168132          if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
168133        }else{
168134          break;
168135        }
168136      }
168137      pIter->iInst++;
168138    }
168139  }
168140
168141  return rc;
168142}
168143
168144/*
168145** Initialize the iterator object indicated by the final parameter to
168146** iterate through coalesced phrase instances in column iCol.
168147*/
168148static int fts5CInstIterInit(
168149  const Fts5ExtensionApi *pApi,
168150  Fts5Context *pFts,
168151  int iCol,
168152  CInstIter *pIter
168153){
168154  int rc;
168155
168156  memset(pIter, 0, sizeof(CInstIter));
168157  pIter->pApi = pApi;
168158  pIter->pFts = pFts;
168159  pIter->iCol = iCol;
168160  rc = pApi->xInstCount(pFts, &pIter->nInst);
168161
168162  if( rc==SQLITE_OK ){
168163    rc = fts5CInstIterNext(pIter);
168164  }
168165
168166  return rc;
168167}
168168
168169
168170
168171/*************************************************************************
168172** Start of highlight() implementation.
168173*/
168174typedef struct HighlightContext HighlightContext;
168175struct HighlightContext {
168176  CInstIter iter;                 /* Coalesced Instance Iterator */
168177  int iPos;                       /* Current token offset in zIn[] */
168178  int iRangeStart;                /* First token to include */
168179  int iRangeEnd;                  /* If non-zero, last token to include */
168180  const char *zOpen;              /* Opening highlight */
168181  const char *zClose;             /* Closing highlight */
168182  const char *zIn;                /* Input text */
168183  int nIn;                        /* Size of input text in bytes */
168184  int iOff;                       /* Current offset within zIn[] */
168185  char *zOut;                     /* Output value */
168186};
168187
168188/*
168189** Append text to the HighlightContext output string - p->zOut. Argument
168190** z points to a buffer containing n bytes of text to append. If n is
168191** negative, everything up until the first '\0' is appended to the output.
168192**
168193** If *pRc is set to any value other than SQLITE_OK when this function is
168194** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
168195** *pRc is set to an error code before returning.
168196*/
168197static void fts5HighlightAppend(
168198  int *pRc,
168199  HighlightContext *p,
168200  const char *z, int n
168201){
168202  if( *pRc==SQLITE_OK ){
168203    if( n<0 ) n = strlen(z);
168204    p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
168205    if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
168206  }
168207}
168208
168209/*
168210** Tokenizer callback used by implementation of highlight() function.
168211*/
168212static int fts5HighlightCb(
168213  void *pContext,                 /* Pointer to HighlightContext object */
168214  int tflags,                     /* Mask of FTS5_TOKEN_* flags */
168215  const char *pToken,             /* Buffer containing token */
168216  int nToken,                     /* Size of token in bytes */
168217  int iStartOff,                  /* Start offset of token */
168218  int iEndOff                     /* End offset of token */
168219){
168220  HighlightContext *p = (HighlightContext*)pContext;
168221  int rc = SQLITE_OK;
168222  int iPos;
168223
168224  if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
168225  iPos = p->iPos++;
168226
168227  if( p->iRangeEnd>0 ){
168228    if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
168229    if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
168230  }
168231
168232  if( iPos==p->iter.iStart ){
168233    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
168234    fts5HighlightAppend(&rc, p, p->zOpen, -1);
168235    p->iOff = iStartOff;
168236  }
168237
168238  if( iPos==p->iter.iEnd ){
168239    if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
168240      fts5HighlightAppend(&rc, p, p->zOpen, -1);
168241    }
168242    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
168243    fts5HighlightAppend(&rc, p, p->zClose, -1);
168244    p->iOff = iEndOff;
168245    if( rc==SQLITE_OK ){
168246      rc = fts5CInstIterNext(&p->iter);
168247    }
168248  }
168249
168250  if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
168251    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
168252    p->iOff = iEndOff;
168253    if( iPos<p->iter.iEnd ){
168254      fts5HighlightAppend(&rc, p, p->zClose, -1);
168255    }
168256  }
168257
168258  return rc;
168259}
168260
168261/*
168262** Implementation of highlight() function.
168263*/
168264static void fts5HighlightFunction(
168265  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
168266  Fts5Context *pFts,              /* First arg to pass to pApi functions */
168267  sqlite3_context *pCtx,          /* Context for returning result/error */
168268  int nVal,                       /* Number of values in apVal[] array */
168269  sqlite3_value **apVal           /* Array of trailing arguments */
168270){
168271  HighlightContext ctx;
168272  int rc;
168273  int iCol;
168274
168275  if( nVal!=3 ){
168276    const char *zErr = "wrong number of arguments to function highlight()";
168277    sqlite3_result_error(pCtx, zErr, -1);
168278    return;
168279  }
168280
168281  iCol = sqlite3_value_int(apVal[0]);
168282  memset(&ctx, 0, sizeof(HighlightContext));
168283  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
168284  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
168285  rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
168286
168287  if( ctx.zIn ){
168288    if( rc==SQLITE_OK ){
168289      rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
168290    }
168291
168292    if( rc==SQLITE_OK ){
168293      rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
168294    }
168295    fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
168296
168297    if( rc==SQLITE_OK ){
168298      sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
168299    }
168300    sqlite3_free(ctx.zOut);
168301  }
168302  if( rc!=SQLITE_OK ){
168303    sqlite3_result_error_code(pCtx, rc);
168304  }
168305}
168306/*
168307** End of highlight() implementation.
168308**************************************************************************/
168309
168310/*
168311** Implementation of snippet() function.
168312*/
168313static void fts5SnippetFunction(
168314  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
168315  Fts5Context *pFts,              /* First arg to pass to pApi functions */
168316  sqlite3_context *pCtx,          /* Context for returning result/error */
168317  int nVal,                       /* Number of values in apVal[] array */
168318  sqlite3_value **apVal           /* Array of trailing arguments */
168319){
168320  HighlightContext ctx;
168321  int rc = SQLITE_OK;             /* Return code */
168322  int iCol;                       /* 1st argument to snippet() */
168323  const char *zEllips;            /* 4th argument to snippet() */
168324  int nToken;                     /* 5th argument to snippet() */
168325  int nInst = 0;                  /* Number of instance matches this row */
168326  int i;                          /* Used to iterate through instances */
168327  int nPhrase;                    /* Number of phrases in query */
168328  unsigned char *aSeen;           /* Array of "seen instance" flags */
168329  int iBestCol;                   /* Column containing best snippet */
168330  int iBestStart = 0;             /* First token of best snippet */
168331  int iBestLast;                  /* Last token of best snippet */
168332  int nBestScore = 0;             /* Score of best snippet */
168333  int nColSize = 0;               /* Total size of iBestCol in tokens */
168334
168335  if( nVal!=5 ){
168336    const char *zErr = "wrong number of arguments to function snippet()";
168337    sqlite3_result_error(pCtx, zErr, -1);
168338    return;
168339  }
168340
168341  memset(&ctx, 0, sizeof(HighlightContext));
168342  iCol = sqlite3_value_int(apVal[0]);
168343  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
168344  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
168345  zEllips = (const char*)sqlite3_value_text(apVal[3]);
168346  nToken = sqlite3_value_int(apVal[4]);
168347  iBestLast = nToken-1;
168348
168349  iBestCol = (iCol>=0 ? iCol : 0);
168350  nPhrase = pApi->xPhraseCount(pFts);
168351  aSeen = sqlite3_malloc(nPhrase);
168352  if( aSeen==0 ){
168353    rc = SQLITE_NOMEM;
168354  }
168355
168356  if( rc==SQLITE_OK ){
168357    rc = pApi->xInstCount(pFts, &nInst);
168358  }
168359  for(i=0; rc==SQLITE_OK && i<nInst; i++){
168360    int ip, iSnippetCol, iStart;
168361    memset(aSeen, 0, nPhrase);
168362    rc = pApi->xInst(pFts, i, &ip, &iSnippetCol, &iStart);
168363    if( rc==SQLITE_OK && (iCol<0 || iSnippetCol==iCol) ){
168364      int nScore = 1000;
168365      int iLast = iStart - 1 + pApi->xPhraseSize(pFts, ip);
168366      int j;
168367      aSeen[ip] = 1;
168368
168369      for(j=i+1; rc==SQLITE_OK && j<nInst; j++){
168370        int ic; int io; int iFinal;
168371        rc = pApi->xInst(pFts, j, &ip, &ic, &io);
168372        iFinal = io + pApi->xPhraseSize(pFts, ip) - 1;
168373        if( rc==SQLITE_OK && ic==iSnippetCol && iLast<iStart+nToken ){
168374          nScore += aSeen[ip] ? 1000 : 1;
168375          aSeen[ip] = 1;
168376          if( iFinal>iLast ) iLast = iFinal;
168377        }
168378      }
168379
168380      if( rc==SQLITE_OK && nScore>nBestScore ){
168381        iBestCol = iSnippetCol;
168382        iBestStart = iStart;
168383        iBestLast = iLast;
168384        nBestScore = nScore;
168385      }
168386    }
168387  }
168388
168389  if( rc==SQLITE_OK ){
168390    rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
168391  }
168392  if( rc==SQLITE_OK ){
168393    rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
168394  }
168395  if( ctx.zIn ){
168396    if( rc==SQLITE_OK ){
168397      rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
168398    }
168399
168400    if( (iBestStart+nToken-1)>iBestLast ){
168401      iBestStart -= (iBestStart+nToken-1-iBestLast) / 2;
168402    }
168403    if( iBestStart+nToken>nColSize ){
168404      iBestStart = nColSize - nToken;
168405    }
168406    if( iBestStart<0 ) iBestStart = 0;
168407
168408    ctx.iRangeStart = iBestStart;
168409    ctx.iRangeEnd = iBestStart + nToken - 1;
168410
168411    if( iBestStart>0 ){
168412      fts5HighlightAppend(&rc, &ctx, zEllips, -1);
168413    }
168414    if( rc==SQLITE_OK ){
168415      rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
168416    }
168417    if( ctx.iRangeEnd>=(nColSize-1) ){
168418      fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
168419    }else{
168420      fts5HighlightAppend(&rc, &ctx, zEllips, -1);
168421    }
168422
168423    if( rc==SQLITE_OK ){
168424      sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
168425    }else{
168426      sqlite3_result_error_code(pCtx, rc);
168427    }
168428    sqlite3_free(ctx.zOut);
168429  }
168430  sqlite3_free(aSeen);
168431}
168432
168433/************************************************************************/
168434
168435/*
168436** The first time the bm25() function is called for a query, an instance
168437** of the following structure is allocated and populated.
168438*/
168439typedef struct Fts5Bm25Data Fts5Bm25Data;
168440struct Fts5Bm25Data {
168441  int nPhrase;                    /* Number of phrases in query */
168442  double avgdl;                   /* Average number of tokens in each row */
168443  double *aIDF;                   /* IDF for each phrase */
168444  double *aFreq;                  /* Array used to calculate phrase freq. */
168445};
168446
168447/*
168448** Callback used by fts5Bm25GetData() to count the number of rows in the
168449** table matched by each individual phrase within the query.
168450*/
168451static int fts5CountCb(
168452  const Fts5ExtensionApi *pApi,
168453  Fts5Context *pFts,
168454  void *pUserData                 /* Pointer to sqlite3_int64 variable */
168455){
168456  sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
168457  (*pn)++;
168458  return SQLITE_OK;
168459}
168460
168461/*
168462** Set *ppData to point to the Fts5Bm25Data object for the current query.
168463** If the object has not already been allocated, allocate and populate it
168464** now.
168465*/
168466static int fts5Bm25GetData(
168467  const Fts5ExtensionApi *pApi,
168468  Fts5Context *pFts,
168469  Fts5Bm25Data **ppData           /* OUT: bm25-data object for this query */
168470){
168471  int rc = SQLITE_OK;             /* Return code */
168472  Fts5Bm25Data *p;                /* Object to return */
168473
168474  p = pApi->xGetAuxdata(pFts, 0);
168475  if( p==0 ){
168476    int nPhrase;                  /* Number of phrases in query */
168477    sqlite3_int64 nRow = 0;       /* Number of rows in table */
168478    sqlite3_int64 nToken = 0;     /* Number of tokens in table */
168479    int nByte;                    /* Bytes of space to allocate */
168480    int i;
168481
168482    /* Allocate the Fts5Bm25Data object */
168483    nPhrase = pApi->xPhraseCount(pFts);
168484    nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
168485    p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
168486    if( p==0 ){
168487      rc = SQLITE_NOMEM;
168488    }else{
168489      memset(p, 0, nByte);
168490      p->nPhrase = nPhrase;
168491      p->aIDF = (double*)&p[1];
168492      p->aFreq = &p->aIDF[nPhrase];
168493    }
168494
168495    /* Calculate the average document length for this FTS5 table */
168496    if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
168497    if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
168498    if( rc==SQLITE_OK ) p->avgdl = (double)nToken  / (double)nRow;
168499
168500    /* Calculate an IDF for each phrase in the query */
168501    for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
168502      sqlite3_int64 nHit = 0;
168503      rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
168504      if( rc==SQLITE_OK ){
168505        /* Calculate the IDF (Inverse Document Frequency) for phrase i.
168506        ** This is done using the standard BM25 formula as found on wikipedia:
168507        **
168508        **   IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
168509        **
168510        ** where "N" is the total number of documents in the set and nHit
168511        ** is the number that contain at least one instance of the phrase
168512        ** under consideration.
168513        **
168514        ** The problem with this is that if (N < 2*nHit), the IDF is
168515        ** negative. Which is undesirable. So the mimimum allowable IDF is
168516        ** (1e-6) - roughly the same as a term that appears in just over
168517        ** half of set of 5,000,000 documents.  */
168518        double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
168519        if( idf<=0.0 ) idf = 1e-6;
168520        p->aIDF[i] = idf;
168521      }
168522    }
168523
168524    if( rc!=SQLITE_OK ){
168525      sqlite3_free(p);
168526    }else{
168527      rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
168528    }
168529    if( rc!=SQLITE_OK ) p = 0;
168530  }
168531  *ppData = p;
168532  return rc;
168533}
168534
168535/*
168536** Implementation of bm25() function.
168537*/
168538static void fts5Bm25Function(
168539  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
168540  Fts5Context *pFts,              /* First arg to pass to pApi functions */
168541  sqlite3_context *pCtx,          /* Context for returning result/error */
168542  int nVal,                       /* Number of values in apVal[] array */
168543  sqlite3_value **apVal           /* Array of trailing arguments */
168544){
168545  const double k1 = 1.2;          /* Constant "k1" from BM25 formula */
168546  const double b = 0.75;          /* Constant "b" from BM25 formula */
168547  int rc = SQLITE_OK;             /* Error code */
168548  double score = 0.0;             /* SQL function return value */
168549  Fts5Bm25Data *pData;            /* Values allocated/calculated once only */
168550  int i;                          /* Iterator variable */
168551  int nInst = 0;                  /* Value returned by xInstCount() */
168552  double D = 0.0;                 /* Total number of tokens in row */
168553  double *aFreq = 0;              /* Array of phrase freq. for current row */
168554
168555  /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
168556  ** for each phrase in the query for the current row. */
168557  rc = fts5Bm25GetData(pApi, pFts, &pData);
168558  if( rc==SQLITE_OK ){
168559    aFreq = pData->aFreq;
168560    memset(aFreq, 0, sizeof(double) * pData->nPhrase);
168561    rc = pApi->xInstCount(pFts, &nInst);
168562  }
168563  for(i=0; rc==SQLITE_OK && i<nInst; i++){
168564    int ip; int ic; int io;
168565    rc = pApi->xInst(pFts, i, &ip, &ic, &io);
168566    if( rc==SQLITE_OK ){
168567      double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
168568      aFreq[ip] += w;
168569    }
168570  }
168571
168572  /* Figure out the total size of the current row in tokens. */
168573  if( rc==SQLITE_OK ){
168574    int nTok;
168575    rc = pApi->xColumnSize(pFts, -1, &nTok);
168576    D = (double)nTok;
168577  }
168578
168579  /* Determine the BM25 score for the current row. */
168580  for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
168581    score += pData->aIDF[i] * (
168582      ( aFreq[i] * (k1 + 1.0) ) /
168583      ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
168584    );
168585  }
168586
168587  /* If no error has occurred, return the calculated score. Otherwise,
168588  ** throw an SQL exception.  */
168589  if( rc==SQLITE_OK ){
168590    sqlite3_result_double(pCtx, -1.0 * score);
168591  }else{
168592    sqlite3_result_error_code(pCtx, rc);
168593  }
168594}
168595
168596static int sqlite3Fts5AuxInit(fts5_api *pApi){
168597  struct Builtin {
168598    const char *zFunc;            /* Function name (nul-terminated) */
168599    void *pUserData;              /* User-data pointer */
168600    fts5_extension_function xFunc;/* Callback function */
168601    void (*xDestroy)(void*);      /* Destructor function */
168602  } aBuiltin [] = {
168603    { "snippet",   0, fts5SnippetFunction, 0 },
168604    { "highlight", 0, fts5HighlightFunction, 0 },
168605    { "bm25",      0, fts5Bm25Function,    0 },
168606  };
168607  int rc = SQLITE_OK;             /* Return code */
168608  int i;                          /* To iterate through builtin functions */
168609
168610  for(i=0; rc==SQLITE_OK && i<sizeof(aBuiltin)/sizeof(aBuiltin[0]); i++){
168611    rc = pApi->xCreateFunction(pApi,
168612        aBuiltin[i].zFunc,
168613        aBuiltin[i].pUserData,
168614        aBuiltin[i].xFunc,
168615        aBuiltin[i].xDestroy
168616    );
168617  }
168618
168619  return rc;
168620}
168621
168622
168623
168624/*
168625** 2014 May 31
168626**
168627** The author disclaims copyright to this source code.  In place of
168628** a legal notice, here is a blessing:
168629**
168630**    May you do good and not evil.
168631**    May you find forgiveness for yourself and forgive others.
168632**    May you share freely, never taking more than you give.
168633**
168634******************************************************************************
168635*/
168636
168637
168638
168639
168640static int sqlite3Fts5BufferGrow(int *pRc, Fts5Buffer *pBuf, int nByte){
168641
168642  if( (pBuf->n + nByte) > pBuf->nSpace ){
168643    u8 *pNew;
168644    int nNew = pBuf->nSpace ? pBuf->nSpace*2 : 64;
168645
168646    /* A no-op if an error has already occurred */
168647    if( *pRc ) return 1;
168648
168649    while( nNew<(pBuf->n + nByte) ){
168650      nNew = nNew * 2;
168651    }
168652    pNew = sqlite3_realloc(pBuf->p, nNew);
168653    if( pNew==0 ){
168654      *pRc = SQLITE_NOMEM;
168655      return 1;
168656    }else{
168657      pBuf->nSpace = nNew;
168658      pBuf->p = pNew;
168659    }
168660  }
168661  return 0;
168662}
168663
168664/*
168665** Encode value iVal as an SQLite varint and append it to the buffer object
168666** pBuf. If an OOM error occurs, set the error code in p.
168667*/
168668static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
168669  if( sqlite3Fts5BufferGrow(pRc, pBuf, 9) ) return;
168670  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
168671}
168672
168673static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
168674  aBuf[0] = (iVal>>24) & 0x00FF;
168675  aBuf[1] = (iVal>>16) & 0x00FF;
168676  aBuf[2] = (iVal>> 8) & 0x00FF;
168677  aBuf[3] = (iVal>> 0) & 0x00FF;
168678}
168679
168680static int sqlite3Fts5Get32(const u8 *aBuf){
168681  return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
168682}
168683
168684static void sqlite3Fts5BufferAppend32(int *pRc, Fts5Buffer *pBuf, int iVal){
168685  if( sqlite3Fts5BufferGrow(pRc, pBuf, 4) ) return;
168686  sqlite3Fts5Put32(&pBuf->p[pBuf->n], iVal);
168687  pBuf->n += 4;
168688}
168689
168690/*
168691** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
168692** the error code in p. If an error has already occurred when this function
168693** is called, it is a no-op.
168694*/
168695static void sqlite3Fts5BufferAppendBlob(
168696  int *pRc,
168697  Fts5Buffer *pBuf,
168698  int nData,
168699  const u8 *pData
168700){
168701  assert( *pRc || nData>=0 );
168702  if( sqlite3Fts5BufferGrow(pRc, pBuf, nData) ) return;
168703  memcpy(&pBuf->p[pBuf->n], pData, nData);
168704  pBuf->n += nData;
168705}
168706
168707/*
168708** Append the nul-terminated string zStr to the buffer pBuf. This function
168709** ensures that the byte following the buffer data is set to 0x00, even
168710** though this byte is not included in the pBuf->n count.
168711*/
168712static void sqlite3Fts5BufferAppendString(
168713  int *pRc,
168714  Fts5Buffer *pBuf,
168715  const char *zStr
168716){
168717  int nStr = strlen(zStr);
168718  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
168719  pBuf->n--;
168720}
168721
168722/*
168723** Argument zFmt is a printf() style format string. This function performs
168724** the printf() style processing, then appends the results to buffer pBuf.
168725**
168726** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
168727** following the buffer data is set to 0x00, even though this byte is not
168728** included in the pBuf->n count.
168729*/
168730static void sqlite3Fts5BufferAppendPrintf(
168731  int *pRc,
168732  Fts5Buffer *pBuf,
168733  char *zFmt, ...
168734){
168735  if( *pRc==SQLITE_OK ){
168736    char *zTmp;
168737    va_list ap;
168738    va_start(ap, zFmt);
168739    zTmp = sqlite3_vmprintf(zFmt, ap);
168740    va_end(ap);
168741
168742    if( zTmp==0 ){
168743      *pRc = SQLITE_NOMEM;
168744    }else{
168745      sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
168746      sqlite3_free(zTmp);
168747    }
168748  }
168749}
168750
168751static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
168752  char *zRet = 0;
168753  if( *pRc==SQLITE_OK ){
168754    va_list ap;
168755    va_start(ap, zFmt);
168756    zRet = sqlite3_vmprintf(zFmt, ap);
168757    va_end(ap);
168758    if( zRet==0 ){
168759      *pRc = SQLITE_NOMEM;
168760    }
168761  }
168762  return zRet;
168763}
168764
168765
168766/*
168767** Free any buffer allocated by pBuf. Zero the structure before returning.
168768*/
168769static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
168770  sqlite3_free(pBuf->p);
168771  memset(pBuf, 0, sizeof(Fts5Buffer));
168772}
168773
168774/*
168775** Zero the contents of the buffer object. But do not free the associated
168776** memory allocation.
168777*/
168778static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
168779  pBuf->n = 0;
168780}
168781
168782/*
168783** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
168784** the error code in p. If an error has already occurred when this function
168785** is called, it is a no-op.
168786*/
168787static void sqlite3Fts5BufferSet(
168788  int *pRc,
168789  Fts5Buffer *pBuf,
168790  int nData,
168791  const u8 *pData
168792){
168793  pBuf->n = 0;
168794  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
168795}
168796
168797static int sqlite3Fts5PoslistNext64(
168798  const u8 *a, int n,             /* Buffer containing poslist */
168799  int *pi,                        /* IN/OUT: Offset within a[] */
168800  i64 *piOff                      /* IN/OUT: Current offset */
168801){
168802  int i = *pi;
168803  if( i>=n ){
168804    /* EOF */
168805    *piOff = -1;
168806    return 1;
168807  }else{
168808    i64 iOff = *piOff;
168809    int iVal;
168810    fts5FastGetVarint32(a, i, iVal);
168811    if( iVal==1 ){
168812      fts5FastGetVarint32(a, i, iVal);
168813      iOff = ((i64)iVal) << 32;
168814      fts5FastGetVarint32(a, i, iVal);
168815    }
168816    *piOff = iOff + (iVal-2);
168817    *pi = i;
168818    return 0;
168819  }
168820}
168821
168822
168823/*
168824** Advance the iterator object passed as the only argument. Return true
168825** if the iterator reaches EOF, or false otherwise.
168826*/
168827static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
168828  if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
168829    pIter->bEof = 1;
168830  }
168831  return pIter->bEof;
168832}
168833
168834static int sqlite3Fts5PoslistReaderInit(
168835  const u8 *a, int n,             /* Poslist buffer to iterate through */
168836  Fts5PoslistReader *pIter        /* Iterator object to initialize */
168837){
168838  memset(pIter, 0, sizeof(*pIter));
168839  pIter->a = a;
168840  pIter->n = n;
168841  sqlite3Fts5PoslistReaderNext(pIter);
168842  return pIter->bEof;
168843}
168844
168845static int sqlite3Fts5PoslistWriterAppend(
168846  Fts5Buffer *pBuf,
168847  Fts5PoslistWriter *pWriter,
168848  i64 iPos
168849){
168850  static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
168851  int rc = SQLITE_OK;
168852  if( 0==sqlite3Fts5BufferGrow(&rc, pBuf, 5+5+5) ){
168853    if( (iPos & colmask) != (pWriter->iPrev & colmask) ){
168854      pBuf->p[pBuf->n++] = 1;
168855      pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
168856      pWriter->iPrev = (iPos & colmask);
168857    }
168858    pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-pWriter->iPrev)+2);
168859    pWriter->iPrev = iPos;
168860  }
168861  return rc;
168862}
168863
168864static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
168865  void *pRet = 0;
168866  if( *pRc==SQLITE_OK ){
168867    pRet = sqlite3_malloc(nByte);
168868    if( pRet==0 && nByte>0 ){
168869      *pRc = SQLITE_NOMEM;
168870    }else{
168871      memset(pRet, 0, nByte);
168872    }
168873  }
168874  return pRet;
168875}
168876
168877/*
168878** Return a nul-terminated copy of the string indicated by pIn. If nIn
168879** is non-negative, then it is the length of the string in bytes. Otherwise,
168880** the length of the string is determined using strlen().
168881**
168882** It is the responsibility of the caller to eventually free the returned
168883** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
168884*/
168885static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
168886  char *zRet = 0;
168887  if( *pRc==SQLITE_OK ){
168888    if( nIn<0 ){
168889      nIn = strlen(pIn);
168890    }
168891    zRet = (char*)sqlite3_malloc(nIn+1);
168892    if( zRet ){
168893      memcpy(zRet, pIn, nIn);
168894      zRet[nIn] = '\0';
168895    }else{
168896      *pRc = SQLITE_NOMEM;
168897    }
168898  }
168899  return zRet;
168900}
168901
168902
168903/*
168904** Return true if character 't' may be part of an FTS5 bareword, or false
168905** otherwise. Characters that may be part of barewords:
168906**
168907**   * All non-ASCII characters,
168908**   * The 52 upper and lower case ASCII characters, and
168909**   * The 10 integer ASCII characters.
168910**   * The underscore character "_" (0x5F).
168911**   * The unicode "subsitute" character (0x1A).
168912*/
168913static int sqlite3Fts5IsBareword(char t){
168914  u8 aBareword[128] = {
168915    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00 .. 0x0F */
168916    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 1, 0, 0, 0, 0, 0,   /* 0x10 .. 0x1F */
168917    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20 .. 0x2F */
168918    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30 .. 0x3F */
168919    0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40 .. 0x4F */
168920    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 1,   /* 0x50 .. 0x5F */
168921    0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60 .. 0x6F */
168922    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 0    /* 0x70 .. 0x7F */
168923  };
168924
168925  return (t & 0x80) || aBareword[(int)t];
168926}
168927
168928
168929
168930/*
168931** 2014 Jun 09
168932**
168933** The author disclaims copyright to this source code.  In place of
168934** a legal notice, here is a blessing:
168935**
168936**    May you do good and not evil.
168937**    May you find forgiveness for yourself and forgive others.
168938**    May you share freely, never taking more than you give.
168939**
168940******************************************************************************
168941**
168942** This is an SQLite module implementing full-text search.
168943*/
168944
168945
168946
168947
168948#define FTS5_DEFAULT_PAGE_SIZE   4050
168949#define FTS5_DEFAULT_AUTOMERGE      4
168950#define FTS5_DEFAULT_CRISISMERGE   16
168951
168952/* Maximum allowed page size */
168953#define FTS5_MAX_PAGE_SIZE (128*1024)
168954
168955static int fts5_iswhitespace(char x){
168956  return (x==' ');
168957}
168958
168959static int fts5_isopenquote(char x){
168960  return (x=='"' || x=='\'' || x=='[' || x=='`');
168961}
168962
168963/*
168964** Argument pIn points to a character that is part of a nul-terminated
168965** string. Return a pointer to the first character following *pIn in
168966** the string that is not a white-space character.
168967*/
168968static const char *fts5ConfigSkipWhitespace(const char *pIn){
168969  const char *p = pIn;
168970  if( p ){
168971    while( fts5_iswhitespace(*p) ){ p++; }
168972  }
168973  return p;
168974}
168975
168976/*
168977** Argument pIn points to a character that is part of a nul-terminated
168978** string. Return a pointer to the first character following *pIn in
168979** the string that is not a "bareword" character.
168980*/
168981static const char *fts5ConfigSkipBareword(const char *pIn){
168982  const char *p = pIn;
168983  while ( sqlite3Fts5IsBareword(*p) ) p++;
168984  if( p==pIn ) p = 0;
168985  return p;
168986}
168987
168988static int fts5_isdigit(char a){
168989  return (a>='0' && a<='9');
168990}
168991
168992
168993
168994static const char *fts5ConfigSkipLiteral(const char *pIn){
168995  const char *p = pIn;
168996  switch( *p ){
168997    case 'n': case 'N':
168998      if( sqlite3_strnicmp("null", p, 4)==0 ){
168999        p = &p[4];
169000      }else{
169001        p = 0;
169002      }
169003      break;
169004
169005    case 'x': case 'X':
169006      p++;
169007      if( *p=='\'' ){
169008        p++;
169009        while( (*p>='a' && *p<='f')
169010            || (*p>='A' && *p<='F')
169011            || (*p>='0' && *p<='9')
169012            ){
169013          p++;
169014        }
169015        if( *p=='\'' && 0==((p-pIn)%2) ){
169016          p++;
169017        }else{
169018          p = 0;
169019        }
169020      }else{
169021        p = 0;
169022      }
169023      break;
169024
169025    case '\'':
169026      p++;
169027      while( p ){
169028        if( *p=='\'' ){
169029          p++;
169030          if( *p!='\'' ) break;
169031        }
169032        p++;
169033        if( *p==0 ) p = 0;
169034      }
169035      break;
169036
169037    default:
169038      /* maybe a number */
169039      if( *p=='+' || *p=='-' ) p++;
169040      while( fts5_isdigit(*p) ) p++;
169041
169042      /* At this point, if the literal was an integer, the parse is
169043      ** finished. Or, if it is a floating point value, it may continue
169044      ** with either a decimal point or an 'E' character. */
169045      if( *p=='.' && fts5_isdigit(p[1]) ){
169046        p += 2;
169047        while( fts5_isdigit(*p) ) p++;
169048      }
169049      if( p==pIn ) p = 0;
169050
169051      break;
169052  }
169053
169054  return p;
169055}
169056
169057/*
169058** The first character of the string pointed to by argument z is guaranteed
169059** to be an open-quote character (see function fts5_isopenquote()).
169060**
169061** This function searches for the corresponding close-quote character within
169062** the string and, if found, dequotes the string in place and adds a new
169063** nul-terminator byte.
169064**
169065** If the close-quote is found, the value returned is the byte offset of
169066** the character immediately following it. Or, if the close-quote is not
169067** found, -1 is returned. If -1 is returned, the buffer is left in an
169068** undefined state.
169069*/
169070static int fts5Dequote(char *z){
169071  char q;
169072  int iIn = 1;
169073  int iOut = 0;
169074  q = z[0];
169075
169076  /* Set stack variable q to the close-quote character */
169077  assert( q=='[' || q=='\'' || q=='"' || q=='`' );
169078  if( q=='[' ) q = ']';
169079
169080  while( ALWAYS(z[iIn]) ){
169081    if( z[iIn]==q ){
169082      if( z[iIn+1]!=q ){
169083        /* Character iIn was the close quote. */
169084        iIn++;
169085        break;
169086      }else{
169087        /* Character iIn and iIn+1 form an escaped quote character. Skip
169088        ** the input cursor past both and copy a single quote character
169089        ** to the output buffer. */
169090        iIn += 2;
169091        z[iOut++] = q;
169092      }
169093    }else{
169094      z[iOut++] = z[iIn++];
169095    }
169096  }
169097
169098  z[iOut] = '\0';
169099  return iIn;
169100}
169101
169102/*
169103** Convert an SQL-style quoted string into a normal string by removing
169104** the quote characters.  The conversion is done in-place.  If the
169105** input does not begin with a quote character, then this routine
169106** is a no-op.
169107**
169108** Examples:
169109**
169110**     "abc"   becomes   abc
169111**     'xyz'   becomes   xyz
169112**     [pqr]   becomes   pqr
169113**     `mno`   becomes   mno
169114*/
169115static void sqlite3Fts5Dequote(char *z){
169116  char quote;                     /* Quote character (if any ) */
169117
169118  assert( 0==fts5_iswhitespace(z[0]) );
169119  quote = z[0];
169120  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
169121    fts5Dequote(z);
169122  }
169123}
169124
169125/*
169126** Parse a "special" CREATE VIRTUAL TABLE directive and update
169127** configuration object pConfig as appropriate.
169128**
169129** If successful, object pConfig is updated and SQLITE_OK returned. If
169130** an error occurs, an SQLite error code is returned and an error message
169131** may be left in *pzErr. It is the responsibility of the caller to
169132** eventually free any such error message using sqlite3_free().
169133*/
169134static int fts5ConfigParseSpecial(
169135  Fts5Global *pGlobal,
169136  Fts5Config *pConfig,            /* Configuration object to update */
169137  const char *zCmd,               /* Special command to parse */
169138  const char *zArg,               /* Argument to parse */
169139  char **pzErr                    /* OUT: Error message */
169140){
169141  int rc = SQLITE_OK;
169142  int nCmd = strlen(zCmd);
169143  if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
169144    const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
169145    const char *p;
169146    if( pConfig->aPrefix ){
169147      *pzErr = sqlite3_mprintf("multiple prefix=... directives");
169148      rc = SQLITE_ERROR;
169149    }else{
169150      pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
169151    }
169152    p = zArg;
169153    while( rc==SQLITE_OK && p[0] ){
169154      int nPre = 0;
169155      while( p[0]==' ' ) p++;
169156      while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
169157        nPre = nPre*10 + (p[0] - '0');
169158        p++;
169159      }
169160      while( p[0]==' ' ) p++;
169161      if( p[0]==',' ){
169162        p++;
169163      }else if( p[0] ){
169164        *pzErr = sqlite3_mprintf("malformed prefix=... directive");
169165        rc = SQLITE_ERROR;
169166      }
169167      if( rc==SQLITE_OK && (nPre==0 || nPre>=1000) ){
169168        *pzErr = sqlite3_mprintf("prefix length out of range: %d", nPre);
169169        rc = SQLITE_ERROR;
169170      }
169171      pConfig->aPrefix[pConfig->nPrefix] = nPre;
169172      pConfig->nPrefix++;
169173    }
169174    return rc;
169175  }
169176
169177  if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
169178    const char *p = (const char*)zArg;
169179    int nArg = strlen(zArg) + 1;
169180    char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
169181    char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
169182    char *pSpace = pDel;
169183
169184    if( azArg && pSpace ){
169185      if( pConfig->pTok ){
169186        *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
169187        rc = SQLITE_ERROR;
169188      }else{
169189        for(nArg=0; p && *p; nArg++){
169190          const char *p2 = fts5ConfigSkipWhitespace(p);
169191          if( *p2=='\'' ){
169192            p = fts5ConfigSkipLiteral(p2);
169193          }else{
169194            p = fts5ConfigSkipBareword(p2);
169195          }
169196          if( p ){
169197            memcpy(pSpace, p2, p-p2);
169198            azArg[nArg] = pSpace;
169199            sqlite3Fts5Dequote(pSpace);
169200            pSpace += (p - p2) + 1;
169201            p = fts5ConfigSkipWhitespace(p);
169202          }
169203        }
169204        if( p==0 ){
169205          *pzErr = sqlite3_mprintf("parse error in tokenize directive");
169206          rc = SQLITE_ERROR;
169207        }else{
169208          rc = sqlite3Fts5GetTokenizer(pGlobal,
169209              (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
169210              pzErr
169211          );
169212        }
169213      }
169214    }
169215
169216    sqlite3_free(azArg);
169217    sqlite3_free(pDel);
169218    return rc;
169219  }
169220
169221  if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
169222    if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
169223      *pzErr = sqlite3_mprintf("multiple content=... directives");
169224      rc = SQLITE_ERROR;
169225    }else{
169226      if( zArg[0] ){
169227        pConfig->eContent = FTS5_CONTENT_EXTERNAL;
169228        pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
169229      }else{
169230        pConfig->eContent = FTS5_CONTENT_NONE;
169231      }
169232    }
169233    return rc;
169234  }
169235
169236  if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
169237    if( pConfig->zContentRowid ){
169238      *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
169239      rc = SQLITE_ERROR;
169240    }else{
169241      pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
169242    }
169243    return rc;
169244  }
169245
169246  if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
169247    if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
169248      *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
169249      rc = SQLITE_ERROR;
169250    }else{
169251      pConfig->bColumnsize = (zArg[0]=='1');
169252    }
169253    return rc;
169254  }
169255
169256  *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
169257  return SQLITE_ERROR;
169258}
169259
169260/*
169261** Allocate an instance of the default tokenizer ("simple") at
169262** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
169263** code if an error occurs.
169264*/
169265static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
169266  assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
169267  return sqlite3Fts5GetTokenizer(
169268      pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
169269  );
169270}
169271
169272/*
169273** Gobble up the first bareword or quoted word from the input buffer zIn.
169274** Return a pointer to the character immediately following the last in
169275** the gobbled word if successful, or a NULL pointer otherwise (failed
169276** to find close-quote character).
169277**
169278** Before returning, set pzOut to point to a new buffer containing a
169279** nul-terminated, dequoted copy of the gobbled word. If the word was
169280** quoted, *pbQuoted is also set to 1 before returning.
169281**
169282** If *pRc is other than SQLITE_OK when this function is called, it is
169283** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
169284** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
169285** set if a parse error (failed to find close quote) occurs.
169286*/
169287static const char *fts5ConfigGobbleWord(
169288  int *pRc,                       /* IN/OUT: Error code */
169289  const char *zIn,                /* Buffer to gobble string/bareword from */
169290  char **pzOut,                   /* OUT: malloc'd buffer containing str/bw */
169291  int *pbQuoted                   /* OUT: Set to true if dequoting required */
169292){
169293  const char *zRet = 0;
169294
169295  int nIn = strlen(zIn);
169296  char *zOut = sqlite3_malloc(nIn+1);
169297
169298  assert( *pRc==SQLITE_OK );
169299  *pbQuoted = 0;
169300  *pzOut = 0;
169301
169302  if( zOut==0 ){
169303    *pRc = SQLITE_NOMEM;
169304  }else{
169305    memcpy(zOut, zIn, nIn+1);
169306    if( fts5_isopenquote(zOut[0]) ){
169307      int ii = fts5Dequote(zOut);
169308      zRet = &zIn[ii];
169309      *pbQuoted = 1;
169310    }else{
169311      zRet = fts5ConfigSkipBareword(zIn);
169312      zOut[zRet-zIn] = '\0';
169313    }
169314  }
169315
169316  if( zRet==0 ){
169317    sqlite3_free(zOut);
169318  }else{
169319    *pzOut = zOut;
169320  }
169321
169322  return zRet;
169323}
169324
169325static int fts5ConfigParseColumn(
169326  Fts5Config *p,
169327  char *zCol,
169328  char *zArg,
169329  char **pzErr
169330){
169331  int rc = SQLITE_OK;
169332  if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
169333   || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
169334  ){
169335    *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
169336    rc = SQLITE_ERROR;
169337  }else if( zArg ){
169338    if( 0==sqlite3_stricmp(zArg, "unindexed") ){
169339      p->abUnindexed[p->nCol] = 1;
169340    }else{
169341      *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
169342      rc = SQLITE_ERROR;
169343    }
169344  }
169345
169346  p->azCol[p->nCol++] = zCol;
169347  return rc;
169348}
169349
169350/*
169351** Populate the Fts5Config.zContentExprlist string.
169352*/
169353static int fts5ConfigMakeExprlist(Fts5Config *p){
169354  int i;
169355  int rc = SQLITE_OK;
169356  Fts5Buffer buf = {0, 0, 0};
169357
169358  sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
169359  if( p->eContent!=FTS5_CONTENT_NONE ){
169360    for(i=0; i<p->nCol; i++){
169361      if( p->eContent==FTS5_CONTENT_EXTERNAL ){
169362        sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
169363      }else{
169364        sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
169365      }
169366    }
169367  }
169368
169369  assert( p->zContentExprlist==0 );
169370  p->zContentExprlist = (char*)buf.p;
169371  return rc;
169372}
169373
169374/*
169375** Arguments nArg/azArg contain the string arguments passed to the xCreate
169376** or xConnect method of the virtual table. This function attempts to
169377** allocate an instance of Fts5Config containing the results of parsing
169378** those arguments.
169379**
169380** If successful, SQLITE_OK is returned and *ppOut is set to point to the
169381** new Fts5Config object. If an error occurs, an SQLite error code is
169382** returned, *ppOut is set to NULL and an error message may be left in
169383** *pzErr. It is the responsibility of the caller to eventually free any
169384** such error message using sqlite3_free().
169385*/
169386static int sqlite3Fts5ConfigParse(
169387  Fts5Global *pGlobal,
169388  sqlite3 *db,
169389  int nArg,                       /* Number of arguments */
169390  const char **azArg,             /* Array of nArg CREATE VIRTUAL TABLE args */
169391  Fts5Config **ppOut,             /* OUT: Results of parse */
169392  char **pzErr                    /* OUT: Error message */
169393){
169394  int rc = SQLITE_OK;             /* Return code */
169395  Fts5Config *pRet;               /* New object to return */
169396  int i;
169397  int nByte;
169398
169399  *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
169400  if( pRet==0 ) return SQLITE_NOMEM;
169401  memset(pRet, 0, sizeof(Fts5Config));
169402  pRet->db = db;
169403  pRet->iCookie = -1;
169404
169405  nByte = nArg * (sizeof(char*) + sizeof(u8));
169406  pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
169407  pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
169408  pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
169409  pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
169410  pRet->bColumnsize = 1;
169411#ifdef SQLITE_DEBUG
169412  pRet->bPrefixIndex = 1;
169413#endif
169414  if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
169415    *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
169416    rc = SQLITE_ERROR;
169417  }
169418
169419  for(i=3; rc==SQLITE_OK && i<nArg; i++){
169420    const char *zOrig = azArg[i];
169421    const char *z;
169422    char *zOne = 0;
169423    char *zTwo = 0;
169424    int bOption = 0;
169425    int bMustBeCol = 0;
169426
169427    z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
169428    z = fts5ConfigSkipWhitespace(z);
169429    if( z && *z=='=' ){
169430      bOption = 1;
169431      z++;
169432      if( bMustBeCol ) z = 0;
169433    }
169434    z = fts5ConfigSkipWhitespace(z);
169435    if( z && z[0] ){
169436      int bDummy;
169437      z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
169438      if( z && z[0] ) z = 0;
169439    }
169440
169441    if( rc==SQLITE_OK ){
169442      if( z==0 ){
169443        *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
169444        rc = SQLITE_ERROR;
169445      }else{
169446        if( bOption ){
169447          rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
169448        }else{
169449          rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
169450          zOne = 0;
169451        }
169452      }
169453    }
169454
169455    sqlite3_free(zOne);
169456    sqlite3_free(zTwo);
169457  }
169458
169459  /* If a tokenizer= option was successfully parsed, the tokenizer has
169460  ** already been allocated. Otherwise, allocate an instance of the default
169461  ** tokenizer (unicode61) now.  */
169462  if( rc==SQLITE_OK && pRet->pTok==0 ){
169463    rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
169464  }
169465
169466  /* If no zContent option was specified, fill in the default values. */
169467  if( rc==SQLITE_OK && pRet->zContent==0 ){
169468    const char *zTail = 0;
169469    assert( pRet->eContent==FTS5_CONTENT_NORMAL
169470         || pRet->eContent==FTS5_CONTENT_NONE
169471    );
169472    if( pRet->eContent==FTS5_CONTENT_NORMAL ){
169473      zTail = "content";
169474    }else if( pRet->bColumnsize ){
169475      zTail = "docsize";
169476    }
169477
169478    if( zTail ){
169479      pRet->zContent = sqlite3Fts5Mprintf(
169480          &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
169481      );
169482    }
169483  }
169484
169485  if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
169486    pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
169487  }
169488
169489  /* Formulate the zContentExprlist text */
169490  if( rc==SQLITE_OK ){
169491    rc = fts5ConfigMakeExprlist(pRet);
169492  }
169493
169494  if( rc!=SQLITE_OK ){
169495    sqlite3Fts5ConfigFree(pRet);
169496    *ppOut = 0;
169497  }
169498  return rc;
169499}
169500
169501/*
169502** Free the configuration object passed as the only argument.
169503*/
169504static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
169505  if( pConfig ){
169506    int i;
169507    if( pConfig->pTok ){
169508      pConfig->pTokApi->xDelete(pConfig->pTok);
169509    }
169510    sqlite3_free(pConfig->zDb);
169511    sqlite3_free(pConfig->zName);
169512    for(i=0; i<pConfig->nCol; i++){
169513      sqlite3_free(pConfig->azCol[i]);
169514    }
169515    sqlite3_free(pConfig->azCol);
169516    sqlite3_free(pConfig->aPrefix);
169517    sqlite3_free(pConfig->zRank);
169518    sqlite3_free(pConfig->zRankArgs);
169519    sqlite3_free(pConfig->zContent);
169520    sqlite3_free(pConfig->zContentRowid);
169521    sqlite3_free(pConfig->zContentExprlist);
169522    sqlite3_free(pConfig);
169523  }
169524}
169525
169526/*
169527** Call sqlite3_declare_vtab() based on the contents of the configuration
169528** object passed as the only argument. Return SQLITE_OK if successful, or
169529** an SQLite error code if an error occurs.
169530*/
169531static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
169532  int i;
169533  int rc = SQLITE_OK;
169534  char *zSql;
169535
169536  zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
169537  for(i=0; zSql && i<pConfig->nCol; i++){
169538    const char *zSep = (i==0?"":", ");
169539    zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
169540  }
169541  zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
169542      zSql, pConfig->zName, FTS5_RANK_NAME
169543  );
169544
169545  assert( zSql || rc==SQLITE_NOMEM );
169546  if( zSql ){
169547    rc = sqlite3_declare_vtab(pConfig->db, zSql);
169548    sqlite3_free(zSql);
169549  }
169550
169551  return rc;
169552}
169553
169554/*
169555** Tokenize the text passed via the second and third arguments.
169556**
169557** The callback is invoked once for each token in the input text. The
169558** arguments passed to it are, in order:
169559**
169560**     void *pCtx          // Copy of 4th argument to sqlite3Fts5Tokenize()
169561**     const char *pToken  // Pointer to buffer containing token
169562**     int nToken          // Size of token in bytes
169563**     int iStart          // Byte offset of start of token within input text
169564**     int iEnd            // Byte offset of end of token within input text
169565**     int iPos            // Position of token in input (first token is 0)
169566**
169567** If the callback returns a non-zero value the tokenization is abandoned
169568** and no further callbacks are issued.
169569**
169570** This function returns SQLITE_OK if successful or an SQLite error code
169571** if an error occurs. If the tokenization was abandoned early because
169572** the callback returned SQLITE_DONE, this is not an error and this function
169573** still returns SQLITE_OK. Or, if the tokenization was abandoned early
169574** because the callback returned another non-zero value, it is assumed
169575** to be an SQLite error code and returned to the caller.
169576*/
169577static int sqlite3Fts5Tokenize(
169578  Fts5Config *pConfig,            /* FTS5 Configuration object */
169579  int flags,                      /* FTS5_TOKENIZE_* flags */
169580  const char *pText, int nText,   /* Text to tokenize */
169581  void *pCtx,                     /* Context passed to xToken() */
169582  int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
169583){
169584  if( pText==0 ) return SQLITE_OK;
169585  return pConfig->pTokApi->xTokenize(
169586      pConfig->pTok, pCtx, flags, pText, nText, xToken
169587  );
169588}
169589
169590/*
169591** Argument pIn points to the first character in what is expected to be
169592** a comma-separated list of SQL literals followed by a ')' character.
169593** If it actually is this, return a pointer to the ')'. Otherwise, return
169594** NULL to indicate a parse error.
169595*/
169596static const char *fts5ConfigSkipArgs(const char *pIn){
169597  const char *p = pIn;
169598
169599  while( 1 ){
169600    p = fts5ConfigSkipWhitespace(p);
169601    p = fts5ConfigSkipLiteral(p);
169602    p = fts5ConfigSkipWhitespace(p);
169603    if( p==0 || *p==')' ) break;
169604    if( *p!=',' ){
169605      p = 0;
169606      break;
169607    }
169608    p++;
169609  }
169610
169611  return p;
169612}
169613
169614/*
169615** Parameter zIn contains a rank() function specification. The format of
169616** this is:
169617**
169618**   + Bareword (function name)
169619**   + Open parenthesis - "("
169620**   + Zero or more SQL literals in a comma separated list
169621**   + Close parenthesis - ")"
169622*/
169623static int sqlite3Fts5ConfigParseRank(
169624  const char *zIn,                /* Input string */
169625  char **pzRank,                  /* OUT: Rank function name */
169626  char **pzRankArgs               /* OUT: Rank function arguments */
169627){
169628  const char *p = zIn;
169629  const char *pRank;
169630  char *zRank = 0;
169631  char *zRankArgs = 0;
169632  int rc = SQLITE_OK;
169633
169634  *pzRank = 0;
169635  *pzRankArgs = 0;
169636
169637  p = fts5ConfigSkipWhitespace(p);
169638  pRank = p;
169639  p = fts5ConfigSkipBareword(p);
169640
169641  if( p ){
169642    zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
169643    if( zRank ) memcpy(zRank, pRank, p-pRank);
169644  }else{
169645    rc = SQLITE_ERROR;
169646  }
169647
169648  if( rc==SQLITE_OK ){
169649    p = fts5ConfigSkipWhitespace(p);
169650    if( *p!='(' ) rc = SQLITE_ERROR;
169651    p++;
169652  }
169653  if( rc==SQLITE_OK ){
169654    const char *pArgs;
169655    p = fts5ConfigSkipWhitespace(p);
169656    pArgs = p;
169657    if( *p!=')' ){
169658      p = fts5ConfigSkipArgs(p);
169659      if( p==0 ){
169660        rc = SQLITE_ERROR;
169661      }else{
169662        zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
169663        if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
169664      }
169665    }
169666  }
169667
169668  if( rc!=SQLITE_OK ){
169669    sqlite3_free(zRank);
169670    assert( zRankArgs==0 );
169671  }else{
169672    *pzRank = zRank;
169673    *pzRankArgs = zRankArgs;
169674  }
169675  return rc;
169676}
169677
169678static int sqlite3Fts5ConfigSetValue(
169679  Fts5Config *pConfig,
169680  const char *zKey,
169681  sqlite3_value *pVal,
169682  int *pbBadkey
169683){
169684  int rc = SQLITE_OK;
169685
169686  if( 0==sqlite3_stricmp(zKey, "pgsz") ){
169687    int pgsz = 0;
169688    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
169689      pgsz = sqlite3_value_int(pVal);
169690    }
169691    if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
169692      *pbBadkey = 1;
169693    }else{
169694      pConfig->pgsz = pgsz;
169695    }
169696  }
169697
169698  else if( 0==sqlite3_stricmp(zKey, "automerge") ){
169699    int nAutomerge = -1;
169700    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
169701      nAutomerge = sqlite3_value_int(pVal);
169702    }
169703    if( nAutomerge<0 || nAutomerge>64 ){
169704      *pbBadkey = 1;
169705    }else{
169706      if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
169707      pConfig->nAutomerge = nAutomerge;
169708    }
169709  }
169710
169711  else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
169712    int nCrisisMerge = -1;
169713    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
169714      nCrisisMerge = sqlite3_value_int(pVal);
169715    }
169716    if( nCrisisMerge<0 ){
169717      *pbBadkey = 1;
169718    }else{
169719      if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
169720      pConfig->nCrisisMerge = nCrisisMerge;
169721    }
169722  }
169723
169724  else if( 0==sqlite3_stricmp(zKey, "rank") ){
169725    const char *zIn = (const char*)sqlite3_value_text(pVal);
169726    char *zRank;
169727    char *zRankArgs;
169728    rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
169729    if( rc==SQLITE_OK ){
169730      sqlite3_free(pConfig->zRank);
169731      sqlite3_free(pConfig->zRankArgs);
169732      pConfig->zRank = zRank;
169733      pConfig->zRankArgs = zRankArgs;
169734    }else if( rc==SQLITE_ERROR ){
169735      rc = SQLITE_OK;
169736      *pbBadkey = 1;
169737    }
169738  }else{
169739    *pbBadkey = 1;
169740  }
169741  return rc;
169742}
169743
169744/*
169745** Load the contents of the %_config table into memory.
169746*/
169747static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
169748  const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
169749  char *zSql;
169750  sqlite3_stmt *p = 0;
169751  int rc = SQLITE_OK;
169752  int iVersion = 0;
169753
169754  /* Set default values */
169755  pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
169756  pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
169757  pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
169758
169759  zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
169760  if( zSql ){
169761    rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
169762    sqlite3_free(zSql);
169763  }
169764
169765  assert( rc==SQLITE_OK || p==0 );
169766  if( rc==SQLITE_OK ){
169767    while( SQLITE_ROW==sqlite3_step(p) ){
169768      const char *zK = (const char*)sqlite3_column_text(p, 0);
169769      sqlite3_value *pVal = sqlite3_column_value(p, 1);
169770      if( 0==sqlite3_stricmp(zK, "version") ){
169771        iVersion = sqlite3_value_int(pVal);
169772      }else{
169773        int bDummy = 0;
169774        sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
169775      }
169776    }
169777    rc = sqlite3_finalize(p);
169778  }
169779
169780  if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
169781    rc = SQLITE_ERROR;
169782    if( pConfig->pzErrmsg ){
169783      assert( 0==*pConfig->pzErrmsg );
169784      *pConfig->pzErrmsg = sqlite3_mprintf(
169785          "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
169786          iVersion, FTS5_CURRENT_VERSION
169787      );
169788    }
169789  }
169790
169791  if( rc==SQLITE_OK ){
169792    pConfig->iCookie = iCookie;
169793  }
169794  return rc;
169795}
169796
169797
169798/*
169799** 2014 May 31
169800**
169801** The author disclaims copyright to this source code.  In place of
169802** a legal notice, here is a blessing:
169803**
169804**    May you do good and not evil.
169805**    May you find forgiveness for yourself and forgive others.
169806**    May you share freely, never taking more than you give.
169807**
169808******************************************************************************
169809**
169810*/
169811
169812
169813
169814
169815/*
169816** All token types in the generated fts5parse.h file are greater than 0.
169817*/
169818#define FTS5_EOF 0
169819
169820#define FTS5_LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
169821
169822typedef struct Fts5ExprTerm Fts5ExprTerm;
169823
169824/*
169825** Functions generated by lemon from fts5parse.y.
169826*/
169827static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
169828static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
169829static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
169830#ifndef NDEBUG
169831/* #include <stdio.h> */
169832static void sqlite3Fts5ParserTrace(FILE*, char*);
169833#endif
169834
169835
169836struct Fts5Expr {
169837  Fts5Index *pIndex;
169838  Fts5ExprNode *pRoot;
169839  int bDesc;                      /* Iterate in descending rowid order */
169840  int nPhrase;                    /* Number of phrases in expression */
169841  Fts5ExprPhrase **apExprPhrase;  /* Pointers to phrase objects */
169842};
169843
169844/*
169845** eType:
169846**   Expression node type. Always one of:
169847**
169848**       FTS5_AND                 (nChild, apChild valid)
169849**       FTS5_OR                  (nChild, apChild valid)
169850**       FTS5_NOT                 (nChild, apChild valid)
169851**       FTS5_STRING              (pNear valid)
169852**       FTS5_TERM                (pNear valid)
169853*/
169854struct Fts5ExprNode {
169855  int eType;                      /* Node type */
169856  int bEof;                       /* True at EOF */
169857  int bNomatch;                   /* True if entry is not a match */
169858
169859  i64 iRowid;                     /* Current rowid */
169860  Fts5ExprNearset *pNear;         /* For FTS5_STRING - cluster of phrases */
169861
169862  /* Child nodes. For a NOT node, this array always contains 2 entries. For
169863  ** AND or OR nodes, it contains 2 or more entries.  */
169864  int nChild;                     /* Number of child nodes */
169865  Fts5ExprNode *apChild[1];       /* Array of child nodes */
169866};
169867
169868#define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
169869
169870/*
169871** An instance of the following structure represents a single search term
169872** or term prefix.
169873*/
169874struct Fts5ExprTerm {
169875  int bPrefix;                    /* True for a prefix term */
169876  char *zTerm;                    /* nul-terminated term */
169877  Fts5IndexIter *pIter;           /* Iterator for this term */
169878  Fts5ExprTerm *pSynonym;         /* Pointer to first in list of synonyms */
169879};
169880
169881/*
169882** A phrase. One or more terms that must appear in a contiguous sequence
169883** within a document for it to match.
169884*/
169885struct Fts5ExprPhrase {
169886  Fts5ExprNode *pNode;            /* FTS5_STRING node this phrase is part of */
169887  Fts5Buffer poslist;             /* Current position list */
169888  int nTerm;                      /* Number of entries in aTerm[] */
169889  Fts5ExprTerm aTerm[1];          /* Terms that make up this phrase */
169890};
169891
169892/*
169893** One or more phrases that must appear within a certain token distance of
169894** each other within each matching document.
169895*/
169896struct Fts5ExprNearset {
169897  int nNear;                      /* NEAR parameter */
169898  Fts5Colset *pColset;            /* Columns to search (NULL -> all columns) */
169899  int nPhrase;                    /* Number of entries in aPhrase[] array */
169900  Fts5ExprPhrase *apPhrase[1];    /* Array of phrase pointers */
169901};
169902
169903
169904/*
169905** Parse context.
169906*/
169907struct Fts5Parse {
169908  Fts5Config *pConfig;
169909  char *zErr;
169910  int rc;
169911  int nPhrase;                    /* Size of apPhrase array */
169912  Fts5ExprPhrase **apPhrase;      /* Array of all phrases */
169913  Fts5ExprNode *pExpr;            /* Result of a successful parse */
169914};
169915
169916static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
169917  va_list ap;
169918  va_start(ap, zFmt);
169919  if( pParse->rc==SQLITE_OK ){
169920    pParse->zErr = sqlite3_vmprintf(zFmt, ap);
169921    pParse->rc = SQLITE_ERROR;
169922  }
169923  va_end(ap);
169924}
169925
169926static int fts5ExprIsspace(char t){
169927  return t==' ' || t=='\t' || t=='\n' || t=='\r';
169928}
169929
169930/*
169931** Read the first token from the nul-terminated string at *pz.
169932*/
169933static int fts5ExprGetToken(
169934  Fts5Parse *pParse,
169935  const char **pz,                /* IN/OUT: Pointer into buffer */
169936  Fts5Token *pToken
169937){
169938  const char *z = *pz;
169939  int tok;
169940
169941  /* Skip past any whitespace */
169942  while( fts5ExprIsspace(*z) ) z++;
169943
169944  pToken->p = z;
169945  pToken->n = 1;
169946  switch( *z ){
169947    case '(':  tok = FTS5_LP;    break;
169948    case ')':  tok = FTS5_RP;    break;
169949    case '{':  tok = FTS5_LCP;   break;
169950    case '}':  tok = FTS5_RCP;   break;
169951    case ':':  tok = FTS5_COLON; break;
169952    case ',':  tok = FTS5_COMMA; break;
169953    case '+':  tok = FTS5_PLUS;  break;
169954    case '*':  tok = FTS5_STAR;  break;
169955    case '\0': tok = FTS5_EOF;   break;
169956
169957    case '"': {
169958      const char *z2;
169959      tok = FTS5_STRING;
169960
169961      for(z2=&z[1]; 1; z2++){
169962        if( z2[0]=='"' ){
169963          z2++;
169964          if( z2[0]!='"' ) break;
169965        }
169966        if( z2[0]=='\0' ){
169967          sqlite3Fts5ParseError(pParse, "unterminated string");
169968          return FTS5_EOF;
169969        }
169970      }
169971      pToken->n = (z2 - z);
169972      break;
169973    }
169974
169975    default: {
169976      const char *z2;
169977      if( sqlite3Fts5IsBareword(z[0])==0 ){
169978        sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
169979        return FTS5_EOF;
169980      }
169981      tok = FTS5_STRING;
169982      for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
169983      pToken->n = (z2 - z);
169984      if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 )  tok = FTS5_OR;
169985      if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
169986      if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
169987      break;
169988    }
169989  }
169990
169991  *pz = &pToken->p[pToken->n];
169992  return tok;
169993}
169994
169995static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
169996static void fts5ParseFree(void *p){ sqlite3_free(p); }
169997
169998static int sqlite3Fts5ExprNew(
169999  Fts5Config *pConfig,            /* FTS5 Configuration */
170000  const char *zExpr,              /* Expression text */
170001  Fts5Expr **ppNew,
170002  char **pzErr
170003){
170004  Fts5Parse sParse;
170005  Fts5Token token;
170006  const char *z = zExpr;
170007  int t;                          /* Next token type */
170008  void *pEngine;
170009  Fts5Expr *pNew;
170010
170011  *ppNew = 0;
170012  *pzErr = 0;
170013  memset(&sParse, 0, sizeof(sParse));
170014  pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
170015  if( pEngine==0 ){ return SQLITE_NOMEM; }
170016  sParse.pConfig = pConfig;
170017
170018  do {
170019    t = fts5ExprGetToken(&sParse, &z, &token);
170020    sqlite3Fts5Parser(pEngine, t, token, &sParse);
170021  }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
170022  sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
170023
170024  assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
170025  if( sParse.rc==SQLITE_OK ){
170026    *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
170027    if( pNew==0 ){
170028      sParse.rc = SQLITE_NOMEM;
170029      sqlite3Fts5ParseNodeFree(sParse.pExpr);
170030    }else{
170031      pNew->pRoot = sParse.pExpr;
170032      pNew->pIndex = 0;
170033      pNew->apExprPhrase = sParse.apPhrase;
170034      pNew->nPhrase = sParse.nPhrase;
170035      sParse.apPhrase = 0;
170036    }
170037  }
170038
170039  sqlite3_free(sParse.apPhrase);
170040  *pzErr = sParse.zErr;
170041  return sParse.rc;
170042}
170043
170044/*
170045** Free the expression node object passed as the only argument.
170046*/
170047static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
170048  if( p ){
170049    int i;
170050    for(i=0; i<p->nChild; i++){
170051      sqlite3Fts5ParseNodeFree(p->apChild[i]);
170052    }
170053    sqlite3Fts5ParseNearsetFree(p->pNear);
170054    sqlite3_free(p);
170055  }
170056}
170057
170058/*
170059** Free the expression object passed as the only argument.
170060*/
170061static void sqlite3Fts5ExprFree(Fts5Expr *p){
170062  if( p ){
170063    sqlite3Fts5ParseNodeFree(p->pRoot);
170064    sqlite3_free(p->apExprPhrase);
170065    sqlite3_free(p);
170066  }
170067}
170068
170069/*
170070** Argument pTerm must be a synonym iterator. Return the current rowid
170071** that it points to.
170072*/
170073static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
170074  i64 iRet = 0;
170075  int bRetValid = 0;
170076  Fts5ExprTerm *p;
170077
170078  assert( pTerm->pSynonym );
170079  assert( bDesc==0 || bDesc==1 );
170080  for(p=pTerm; p; p=p->pSynonym){
170081    if( 0==sqlite3Fts5IterEof(p->pIter) ){
170082      i64 iRowid = sqlite3Fts5IterRowid(p->pIter);
170083      if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
170084        iRet = iRowid;
170085        bRetValid = 1;
170086      }
170087    }
170088  }
170089
170090  if( pbEof && bRetValid==0 ) *pbEof = 1;
170091  return iRet;
170092}
170093
170094/*
170095** Argument pTerm must be a synonym iterator.
170096*/
170097static int fts5ExprSynonymPoslist(
170098  Fts5ExprTerm *pTerm,
170099  Fts5Colset *pColset,
170100  i64 iRowid,
170101  int *pbDel,                     /* OUT: Caller should sqlite3_free(*pa) */
170102  u8 **pa, int *pn
170103){
170104  Fts5PoslistReader aStatic[4];
170105  Fts5PoslistReader *aIter = aStatic;
170106  int nIter = 0;
170107  int nAlloc = 4;
170108  int rc = SQLITE_OK;
170109  Fts5ExprTerm *p;
170110
170111  assert( pTerm->pSynonym );
170112  for(p=pTerm; p; p=p->pSynonym){
170113    Fts5IndexIter *pIter = p->pIter;
170114    if( sqlite3Fts5IterEof(pIter)==0 && sqlite3Fts5IterRowid(pIter)==iRowid ){
170115      const u8 *a;
170116      int n;
170117      i64 dummy;
170118      rc = sqlite3Fts5IterPoslist(pIter, pColset, &a, &n, &dummy);
170119      if( rc!=SQLITE_OK ) goto synonym_poslist_out;
170120      if( nIter==nAlloc ){
170121        int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
170122        Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
170123        if( aNew==0 ){
170124          rc = SQLITE_NOMEM;
170125          goto synonym_poslist_out;
170126        }
170127        memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
170128        nAlloc = nAlloc*2;
170129        if( aIter!=aStatic ) sqlite3_free(aIter);
170130        aIter = aNew;
170131      }
170132      sqlite3Fts5PoslistReaderInit(a, n, &aIter[nIter]);
170133      assert( aIter[nIter].bEof==0 );
170134      nIter++;
170135    }
170136  }
170137
170138  assert( *pbDel==0 );
170139  if( nIter==1 ){
170140    *pa = (u8*)aIter[0].a;
170141    *pn = aIter[0].n;
170142  }else{
170143    Fts5PoslistWriter writer = {0};
170144    Fts5Buffer buf = {0,0,0};
170145    i64 iPrev = -1;
170146    while( 1 ){
170147      int i;
170148      i64 iMin = FTS5_LARGEST_INT64;
170149      for(i=0; i<nIter; i++){
170150        if( aIter[i].bEof==0 ){
170151          if( aIter[i].iPos==iPrev ){
170152            if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
170153          }
170154          if( aIter[i].iPos<iMin ){
170155            iMin = aIter[i].iPos;
170156          }
170157        }
170158      }
170159      if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
170160      rc = sqlite3Fts5PoslistWriterAppend(&buf, &writer, iMin);
170161      iPrev = iMin;
170162    }
170163    if( rc ){
170164      sqlite3_free(buf.p);
170165    }else{
170166      *pa = buf.p;
170167      *pn = buf.n;
170168      *pbDel = 1;
170169    }
170170  }
170171
170172 synonym_poslist_out:
170173  if( aIter!=aStatic ) sqlite3_free(aIter);
170174  return rc;
170175}
170176
170177
170178/*
170179** All individual term iterators in pPhrase are guaranteed to be valid and
170180** pointing to the same rowid when this function is called. This function
170181** checks if the current rowid really is a match, and if so populates
170182** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
170183** is set to true if this is really a match, or false otherwise.
170184**
170185** SQLITE_OK is returned if an error occurs, or an SQLite error code
170186** otherwise. It is not considered an error code if the current rowid is
170187** not a match.
170188*/
170189static int fts5ExprPhraseIsMatch(
170190  Fts5ExprNode *pNode,            /* Node pPhrase belongs to */
170191  Fts5Colset *pColset,            /* Restrict matches to these columns */
170192  Fts5ExprPhrase *pPhrase,        /* Phrase object to initialize */
170193  int *pbMatch                    /* OUT: Set to true if really a match */
170194){
170195  Fts5PoslistWriter writer = {0};
170196  Fts5PoslistReader aStatic[4];
170197  Fts5PoslistReader *aIter = aStatic;
170198  int i;
170199  int rc = SQLITE_OK;
170200
170201  fts5BufferZero(&pPhrase->poslist);
170202
170203  /* If the aStatic[] array is not large enough, allocate a large array
170204  ** using sqlite3_malloc(). This approach could be improved upon. */
170205  if( pPhrase->nTerm>(sizeof(aStatic) / sizeof(aStatic[0])) ){
170206    int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
170207    aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
170208    if( !aIter ) return SQLITE_NOMEM;
170209  }
170210  memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
170211
170212  /* Initialize a term iterator for each term in the phrase */
170213  for(i=0; i<pPhrase->nTerm; i++){
170214    Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
170215    i64 dummy;
170216    int n = 0;
170217    int bFlag = 0;
170218    const u8 *a = 0;
170219    if( pTerm->pSynonym ){
170220      rc = fts5ExprSynonymPoslist(
170221          pTerm, pColset, pNode->iRowid, &bFlag, (u8**)&a, &n
170222      );
170223    }else{
170224      rc = sqlite3Fts5IterPoslist(pTerm->pIter, pColset, &a, &n, &dummy);
170225    }
170226    if( rc!=SQLITE_OK ) goto ismatch_out;
170227    sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
170228    aIter[i].bFlag = bFlag;
170229    if( aIter[i].bEof ) goto ismatch_out;
170230  }
170231
170232  while( 1 ){
170233    int bMatch;
170234    i64 iPos = aIter[0].iPos;
170235    do {
170236      bMatch = 1;
170237      for(i=0; i<pPhrase->nTerm; i++){
170238        Fts5PoslistReader *pPos = &aIter[i];
170239        i64 iAdj = iPos + i;
170240        if( pPos->iPos!=iAdj ){
170241          bMatch = 0;
170242          while( pPos->iPos<iAdj ){
170243            if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
170244          }
170245          if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
170246        }
170247      }
170248    }while( bMatch==0 );
170249
170250    /* Append position iPos to the output */
170251    rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
170252    if( rc!=SQLITE_OK ) goto ismatch_out;
170253
170254    for(i=0; i<pPhrase->nTerm; i++){
170255      if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
170256    }
170257  }
170258
170259 ismatch_out:
170260  *pbMatch = (pPhrase->poslist.n>0);
170261  for(i=0; i<pPhrase->nTerm; i++){
170262    if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
170263  }
170264  if( aIter!=aStatic ) sqlite3_free(aIter);
170265  return rc;
170266}
170267
170268typedef struct Fts5LookaheadReader Fts5LookaheadReader;
170269struct Fts5LookaheadReader {
170270  const u8 *a;                    /* Buffer containing position list */
170271  int n;                          /* Size of buffer a[] in bytes */
170272  int i;                          /* Current offset in position list */
170273  i64 iPos;                       /* Current position */
170274  i64 iLookahead;                 /* Next position */
170275};
170276
170277#define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
170278
170279static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
170280  p->iPos = p->iLookahead;
170281  if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
170282    p->iLookahead = FTS5_LOOKAHEAD_EOF;
170283  }
170284  return (p->iPos==FTS5_LOOKAHEAD_EOF);
170285}
170286
170287static int fts5LookaheadReaderInit(
170288  const u8 *a, int n,             /* Buffer to read position list from */
170289  Fts5LookaheadReader *p          /* Iterator object to initialize */
170290){
170291  memset(p, 0, sizeof(Fts5LookaheadReader));
170292  p->a = a;
170293  p->n = n;
170294  fts5LookaheadReaderNext(p);
170295  return fts5LookaheadReaderNext(p);
170296}
170297
170298#if 0
170299static int fts5LookaheadReaderEof(Fts5LookaheadReader *p){
170300  return (p->iPos==FTS5_LOOKAHEAD_EOF);
170301}
170302#endif
170303
170304typedef struct Fts5NearTrimmer Fts5NearTrimmer;
170305struct Fts5NearTrimmer {
170306  Fts5LookaheadReader reader;     /* Input iterator */
170307  Fts5PoslistWriter writer;       /* Writer context */
170308  Fts5Buffer *pOut;               /* Output poslist */
170309};
170310
170311/*
170312** The near-set object passed as the first argument contains more than
170313** one phrase. All phrases currently point to the same row. The
170314** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
170315** tests if the current row contains instances of each phrase sufficiently
170316** close together to meet the NEAR constraint. Non-zero is returned if it
170317** does, or zero otherwise.
170318**
170319** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
170320** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
170321** occurs within this function (*pRc) is set accordingly before returning.
170322** The return value is undefined in both these cases.
170323**
170324** If no error occurs and non-zero (a match) is returned, the position-list
170325** of each phrase object is edited to contain only those entries that
170326** meet the constraint before returning.
170327*/
170328static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
170329  Fts5NearTrimmer aStatic[4];
170330  Fts5NearTrimmer *a = aStatic;
170331  Fts5ExprPhrase **apPhrase = pNear->apPhrase;
170332
170333  int i;
170334  int rc = *pRc;
170335  int bMatch;
170336
170337  assert( pNear->nPhrase>1 );
170338
170339  /* If the aStatic[] array is not large enough, allocate a large array
170340  ** using sqlite3_malloc(). This approach could be improved upon. */
170341  if( pNear->nPhrase>(sizeof(aStatic) / sizeof(aStatic[0])) ){
170342    int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
170343    a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
170344  }else{
170345    memset(aStatic, 0, sizeof(aStatic));
170346  }
170347  if( rc!=SQLITE_OK ){
170348    *pRc = rc;
170349    return 0;
170350  }
170351
170352  /* Initialize a lookahead iterator for each phrase. After passing the
170353  ** buffer and buffer size to the lookaside-reader init function, zero
170354  ** the phrase poslist buffer. The new poslist for the phrase (containing
170355  ** the same entries as the original with some entries removed on account
170356  ** of the NEAR constraint) is written over the original even as it is
170357  ** being read. This is safe as the entries for the new poslist are a
170358  ** subset of the old, so it is not possible for data yet to be read to
170359  ** be overwritten.  */
170360  for(i=0; i<pNear->nPhrase; i++){
170361    Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
170362    fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
170363    pPoslist->n = 0;
170364    a[i].pOut = pPoslist;
170365  }
170366
170367  while( 1 ){
170368    int iAdv;
170369    i64 iMin;
170370    i64 iMax;
170371
170372    /* This block advances the phrase iterators until they point to a set of
170373    ** entries that together comprise a match.  */
170374    iMax = a[0].reader.iPos;
170375    do {
170376      bMatch = 1;
170377      for(i=0; i<pNear->nPhrase; i++){
170378        Fts5LookaheadReader *pPos = &a[i].reader;
170379        iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
170380        if( pPos->iPos<iMin || pPos->iPos>iMax ){
170381          bMatch = 0;
170382          while( pPos->iPos<iMin ){
170383            if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
170384          }
170385          if( pPos->iPos>iMax ) iMax = pPos->iPos;
170386        }
170387      }
170388    }while( bMatch==0 );
170389
170390    /* Add an entry to each output position list */
170391    for(i=0; i<pNear->nPhrase; i++){
170392      i64 iPos = a[i].reader.iPos;
170393      Fts5PoslistWriter *pWriter = &a[i].writer;
170394      if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
170395        sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
170396      }
170397    }
170398
170399    iAdv = 0;
170400    iMin = a[0].reader.iLookahead;
170401    for(i=0; i<pNear->nPhrase; i++){
170402      if( a[i].reader.iLookahead < iMin ){
170403        iMin = a[i].reader.iLookahead;
170404        iAdv = i;
170405      }
170406    }
170407    if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
170408  }
170409
170410  ismatch_out: {
170411    int bRet = a[0].pOut->n>0;
170412    *pRc = rc;
170413    if( a!=aStatic ) sqlite3_free(a);
170414    return bRet;
170415  }
170416}
170417
170418/*
170419** Advance the first term iterator in the first phrase of pNear. Set output
170420** variable *pbEof to true if it reaches EOF or if an error occurs.
170421**
170422** Return SQLITE_OK if successful, or an SQLite error code if an error
170423** occurs.
170424*/
170425static int fts5ExprNearAdvanceFirst(
170426  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
170427  Fts5ExprNode *pNode,            /* FTS5_STRING or FTS5_TERM node */
170428  int bFromValid,
170429  i64 iFrom
170430){
170431  Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
170432  int rc = SQLITE_OK;
170433
170434  if( pTerm->pSynonym ){
170435    int bEof = 1;
170436    Fts5ExprTerm *p;
170437
170438    /* Find the firstest rowid any synonym points to. */
170439    i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
170440
170441    /* Advance each iterator that currently points to iRowid. Or, if iFrom
170442    ** is valid - each iterator that points to a rowid before iFrom.  */
170443    for(p=pTerm; p; p=p->pSynonym){
170444      if( sqlite3Fts5IterEof(p->pIter)==0 ){
170445        i64 ii = sqlite3Fts5IterRowid(p->pIter);
170446        if( ii==iRowid
170447         || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
170448        ){
170449          if( bFromValid ){
170450            rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
170451          }else{
170452            rc = sqlite3Fts5IterNext(p->pIter);
170453          }
170454          if( rc!=SQLITE_OK ) break;
170455          if( sqlite3Fts5IterEof(p->pIter)==0 ){
170456            bEof = 0;
170457          }
170458        }else{
170459          bEof = 0;
170460        }
170461      }
170462    }
170463
170464    /* Set the EOF flag if either all synonym iterators are at EOF or an
170465    ** error has occurred.  */
170466    pNode->bEof = (rc || bEof);
170467  }else{
170468    Fts5IndexIter *pIter = pTerm->pIter;
170469
170470    assert( Fts5NodeIsString(pNode) );
170471    if( bFromValid ){
170472      rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
170473    }else{
170474      rc = sqlite3Fts5IterNext(pIter);
170475    }
170476
170477    pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
170478  }
170479
170480  return rc;
170481}
170482
170483/*
170484** Advance iterator pIter until it points to a value equal to or laster
170485** than the initial value of *piLast. If this means the iterator points
170486** to a value laster than *piLast, update *piLast to the new lastest value.
170487**
170488** If the iterator reaches EOF, set *pbEof to true before returning. If
170489** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
170490** are set, return a non-zero value. Otherwise, return zero.
170491*/
170492static int fts5ExprAdvanceto(
170493  Fts5IndexIter *pIter,           /* Iterator to advance */
170494  int bDesc,                      /* True if iterator is "rowid DESC" */
170495  i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
170496  int *pRc,                       /* OUT: Error code */
170497  int *pbEof                      /* OUT: Set to true if EOF */
170498){
170499  i64 iLast = *piLast;
170500  i64 iRowid;
170501
170502  iRowid = sqlite3Fts5IterRowid(pIter);
170503  if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
170504    int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
170505    if( rc || sqlite3Fts5IterEof(pIter) ){
170506      *pRc = rc;
170507      *pbEof = 1;
170508      return 1;
170509    }
170510    iRowid = sqlite3Fts5IterRowid(pIter);
170511    assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
170512  }
170513  *piLast = iRowid;
170514
170515  return 0;
170516}
170517
170518static int fts5ExprSynonymAdvanceto(
170519  Fts5ExprTerm *pTerm,            /* Term iterator to advance */
170520  int bDesc,                      /* True if iterator is "rowid DESC" */
170521  i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
170522  int *pRc                        /* OUT: Error code */
170523){
170524  int rc = SQLITE_OK;
170525  i64 iLast = *piLast;
170526  Fts5ExprTerm *p;
170527  int bEof = 0;
170528
170529  for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
170530    if( sqlite3Fts5IterEof(p->pIter)==0 ){
170531      i64 iRowid = sqlite3Fts5IterRowid(p->pIter);
170532      if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
170533        rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
170534      }
170535    }
170536  }
170537
170538  if( rc!=SQLITE_OK ){
170539    *pRc = rc;
170540    bEof = 1;
170541  }else{
170542    *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
170543  }
170544  return bEof;
170545}
170546
170547
170548static int fts5ExprNearTest(
170549  int *pRc,
170550  Fts5Expr *pExpr,                /* Expression that pNear is a part of */
170551  Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_STRING) */
170552){
170553  Fts5ExprNearset *pNear = pNode->pNear;
170554  int rc = *pRc;
170555  int i;
170556
170557  /* Check that each phrase in the nearset matches the current row.
170558  ** Populate the pPhrase->poslist buffers at the same time. If any
170559  ** phrase is not a match, break out of the loop early.  */
170560  for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
170561    Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
170562    if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym || pNear->pColset ){
170563      int bMatch = 0;
170564      rc = fts5ExprPhraseIsMatch(pNode, pNear->pColset, pPhrase, &bMatch);
170565      if( bMatch==0 ) break;
170566    }else{
170567      rc = sqlite3Fts5IterPoslistBuffer(
170568          pPhrase->aTerm[0].pIter, &pPhrase->poslist
170569      );
170570    }
170571  }
170572
170573  *pRc = rc;
170574  if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
170575    return 1;
170576  }
170577
170578  return 0;
170579}
170580
170581static int fts5ExprTokenTest(
170582  Fts5Expr *pExpr,                /* Expression that pNear is a part of */
170583  Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_TERM) */
170584){
170585  /* As this "NEAR" object is actually a single phrase that consists
170586  ** of a single term only, grab pointers into the poslist managed by the
170587  ** fts5_index.c iterator object. This is much faster than synthesizing
170588  ** a new poslist the way we have to for more complicated phrase or NEAR
170589  ** expressions.  */
170590  Fts5ExprNearset *pNear = pNode->pNear;
170591  Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
170592  Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
170593  Fts5Colset *pColset = pNear->pColset;
170594  int rc;
170595
170596  assert( pNode->eType==FTS5_TERM );
170597  assert( pNear->nPhrase==1 && pPhrase->nTerm==1 );
170598  assert( pPhrase->aTerm[0].pSynonym==0 );
170599
170600  rc = sqlite3Fts5IterPoslist(pIter, pColset,
170601      (const u8**)&pPhrase->poslist.p, &pPhrase->poslist.n, &pNode->iRowid
170602  );
170603  pNode->bNomatch = (pPhrase->poslist.n==0);
170604  return rc;
170605}
170606
170607/*
170608** All individual term iterators in pNear are guaranteed to be valid when
170609** this function is called. This function checks if all term iterators
170610** point to the same rowid, and if not, advances them until they do.
170611** If an EOF is reached before this happens, *pbEof is set to true before
170612** returning.
170613**
170614** SQLITE_OK is returned if an error occurs, or an SQLite error code
170615** otherwise. It is not considered an error code if an iterator reaches
170616** EOF.
170617*/
170618static int fts5ExprNearNextMatch(
170619  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
170620  Fts5ExprNode *pNode
170621){
170622  Fts5ExprNearset *pNear = pNode->pNear;
170623  Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
170624  int rc = SQLITE_OK;
170625  i64 iLast;                      /* Lastest rowid any iterator points to */
170626  int i, j;                       /* Phrase and token index, respectively */
170627  int bMatch;                     /* True if all terms are at the same rowid */
170628  const int bDesc = pExpr->bDesc;
170629
170630  /* Check that this node should not be FTS5_TERM */
170631  assert( pNear->nPhrase>1
170632       || pNear->apPhrase[0]->nTerm>1
170633       || pNear->apPhrase[0]->aTerm[0].pSynonym
170634  );
170635
170636  /* Initialize iLast, the "lastest" rowid any iterator points to. If the
170637  ** iterator skips through rowids in the default ascending order, this means
170638  ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
170639  ** means the minimum rowid.  */
170640  if( pLeft->aTerm[0].pSynonym ){
170641    iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
170642  }else{
170643    iLast = sqlite3Fts5IterRowid(pLeft->aTerm[0].pIter);
170644  }
170645
170646  do {
170647    bMatch = 1;
170648    for(i=0; i<pNear->nPhrase; i++){
170649      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
170650      for(j=0; j<pPhrase->nTerm; j++){
170651        Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
170652        if( pTerm->pSynonym ){
170653          i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
170654          if( iRowid==iLast ) continue;
170655          bMatch = 0;
170656          if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
170657            pNode->bEof = 1;
170658            return rc;
170659          }
170660        }else{
170661          Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
170662          i64 iRowid = sqlite3Fts5IterRowid(pIter);
170663          if( iRowid==iLast ) continue;
170664          bMatch = 0;
170665          if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
170666            return rc;
170667          }
170668        }
170669      }
170670    }
170671  }while( bMatch==0 );
170672
170673  pNode->iRowid = iLast;
170674  pNode->bNomatch = (0==fts5ExprNearTest(&rc, pExpr, pNode));
170675
170676  return rc;
170677}
170678
170679/*
170680** Initialize all term iterators in the pNear object. If any term is found
170681** to match no documents at all, return immediately without initializing any
170682** further iterators.
170683*/
170684static int fts5ExprNearInitAll(
170685  Fts5Expr *pExpr,
170686  Fts5ExprNode *pNode
170687){
170688  Fts5ExprNearset *pNear = pNode->pNear;
170689  int i, j;
170690  int rc = SQLITE_OK;
170691
170692  for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
170693    Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
170694    for(j=0; j<pPhrase->nTerm; j++){
170695      Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
170696      Fts5ExprTerm *p;
170697      int bEof = 1;
170698
170699      for(p=pTerm; p && rc==SQLITE_OK; p=p->pSynonym){
170700        if( p->pIter ){
170701          sqlite3Fts5IterClose(p->pIter);
170702          p->pIter = 0;
170703        }
170704        rc = sqlite3Fts5IndexQuery(
170705            pExpr->pIndex, p->zTerm, strlen(p->zTerm),
170706            (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
170707            (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
170708            pNear->pColset,
170709            &p->pIter
170710        );
170711        assert( rc==SQLITE_OK || p->pIter==0 );
170712        if( p->pIter && 0==sqlite3Fts5IterEof(p->pIter) ){
170713          bEof = 0;
170714        }
170715      }
170716
170717      if( bEof ){
170718        pNode->bEof = 1;
170719        return rc;
170720      }
170721    }
170722  }
170723
170724  return rc;
170725}
170726
170727/* fts5ExprNodeNext() calls fts5ExprNodeNextMatch(). And vice-versa. */
170728static int fts5ExprNodeNextMatch(Fts5Expr*, Fts5ExprNode*);
170729
170730
170731/*
170732** If pExpr is an ASC iterator, this function returns a value with the
170733** same sign as:
170734**
170735**   (iLhs - iRhs)
170736**
170737** Otherwise, if this is a DESC iterator, the opposite is returned:
170738**
170739**   (iRhs - iLhs)
170740*/
170741static int fts5RowidCmp(
170742  Fts5Expr *pExpr,
170743  i64 iLhs,
170744  i64 iRhs
170745){
170746  assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
170747  if( pExpr->bDesc==0 ){
170748    if( iLhs<iRhs ) return -1;
170749    return (iLhs > iRhs);
170750  }else{
170751    if( iLhs>iRhs ) return -1;
170752    return (iLhs < iRhs);
170753  }
170754}
170755
170756static void fts5ExprSetEof(Fts5ExprNode *pNode){
170757  int i;
170758  pNode->bEof = 1;
170759  for(i=0; i<pNode->nChild; i++){
170760    fts5ExprSetEof(pNode->apChild[i]);
170761  }
170762}
170763
170764static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
170765  if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
170766    Fts5ExprNearset *pNear = pNode->pNear;
170767    int i;
170768    for(i=0; i<pNear->nPhrase; i++){
170769      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
170770      pPhrase->poslist.n = 0;
170771    }
170772  }else{
170773    int i;
170774    for(i=0; i<pNode->nChild; i++){
170775      fts5ExprNodeZeroPoslist(pNode->apChild[i]);
170776    }
170777  }
170778}
170779
170780
170781static int fts5ExprNodeNext(Fts5Expr*, Fts5ExprNode*, int, i64);
170782
170783/*
170784** Argument pNode is an FTS5_AND node.
170785*/
170786static int fts5ExprAndNextRowid(
170787  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
170788  Fts5ExprNode *pAnd              /* FTS5_AND node to advance */
170789){
170790  int iChild;
170791  i64 iLast = pAnd->iRowid;
170792  int rc = SQLITE_OK;
170793  int bMatch;
170794
170795  assert( pAnd->bEof==0 );
170796  do {
170797    pAnd->bNomatch = 0;
170798    bMatch = 1;
170799    for(iChild=0; iChild<pAnd->nChild; iChild++){
170800      Fts5ExprNode *pChild = pAnd->apChild[iChild];
170801      if( 0 && pChild->eType==FTS5_STRING ){
170802        /* TODO */
170803      }else{
170804        int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
170805        if( cmp>0 ){
170806          /* Advance pChild until it points to iLast or laster */
170807          rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
170808          if( rc!=SQLITE_OK ) return rc;
170809        }
170810      }
170811
170812      /* If the child node is now at EOF, so is the parent AND node. Otherwise,
170813      ** the child node is guaranteed to have advanced at least as far as
170814      ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
170815      ** new lastest rowid seen so far.  */
170816      assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
170817      if( pChild->bEof ){
170818        fts5ExprSetEof(pAnd);
170819        bMatch = 1;
170820        break;
170821      }else if( iLast!=pChild->iRowid ){
170822        bMatch = 0;
170823        iLast = pChild->iRowid;
170824      }
170825
170826      if( pChild->bNomatch ){
170827        pAnd->bNomatch = 1;
170828      }
170829    }
170830  }while( bMatch==0 );
170831
170832  if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
170833    fts5ExprNodeZeroPoslist(pAnd);
170834  }
170835  pAnd->iRowid = iLast;
170836  return SQLITE_OK;
170837}
170838
170839
170840/*
170841** Compare the values currently indicated by the two nodes as follows:
170842**
170843**    res = (*p1) - (*p2)
170844**
170845** Nodes that point to values that come later in the iteration order are
170846** considered to be larger. Nodes at EOF are the largest of all.
170847**
170848** This means that if the iteration order is ASC, then numerically larger
170849** rowids are considered larger. Or if it is the default DESC, numerically
170850** smaller rowids are larger.
170851*/
170852static int fts5NodeCompare(
170853  Fts5Expr *pExpr,
170854  Fts5ExprNode *p1,
170855  Fts5ExprNode *p2
170856){
170857  if( p2->bEof ) return -1;
170858  if( p1->bEof ) return +1;
170859  return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
170860}
170861
170862/*
170863** Advance node iterator pNode, part of expression pExpr. If argument
170864** bFromValid is zero, then pNode is advanced exactly once. Or, if argument
170865** bFromValid is non-zero, then pNode is advanced until it is at or past
170866** rowid value iFrom. Whether "past" means "less than" or "greater than"
170867** depends on whether this is an ASC or DESC iterator.
170868*/
170869static int fts5ExprNodeNext(
170870  Fts5Expr *pExpr,
170871  Fts5ExprNode *pNode,
170872  int bFromValid,
170873  i64 iFrom
170874){
170875  int rc = SQLITE_OK;
170876
170877  if( pNode->bEof==0 ){
170878    switch( pNode->eType ){
170879      case FTS5_STRING: {
170880        rc = fts5ExprNearAdvanceFirst(pExpr, pNode, bFromValid, iFrom);
170881        break;
170882      };
170883
170884      case FTS5_TERM: {
170885        Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
170886        if( bFromValid ){
170887          rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
170888        }else{
170889          rc = sqlite3Fts5IterNext(pIter);
170890        }
170891        if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
170892          assert( rc==SQLITE_OK );
170893          rc = fts5ExprTokenTest(pExpr, pNode);
170894        }else{
170895          pNode->bEof = 1;
170896        }
170897        return rc;
170898      };
170899
170900      case FTS5_AND: {
170901        Fts5ExprNode *pLeft = pNode->apChild[0];
170902        rc = fts5ExprNodeNext(pExpr, pLeft, bFromValid, iFrom);
170903        break;
170904      }
170905
170906      case FTS5_OR: {
170907        int i;
170908        i64 iLast = pNode->iRowid;
170909
170910        for(i=0; rc==SQLITE_OK && i<pNode->nChild; i++){
170911          Fts5ExprNode *p1 = pNode->apChild[i];
170912          assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
170913          if( p1->bEof==0 ){
170914            if( (p1->iRowid==iLast)
170915             || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
170916            ){
170917              rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
170918            }
170919          }
170920        }
170921
170922        break;
170923      }
170924
170925      default: assert( pNode->eType==FTS5_NOT ); {
170926        assert( pNode->nChild==2 );
170927        rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
170928        break;
170929      }
170930    }
170931
170932    if( rc==SQLITE_OK ){
170933      rc = fts5ExprNodeNextMatch(pExpr, pNode);
170934    }
170935  }
170936
170937  /* Assert that if bFromValid was true, either:
170938  **
170939  **   a) an error occurred, or
170940  **   b) the node is now at EOF, or
170941  **   c) the node is now at or past rowid iFrom.
170942  */
170943  assert( bFromValid==0
170944      || rc!=SQLITE_OK                                                  /* a */
170945      || pNode->bEof                                                    /* b */
170946      || pNode->iRowid==iFrom || pExpr->bDesc==(pNode->iRowid<iFrom)    /* c */
170947  );
170948
170949  return rc;
170950}
170951
170952
170953/*
170954** If pNode currently points to a match, this function returns SQLITE_OK
170955** without modifying it. Otherwise, pNode is advanced until it does point
170956** to a match or EOF is reached.
170957*/
170958static int fts5ExprNodeNextMatch(
170959  Fts5Expr *pExpr,                /* Expression of which pNode is a part */
170960  Fts5ExprNode *pNode             /* Expression node to test */
170961){
170962  int rc = SQLITE_OK;
170963  if( pNode->bEof==0 ){
170964    switch( pNode->eType ){
170965
170966      case FTS5_STRING: {
170967        /* Advance the iterators until they all point to the same rowid */
170968        rc = fts5ExprNearNextMatch(pExpr, pNode);
170969        break;
170970      }
170971
170972      case FTS5_TERM: {
170973        rc = fts5ExprTokenTest(pExpr, pNode);
170974        break;
170975      }
170976
170977      case FTS5_AND: {
170978        rc = fts5ExprAndNextRowid(pExpr, pNode);
170979        break;
170980      }
170981
170982      case FTS5_OR: {
170983        Fts5ExprNode *pNext = pNode->apChild[0];
170984        int i;
170985
170986        for(i=1; i<pNode->nChild; i++){
170987          Fts5ExprNode *pChild = pNode->apChild[i];
170988          int cmp = fts5NodeCompare(pExpr, pNext, pChild);
170989          if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
170990            pNext = pChild;
170991          }
170992        }
170993        pNode->iRowid = pNext->iRowid;
170994        pNode->bEof = pNext->bEof;
170995        pNode->bNomatch = pNext->bNomatch;
170996        break;
170997      }
170998
170999      default: assert( pNode->eType==FTS5_NOT ); {
171000        Fts5ExprNode *p1 = pNode->apChild[0];
171001        Fts5ExprNode *p2 = pNode->apChild[1];
171002        assert( pNode->nChild==2 );
171003
171004        while( rc==SQLITE_OK && p1->bEof==0 ){
171005          int cmp = fts5NodeCompare(pExpr, p1, p2);
171006          if( cmp>0 ){
171007            rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
171008            cmp = fts5NodeCompare(pExpr, p1, p2);
171009          }
171010          assert( rc!=SQLITE_OK || cmp<=0 );
171011          if( cmp || p2->bNomatch ) break;
171012          rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
171013        }
171014        pNode->bEof = p1->bEof;
171015        pNode->iRowid = p1->iRowid;
171016        break;
171017      }
171018    }
171019  }
171020  return rc;
171021}
171022
171023
171024/*
171025** Set node pNode, which is part of expression pExpr, to point to the first
171026** match. If there are no matches, set the Node.bEof flag to indicate EOF.
171027**
171028** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
171029** It is not an error if there are no matches.
171030*/
171031static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
171032  int rc = SQLITE_OK;
171033  pNode->bEof = 0;
171034
171035  if( Fts5NodeIsString(pNode) ){
171036    /* Initialize all term iterators in the NEAR object. */
171037    rc = fts5ExprNearInitAll(pExpr, pNode);
171038  }else{
171039    int i;
171040    for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
171041      rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
171042    }
171043    pNode->iRowid = pNode->apChild[0]->iRowid;
171044  }
171045
171046  if( rc==SQLITE_OK ){
171047    rc = fts5ExprNodeNextMatch(pExpr, pNode);
171048  }
171049  return rc;
171050}
171051
171052
171053/*
171054** Begin iterating through the set of documents in index pIdx matched by
171055** the MATCH expression passed as the first argument. If the "bDesc"
171056** parameter is passed a non-zero value, iteration is in descending rowid
171057** order. Or, if it is zero, in ascending order.
171058**
171059** If iterating in ascending rowid order (bDesc==0), the first document
171060** visited is that with the smallest rowid that is larger than or equal
171061** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
171062** then the first document visited must have a rowid smaller than or
171063** equal to iFirst.
171064**
171065** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
171066** is not considered an error if the query does not match any documents.
171067*/
171068static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
171069  Fts5ExprNode *pRoot = p->pRoot;
171070  int rc = SQLITE_OK;
171071  if( pRoot ){
171072    p->pIndex = pIdx;
171073    p->bDesc = bDesc;
171074    rc = fts5ExprNodeFirst(p, pRoot);
171075
171076    /* If not at EOF but the current rowid occurs earlier than iFirst in
171077    ** the iteration order, move to document iFirst or later. */
171078    if( pRoot->bEof==0 && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0 ){
171079      rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
171080    }
171081
171082    /* If the iterator is not at a real match, skip forward until it is. */
171083    while( pRoot->bNomatch && rc==SQLITE_OK && pRoot->bEof==0 ){
171084      rc = fts5ExprNodeNext(p, pRoot, 0, 0);
171085    }
171086  }
171087  return rc;
171088}
171089
171090/*
171091** Move to the next document
171092**
171093** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
171094** is not considered an error if the query does not match any documents.
171095*/
171096static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
171097  int rc;
171098  Fts5ExprNode *pRoot = p->pRoot;
171099  do {
171100    rc = fts5ExprNodeNext(p, pRoot, 0, 0);
171101  }while( pRoot->bNomatch && pRoot->bEof==0 && rc==SQLITE_OK );
171102  if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
171103    pRoot->bEof = 1;
171104  }
171105  return rc;
171106}
171107
171108static int sqlite3Fts5ExprEof(Fts5Expr *p){
171109  return (p->pRoot==0 || p->pRoot->bEof);
171110}
171111
171112static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
171113  return p->pRoot->iRowid;
171114}
171115
171116static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
171117  int rc = SQLITE_OK;
171118  *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
171119  return rc;
171120}
171121
171122/*
171123** Free the phrase object passed as the only argument.
171124*/
171125static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
171126  if( pPhrase ){
171127    int i;
171128    for(i=0; i<pPhrase->nTerm; i++){
171129      Fts5ExprTerm *pSyn;
171130      Fts5ExprTerm *pNext;
171131      Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
171132      sqlite3_free(pTerm->zTerm);
171133      sqlite3Fts5IterClose(pTerm->pIter);
171134
171135      for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
171136        pNext = pSyn->pSynonym;
171137        sqlite3Fts5IterClose(pSyn->pIter);
171138        sqlite3_free(pSyn);
171139      }
171140    }
171141    if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
171142    sqlite3_free(pPhrase);
171143  }
171144}
171145
171146/*
171147** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
171148** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
171149** appended to it and the results returned.
171150**
171151** If an OOM error occurs, both the pNear and pPhrase objects are freed and
171152** NULL returned.
171153*/
171154static Fts5ExprNearset *sqlite3Fts5ParseNearset(
171155  Fts5Parse *pParse,              /* Parse context */
171156  Fts5ExprNearset *pNear,         /* Existing nearset, or NULL */
171157  Fts5ExprPhrase *pPhrase         /* Recently parsed phrase */
171158){
171159  const int SZALLOC = 8;
171160  Fts5ExprNearset *pRet = 0;
171161
171162  if( pParse->rc==SQLITE_OK ){
171163    if( pPhrase==0 ){
171164      return pNear;
171165    }
171166    if( pNear==0 ){
171167      int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
171168      pRet = sqlite3_malloc(nByte);
171169      if( pRet==0 ){
171170        pParse->rc = SQLITE_NOMEM;
171171      }else{
171172        memset(pRet, 0, nByte);
171173      }
171174    }else if( (pNear->nPhrase % SZALLOC)==0 ){
171175      int nNew = pNear->nPhrase + SZALLOC;
171176      int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
171177
171178      pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
171179      if( pRet==0 ){
171180        pParse->rc = SQLITE_NOMEM;
171181      }
171182    }else{
171183      pRet = pNear;
171184    }
171185  }
171186
171187  if( pRet==0 ){
171188    assert( pParse->rc!=SQLITE_OK );
171189    sqlite3Fts5ParseNearsetFree(pNear);
171190    sqlite3Fts5ParsePhraseFree(pPhrase);
171191  }else{
171192    pRet->apPhrase[pRet->nPhrase++] = pPhrase;
171193  }
171194  return pRet;
171195}
171196
171197typedef struct TokenCtx TokenCtx;
171198struct TokenCtx {
171199  Fts5ExprPhrase *pPhrase;
171200  int rc;
171201};
171202
171203/*
171204** Callback for tokenizing terms used by ParseTerm().
171205*/
171206static int fts5ParseTokenize(
171207  void *pContext,                 /* Pointer to Fts5InsertCtx object */
171208  int tflags,                     /* Mask of FTS5_TOKEN_* flags */
171209  const char *pToken,             /* Buffer containing token */
171210  int nToken,                     /* Size of token in bytes */
171211  int iUnused1,                   /* Start offset of token */
171212  int iUnused2                    /* End offset of token */
171213){
171214  int rc = SQLITE_OK;
171215  const int SZALLOC = 8;
171216  TokenCtx *pCtx = (TokenCtx*)pContext;
171217  Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
171218
171219  /* If an error has already occurred, this is a no-op */
171220  if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
171221
171222  assert( pPhrase==0 || pPhrase->nTerm>0 );
171223  if( pPhrase && (tflags & FTS5_TOKEN_COLOCATED) ){
171224    Fts5ExprTerm *pSyn;
171225    int nByte = sizeof(Fts5ExprTerm) + nToken+1;
171226    pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
171227    if( pSyn==0 ){
171228      rc = SQLITE_NOMEM;
171229    }else{
171230      memset(pSyn, 0, nByte);
171231      pSyn->zTerm = (char*)&pSyn[1];
171232      memcpy(pSyn->zTerm, pToken, nToken);
171233      pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
171234      pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
171235    }
171236  }else{
171237    Fts5ExprTerm *pTerm;
171238    if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
171239      Fts5ExprPhrase *pNew;
171240      int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
171241
171242      pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase,
171243          sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
171244      );
171245      if( pNew==0 ){
171246        rc = SQLITE_NOMEM;
171247      }else{
171248        if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
171249        pCtx->pPhrase = pPhrase = pNew;
171250        pNew->nTerm = nNew - SZALLOC;
171251      }
171252    }
171253
171254    if( rc==SQLITE_OK ){
171255      pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
171256      memset(pTerm, 0, sizeof(Fts5ExprTerm));
171257      pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
171258    }
171259  }
171260
171261  pCtx->rc = rc;
171262  return rc;
171263}
171264
171265
171266/*
171267** Free the phrase object passed as the only argument.
171268*/
171269static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
171270  fts5ExprPhraseFree(pPhrase);
171271}
171272
171273/*
171274** Free the phrase object passed as the second argument.
171275*/
171276static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
171277  if( pNear ){
171278    int i;
171279    for(i=0; i<pNear->nPhrase; i++){
171280      fts5ExprPhraseFree(pNear->apPhrase[i]);
171281    }
171282    sqlite3_free(pNear->pColset);
171283    sqlite3_free(pNear);
171284  }
171285}
171286
171287static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
171288  assert( pParse->pExpr==0 );
171289  pParse->pExpr = p;
171290}
171291
171292/*
171293** This function is called by the parser to process a string token. The
171294** string may or may not be quoted. In any case it is tokenized and a
171295** phrase object consisting of all tokens returned.
171296*/
171297static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
171298  Fts5Parse *pParse,              /* Parse context */
171299  Fts5ExprPhrase *pAppend,        /* Phrase to append to */
171300  Fts5Token *pToken,              /* String to tokenize */
171301  int bPrefix                     /* True if there is a trailing "*" */
171302){
171303  Fts5Config *pConfig = pParse->pConfig;
171304  TokenCtx sCtx;                  /* Context object passed to callback */
171305  int rc;                         /* Tokenize return code */
171306  char *z = 0;
171307
171308  memset(&sCtx, 0, sizeof(TokenCtx));
171309  sCtx.pPhrase = pAppend;
171310
171311  rc = fts5ParseStringFromToken(pToken, &z);
171312  if( rc==SQLITE_OK ){
171313    int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_QUERY : 0);
171314    int n;
171315    sqlite3Fts5Dequote(z);
171316    n = strlen(z);
171317    rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
171318  }
171319  sqlite3_free(z);
171320  if( rc || (rc = sCtx.rc) ){
171321    pParse->rc = rc;
171322    fts5ExprPhraseFree(sCtx.pPhrase);
171323    sCtx.pPhrase = 0;
171324  }else if( sCtx.pPhrase ){
171325
171326    if( pAppend==0 ){
171327      if( (pParse->nPhrase % 8)==0 ){
171328        int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
171329        Fts5ExprPhrase **apNew;
171330        apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
171331        if( apNew==0 ){
171332          pParse->rc = SQLITE_NOMEM;
171333          fts5ExprPhraseFree(sCtx.pPhrase);
171334          return 0;
171335        }
171336        pParse->apPhrase = apNew;
171337      }
171338      pParse->nPhrase++;
171339    }
171340
171341    pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
171342    assert( sCtx.pPhrase->nTerm>0 );
171343    sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = bPrefix;
171344  }
171345
171346  return sCtx.pPhrase;
171347}
171348
171349/*
171350** Create a new FTS5 expression by cloning phrase iPhrase of the
171351** expression passed as the second argument.
171352*/
171353static int sqlite3Fts5ExprClonePhrase(
171354  Fts5Config *pConfig,
171355  Fts5Expr *pExpr,
171356  int iPhrase,
171357  Fts5Expr **ppNew
171358){
171359  int rc = SQLITE_OK;             /* Return code */
171360  Fts5ExprPhrase *pOrig;          /* The phrase extracted from pExpr */
171361  int i;                          /* Used to iterate through phrase terms */
171362
171363  Fts5Expr *pNew = 0;             /* Expression to return via *ppNew */
171364
171365  TokenCtx sCtx = {0,0};          /* Context object for fts5ParseTokenize */
171366
171367
171368  pOrig = pExpr->apExprPhrase[iPhrase];
171369
171370  pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
171371  if( rc==SQLITE_OK ){
171372    pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
171373        sizeof(Fts5ExprPhrase*));
171374  }
171375  if( rc==SQLITE_OK ){
171376    pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
171377        sizeof(Fts5ExprNode));
171378  }
171379  if( rc==SQLITE_OK ){
171380    pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
171381        sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
171382  }
171383
171384  for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
171385    int tflags = 0;
171386    Fts5ExprTerm *p;
171387    for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
171388      const char *zTerm = p->zTerm;
171389      rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, strlen(zTerm), 0, 0);
171390      tflags = FTS5_TOKEN_COLOCATED;
171391    }
171392    if( rc==SQLITE_OK ){
171393      sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
171394    }
171395  }
171396
171397  if( rc==SQLITE_OK ){
171398    /* All the allocations succeeded. Put the expression object together. */
171399    pNew->pIndex = pExpr->pIndex;
171400    pNew->nPhrase = 1;
171401    pNew->apExprPhrase[0] = sCtx.pPhrase;
171402    pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
171403    pNew->pRoot->pNear->nPhrase = 1;
171404    sCtx.pPhrase->pNode = pNew->pRoot;
171405
171406    if( pOrig->nTerm==1 && pOrig->aTerm[0].pSynonym==0 ){
171407      pNew->pRoot->eType = FTS5_TERM;
171408    }else{
171409      pNew->pRoot->eType = FTS5_STRING;
171410    }
171411  }else{
171412    sqlite3Fts5ExprFree(pNew);
171413    fts5ExprPhraseFree(sCtx.pPhrase);
171414    pNew = 0;
171415  }
171416
171417  *ppNew = pNew;
171418  return rc;
171419}
171420
171421
171422/*
171423** Token pTok has appeared in a MATCH expression where the NEAR operator
171424** is expected. If token pTok does not contain "NEAR", store an error
171425** in the pParse object.
171426*/
171427static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
171428  if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
171429    sqlite3Fts5ParseError(
171430        pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
171431    );
171432  }
171433}
171434
171435static void sqlite3Fts5ParseSetDistance(
171436  Fts5Parse *pParse,
171437  Fts5ExprNearset *pNear,
171438  Fts5Token *p
171439){
171440  int nNear = 0;
171441  int i;
171442  if( p->n ){
171443    for(i=0; i<p->n; i++){
171444      char c = (char)p->p[i];
171445      if( c<'0' || c>'9' ){
171446        sqlite3Fts5ParseError(
171447            pParse, "expected integer, got \"%.*s\"", p->n, p->p
171448        );
171449        return;
171450      }
171451      nNear = nNear * 10 + (p->p[i] - '0');
171452    }
171453  }else{
171454    nNear = FTS5_DEFAULT_NEARDIST;
171455  }
171456  pNear->nNear = nNear;
171457}
171458
171459/*
171460** The second argument passed to this function may be NULL, or it may be
171461** an existing Fts5Colset object. This function returns a pointer to
171462** a new colset object containing the contents of (p) with new value column
171463** number iCol appended.
171464**
171465** If an OOM error occurs, store an error code in pParse and return NULL.
171466** The old colset object (if any) is not freed in this case.
171467*/
171468static Fts5Colset *fts5ParseColset(
171469  Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
171470  Fts5Colset *p,                  /* Existing colset object */
171471  int iCol                        /* New column to add to colset object */
171472){
171473  int nCol = p ? p->nCol : 0;     /* Num. columns already in colset object */
171474  Fts5Colset *pNew;               /* New colset object to return */
171475
171476  assert( pParse->rc==SQLITE_OK );
171477  assert( iCol>=0 && iCol<pParse->pConfig->nCol );
171478
171479  pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
171480  if( pNew==0 ){
171481    pParse->rc = SQLITE_NOMEM;
171482  }else{
171483    int *aiCol = pNew->aiCol;
171484    int i, j;
171485    for(i=0; i<nCol; i++){
171486      if( aiCol[i]==iCol ) return pNew;
171487      if( aiCol[i]>iCol ) break;
171488    }
171489    for(j=nCol; j>i; j--){
171490      aiCol[j] = aiCol[j-1];
171491    }
171492    aiCol[i] = iCol;
171493    pNew->nCol = nCol+1;
171494
171495#ifndef NDEBUG
171496    /* Check that the array is in order and contains no duplicate entries. */
171497    for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
171498#endif
171499  }
171500
171501  return pNew;
171502}
171503
171504static Fts5Colset *sqlite3Fts5ParseColset(
171505  Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
171506  Fts5Colset *pColset,            /* Existing colset object */
171507  Fts5Token *p
171508){
171509  Fts5Colset *pRet = 0;
171510  int iCol;
171511  char *z;                        /* Dequoted copy of token p */
171512
171513  z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
171514  if( pParse->rc==SQLITE_OK ){
171515    Fts5Config *pConfig = pParse->pConfig;
171516    sqlite3Fts5Dequote(z);
171517    for(iCol=0; iCol<pConfig->nCol; iCol++){
171518      if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
171519    }
171520    if( iCol==pConfig->nCol ){
171521      sqlite3Fts5ParseError(pParse, "no such column: %s", z);
171522    }else{
171523      pRet = fts5ParseColset(pParse, pColset, iCol);
171524    }
171525    sqlite3_free(z);
171526  }
171527
171528  if( pRet==0 ){
171529    assert( pParse->rc!=SQLITE_OK );
171530    sqlite3_free(pColset);
171531  }
171532
171533  return pRet;
171534}
171535
171536static void sqlite3Fts5ParseSetColset(
171537  Fts5Parse *pParse,
171538  Fts5ExprNearset *pNear,
171539  Fts5Colset *pColset
171540){
171541  if( pNear ){
171542    pNear->pColset = pColset;
171543  }else{
171544    sqlite3_free(pColset);
171545  }
171546}
171547
171548static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
171549  if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
171550    int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
171551    memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
171552    p->nChild += pSub->nChild;
171553    sqlite3_free(pSub);
171554  }else{
171555    p->apChild[p->nChild++] = pSub;
171556  }
171557}
171558
171559/*
171560** Allocate and return a new expression object. If anything goes wrong (i.e.
171561** OOM error), leave an error code in pParse and return NULL.
171562*/
171563static Fts5ExprNode *sqlite3Fts5ParseNode(
171564  Fts5Parse *pParse,              /* Parse context */
171565  int eType,                      /* FTS5_STRING, AND, OR or NOT */
171566  Fts5ExprNode *pLeft,            /* Left hand child expression */
171567  Fts5ExprNode *pRight,           /* Right hand child expression */
171568  Fts5ExprNearset *pNear          /* For STRING expressions, the near cluster */
171569){
171570  Fts5ExprNode *pRet = 0;
171571
171572  if( pParse->rc==SQLITE_OK ){
171573    int nChild = 0;               /* Number of children of returned node */
171574    int nByte;                    /* Bytes of space to allocate for this node */
171575
171576    assert( (eType!=FTS5_STRING && !pNear)
171577         || (eType==FTS5_STRING && !pLeft && !pRight)
171578    );
171579    if( eType==FTS5_STRING && pNear==0 ) return 0;
171580    if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
171581    if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
171582
171583    if( eType==FTS5_NOT ){
171584      nChild = 2;
171585    }else if( eType==FTS5_AND || eType==FTS5_OR ){
171586      nChild = 2;
171587      if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
171588      if( pRight->eType==eType ) nChild += pRight->nChild-1;
171589    }
171590
171591    nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
171592    pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
171593
171594    if( pRet ){
171595      pRet->eType = eType;
171596      pRet->pNear = pNear;
171597      if( eType==FTS5_STRING ){
171598        int iPhrase;
171599        for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
171600          pNear->apPhrase[iPhrase]->pNode = pRet;
171601        }
171602        if( pNear->nPhrase==1
171603         && pNear->apPhrase[0]->nTerm==1
171604         && pNear->apPhrase[0]->aTerm[0].pSynonym==0
171605        ){
171606          pRet->eType = FTS5_TERM;
171607        }
171608      }else{
171609        fts5ExprAddChildren(pRet, pLeft);
171610        fts5ExprAddChildren(pRet, pRight);
171611      }
171612    }
171613  }
171614
171615  if( pRet==0 ){
171616    assert( pParse->rc!=SQLITE_OK );
171617    sqlite3Fts5ParseNodeFree(pLeft);
171618    sqlite3Fts5ParseNodeFree(pRight);
171619    sqlite3Fts5ParseNearsetFree(pNear);
171620  }
171621  return pRet;
171622}
171623
171624static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
171625  int nByte = 0;
171626  Fts5ExprTerm *p;
171627  char *zQuoted;
171628
171629  /* Determine the maximum amount of space required. */
171630  for(p=pTerm; p; p=p->pSynonym){
171631    nByte += strlen(pTerm->zTerm) * 2 + 3 + 2;
171632  }
171633  zQuoted = sqlite3_malloc(nByte);
171634
171635  if( zQuoted ){
171636    int i = 0;
171637    for(p=pTerm; p; p=p->pSynonym){
171638      char *zIn = p->zTerm;
171639      zQuoted[i++] = '"';
171640      while( *zIn ){
171641        if( *zIn=='"' ) zQuoted[i++] = '"';
171642        zQuoted[i++] = *zIn++;
171643      }
171644      zQuoted[i++] = '"';
171645      if( p->pSynonym ) zQuoted[i++] = '|';
171646    }
171647    if( pTerm->bPrefix ){
171648      zQuoted[i++] = ' ';
171649      zQuoted[i++] = '*';
171650    }
171651    zQuoted[i++] = '\0';
171652  }
171653  return zQuoted;
171654}
171655
171656static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
171657  char *zNew;
171658  va_list ap;
171659  va_start(ap, zFmt);
171660  zNew = sqlite3_vmprintf(zFmt, ap);
171661  va_end(ap);
171662  if( zApp && zNew ){
171663    char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
171664    sqlite3_free(zNew);
171665    zNew = zNew2;
171666  }
171667  sqlite3_free(zApp);
171668  return zNew;
171669}
171670
171671/*
171672** Compose a tcl-readable representation of expression pExpr. Return a
171673** pointer to a buffer containing that representation. It is the
171674** responsibility of the caller to at some point free the buffer using
171675** sqlite3_free().
171676*/
171677static char *fts5ExprPrintTcl(
171678  Fts5Config *pConfig,
171679  const char *zNearsetCmd,
171680  Fts5ExprNode *pExpr
171681){
171682  char *zRet = 0;
171683  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
171684    Fts5ExprNearset *pNear = pExpr->pNear;
171685    int i;
171686    int iTerm;
171687
171688    zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
171689    if( zRet==0 ) return 0;
171690    if( pNear->pColset ){
171691      int *aiCol = pNear->pColset->aiCol;
171692      int nCol = pNear->pColset->nCol;
171693      if( nCol==1 ){
171694        zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
171695      }else{
171696        zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
171697        for(i=1; i<pNear->pColset->nCol; i++){
171698          zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
171699        }
171700        zRet = fts5PrintfAppend(zRet, "} ");
171701      }
171702      if( zRet==0 ) return 0;
171703    }
171704
171705    if( pNear->nPhrase>1 ){
171706      zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
171707      if( zRet==0 ) return 0;
171708    }
171709
171710    zRet = fts5PrintfAppend(zRet, "--");
171711    if( zRet==0 ) return 0;
171712
171713    for(i=0; i<pNear->nPhrase; i++){
171714      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
171715
171716      zRet = fts5PrintfAppend(zRet, " {");
171717      for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
171718        char *zTerm = pPhrase->aTerm[iTerm].zTerm;
171719        zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
171720      }
171721
171722      if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
171723      if( zRet==0 ) return 0;
171724    }
171725
171726  }else{
171727    char const *zOp = 0;
171728    int i;
171729    switch( pExpr->eType ){
171730      case FTS5_AND: zOp = "AND"; break;
171731      case FTS5_NOT: zOp = "NOT"; break;
171732      default:
171733        assert( pExpr->eType==FTS5_OR );
171734        zOp = "OR";
171735        break;
171736    }
171737
171738    zRet = sqlite3_mprintf("%s", zOp);
171739    for(i=0; zRet && i<pExpr->nChild; i++){
171740      char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
171741      if( !z ){
171742        sqlite3_free(zRet);
171743        zRet = 0;
171744      }else{
171745        zRet = fts5PrintfAppend(zRet, " [%z]", z);
171746      }
171747    }
171748  }
171749
171750  return zRet;
171751}
171752
171753static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
171754  char *zRet = 0;
171755  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
171756    Fts5ExprNearset *pNear = pExpr->pNear;
171757    int i;
171758    int iTerm;
171759
171760    if( pNear->pColset ){
171761      int iCol = pNear->pColset->aiCol[0];
171762      zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
171763      if( zRet==0 ) return 0;
171764    }
171765
171766    if( pNear->nPhrase>1 ){
171767      zRet = fts5PrintfAppend(zRet, "NEAR(");
171768      if( zRet==0 ) return 0;
171769    }
171770
171771    for(i=0; i<pNear->nPhrase; i++){
171772      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
171773      if( i!=0 ){
171774        zRet = fts5PrintfAppend(zRet, " ");
171775        if( zRet==0 ) return 0;
171776      }
171777      for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
171778        char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
171779        if( zTerm ){
171780          zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
171781          sqlite3_free(zTerm);
171782        }
171783        if( zTerm==0 || zRet==0 ){
171784          sqlite3_free(zRet);
171785          return 0;
171786        }
171787      }
171788    }
171789
171790    if( pNear->nPhrase>1 ){
171791      zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
171792      if( zRet==0 ) return 0;
171793    }
171794
171795  }else{
171796    char const *zOp = 0;
171797    int i;
171798
171799    switch( pExpr->eType ){
171800      case FTS5_AND: zOp = " AND "; break;
171801      case FTS5_NOT: zOp = " NOT "; break;
171802      default:
171803        assert( pExpr->eType==FTS5_OR );
171804        zOp = " OR ";
171805        break;
171806    }
171807
171808    for(i=0; i<pExpr->nChild; i++){
171809      char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
171810      if( z==0 ){
171811        sqlite3_free(zRet);
171812        zRet = 0;
171813      }else{
171814        int e = pExpr->apChild[i]->eType;
171815        int b = (e!=FTS5_STRING && e!=FTS5_TERM);
171816        zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
171817            (i==0 ? "" : zOp),
171818            (b?"(":""), z, (b?")":"")
171819        );
171820      }
171821      if( zRet==0 ) break;
171822    }
171823  }
171824
171825  return zRet;
171826}
171827
171828/*
171829** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
171830** and fts5_expr_tcl() (bTcl!=0).
171831*/
171832static void fts5ExprFunction(
171833  sqlite3_context *pCtx,          /* Function call context */
171834  int nArg,                       /* Number of args */
171835  sqlite3_value **apVal,          /* Function arguments */
171836  int bTcl
171837){
171838  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
171839  sqlite3 *db = sqlite3_context_db_handle(pCtx);
171840  const char *zExpr = 0;
171841  char *zErr = 0;
171842  Fts5Expr *pExpr = 0;
171843  int rc;
171844  int i;
171845
171846  const char **azConfig;          /* Array of arguments for Fts5Config */
171847  const char *zNearsetCmd = "nearset";
171848  int nConfig;                    /* Size of azConfig[] */
171849  Fts5Config *pConfig = 0;
171850  int iArg = 1;
171851
171852  if( nArg<1 ){
171853    zErr = sqlite3_mprintf("wrong number of arguments to function %s",
171854        bTcl ? "fts5_expr_tcl" : "fts5_expr"
171855    );
171856    sqlite3_result_error(pCtx, zErr, -1);
171857    sqlite3_free(zErr);
171858    return;
171859  }
171860
171861  if( bTcl && nArg>1 ){
171862    zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
171863    iArg = 2;
171864  }
171865
171866  nConfig = 3 + (nArg-iArg);
171867  azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
171868  if( azConfig==0 ){
171869    sqlite3_result_error_nomem(pCtx);
171870    return;
171871  }
171872  azConfig[0] = 0;
171873  azConfig[1] = "main";
171874  azConfig[2] = "tbl";
171875  for(i=3; iArg<nArg; iArg++){
171876    azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
171877  }
171878
171879  zExpr = (const char*)sqlite3_value_text(apVal[0]);
171880
171881  rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
171882  if( rc==SQLITE_OK ){
171883    rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pExpr, &zErr);
171884  }
171885  if( rc==SQLITE_OK ){
171886    char *zText;
171887    if( pExpr->pRoot==0 ){
171888      zText = sqlite3_mprintf("");
171889    }else if( bTcl ){
171890      zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
171891    }else{
171892      zText = fts5ExprPrint(pConfig, pExpr->pRoot);
171893    }
171894    if( zText==0 ){
171895      rc = SQLITE_NOMEM;
171896    }else{
171897      sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
171898      sqlite3_free(zText);
171899    }
171900  }
171901
171902  if( rc!=SQLITE_OK ){
171903    if( zErr ){
171904      sqlite3_result_error(pCtx, zErr, -1);
171905      sqlite3_free(zErr);
171906    }else{
171907      sqlite3_result_error_code(pCtx, rc);
171908    }
171909  }
171910  sqlite3_free((void *)azConfig);
171911  sqlite3Fts5ConfigFree(pConfig);
171912  sqlite3Fts5ExprFree(pExpr);
171913}
171914
171915static void fts5ExprFunctionHr(
171916  sqlite3_context *pCtx,          /* Function call context */
171917  int nArg,                       /* Number of args */
171918  sqlite3_value **apVal           /* Function arguments */
171919){
171920  fts5ExprFunction(pCtx, nArg, apVal, 0);
171921}
171922static void fts5ExprFunctionTcl(
171923  sqlite3_context *pCtx,          /* Function call context */
171924  int nArg,                       /* Number of args */
171925  sqlite3_value **apVal           /* Function arguments */
171926){
171927  fts5ExprFunction(pCtx, nArg, apVal, 1);
171928}
171929
171930/*
171931** The implementation of an SQLite user-defined-function that accepts a
171932** single integer as an argument. If the integer is an alpha-numeric
171933** unicode code point, 1 is returned. Otherwise 0.
171934*/
171935static void fts5ExprIsAlnum(
171936  sqlite3_context *pCtx,          /* Function call context */
171937  int nArg,                       /* Number of args */
171938  sqlite3_value **apVal           /* Function arguments */
171939){
171940  int iCode;
171941  if( nArg!=1 ){
171942    sqlite3_result_error(pCtx,
171943        "wrong number of arguments to function fts5_isalnum", -1
171944    );
171945    return;
171946  }
171947  iCode = sqlite3_value_int(apVal[0]);
171948  sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode));
171949}
171950
171951static void fts5ExprFold(
171952  sqlite3_context *pCtx,          /* Function call context */
171953  int nArg,                       /* Number of args */
171954  sqlite3_value **apVal           /* Function arguments */
171955){
171956  if( nArg!=1 && nArg!=2 ){
171957    sqlite3_result_error(pCtx,
171958        "wrong number of arguments to function fts5_fold", -1
171959    );
171960  }else{
171961    int iCode;
171962    int bRemoveDiacritics = 0;
171963    iCode = sqlite3_value_int(apVal[0]);
171964    if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
171965    sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
171966  }
171967}
171968
171969/*
171970** This is called during initialization to register the fts5_expr() scalar
171971** UDF with the SQLite handle passed as the only argument.
171972*/
171973static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
171974  struct Fts5ExprFunc {
171975    const char *z;
171976    void (*x)(sqlite3_context*,int,sqlite3_value**);
171977  } aFunc[] = {
171978    { "fts5_expr",     fts5ExprFunctionHr },
171979    { "fts5_expr_tcl", fts5ExprFunctionTcl },
171980    { "fts5_isalnum",  fts5ExprIsAlnum },
171981    { "fts5_fold",     fts5ExprFold },
171982  };
171983  int i;
171984  int rc = SQLITE_OK;
171985  void *pCtx = (void*)pGlobal;
171986
171987  for(i=0; rc==SQLITE_OK && i<(sizeof(aFunc) / sizeof(aFunc[0])); i++){
171988    struct Fts5ExprFunc *p = &aFunc[i];
171989    rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
171990  }
171991
171992  /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */
171993#ifndef NDEBUG
171994  (void)sqlite3Fts5ParserTrace;
171995#endif
171996
171997  return rc;
171998}
171999
172000/*
172001** Return the number of phrases in expression pExpr.
172002*/
172003static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
172004  return (pExpr ? pExpr->nPhrase : 0);
172005}
172006
172007/*
172008** Return the number of terms in the iPhrase'th phrase in pExpr.
172009*/
172010static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
172011  if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
172012  return pExpr->apExprPhrase[iPhrase]->nTerm;
172013}
172014
172015/*
172016** This function is used to access the current position list for phrase
172017** iPhrase.
172018*/
172019static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
172020  int nRet;
172021  Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
172022  Fts5ExprNode *pNode = pPhrase->pNode;
172023  if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
172024    *pa = pPhrase->poslist.p;
172025    nRet = pPhrase->poslist.n;
172026  }else{
172027    *pa = 0;
172028    nRet = 0;
172029  }
172030  return nRet;
172031}
172032
172033/*
172034** 2014 August 11
172035**
172036** The author disclaims copyright to this source code.  In place of
172037** a legal notice, here is a blessing:
172038**
172039**    May you do good and not evil.
172040**    May you find forgiveness for yourself and forgive others.
172041**    May you share freely, never taking more than you give.
172042**
172043******************************************************************************
172044**
172045*/
172046
172047
172048
172049
172050typedef struct Fts5HashEntry Fts5HashEntry;
172051
172052/*
172053** This file contains the implementation of an in-memory hash table used
172054** to accumuluate "term -> doclist" content before it is flused to a level-0
172055** segment.
172056*/
172057
172058
172059struct Fts5Hash {
172060  int *pnByte;                    /* Pointer to bytes counter */
172061  int nEntry;                     /* Number of entries currently in hash */
172062  int nSlot;                      /* Size of aSlot[] array */
172063  Fts5HashEntry *pScan;           /* Current ordered scan item */
172064  Fts5HashEntry **aSlot;          /* Array of hash slots */
172065};
172066
172067/*
172068** Each entry in the hash table is represented by an object of the
172069** following type. Each object, its key (zKey[]) and its current data
172070** are stored in a single memory allocation. The position list data
172071** immediately follows the key data in memory.
172072**
172073** The data that follows the key is in a similar, but not identical format
172074** to the doclist data stored in the database. It is:
172075**
172076**   * Rowid, as a varint
172077**   * Position list, without 0x00 terminator.
172078**   * Size of previous position list and rowid, as a 4 byte
172079**     big-endian integer.
172080**
172081** iRowidOff:
172082**   Offset of last rowid written to data area. Relative to first byte of
172083**   structure.
172084**
172085** nData:
172086**   Bytes of data written since iRowidOff.
172087*/
172088struct Fts5HashEntry {
172089  Fts5HashEntry *pHashNext;       /* Next hash entry with same hash-key */
172090  Fts5HashEntry *pScanNext;       /* Next entry in sorted order */
172091
172092  int nAlloc;                     /* Total size of allocation */
172093  int iSzPoslist;                 /* Offset of space for 4-byte poslist size */
172094  int nData;                      /* Total bytes of data (incl. structure) */
172095  u8 bDel;                        /* Set delete-flag @ iSzPoslist */
172096
172097  int iCol;                       /* Column of last value written */
172098  int iPos;                       /* Position of last value written */
172099  i64 iRowid;                     /* Rowid of last value written */
172100  char zKey[8];                   /* Nul-terminated entry key */
172101};
172102
172103/*
172104** Size of Fts5HashEntry without the zKey[] array.
172105*/
172106#define FTS5_HASHENTRYSIZE (sizeof(Fts5HashEntry)-8)
172107
172108
172109
172110/*
172111** Allocate a new hash table.
172112*/
172113static int sqlite3Fts5HashNew(Fts5Hash **ppNew, int *pnByte){
172114  int rc = SQLITE_OK;
172115  Fts5Hash *pNew;
172116
172117  *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
172118  if( pNew==0 ){
172119    rc = SQLITE_NOMEM;
172120  }else{
172121    int nByte;
172122    memset(pNew, 0, sizeof(Fts5Hash));
172123    pNew->pnByte = pnByte;
172124
172125    pNew->nSlot = 1024;
172126    nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
172127    pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
172128    if( pNew->aSlot==0 ){
172129      sqlite3_free(pNew);
172130      *ppNew = 0;
172131      rc = SQLITE_NOMEM;
172132    }else{
172133      memset(pNew->aSlot, 0, nByte);
172134    }
172135  }
172136  return rc;
172137}
172138
172139/*
172140** Free a hash table object.
172141*/
172142static void sqlite3Fts5HashFree(Fts5Hash *pHash){
172143  if( pHash ){
172144    sqlite3Fts5HashClear(pHash);
172145    sqlite3_free(pHash->aSlot);
172146    sqlite3_free(pHash);
172147  }
172148}
172149
172150/*
172151** Empty (but do not delete) a hash table.
172152*/
172153static void sqlite3Fts5HashClear(Fts5Hash *pHash){
172154  int i;
172155  for(i=0; i<pHash->nSlot; i++){
172156    Fts5HashEntry *pNext;
172157    Fts5HashEntry *pSlot;
172158    for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
172159      pNext = pSlot->pHashNext;
172160      sqlite3_free(pSlot);
172161    }
172162  }
172163  memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
172164  pHash->nEntry = 0;
172165}
172166
172167static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
172168  int i;
172169  unsigned int h = 13;
172170  for(i=n-1; i>=0; i--){
172171    h = (h << 3) ^ h ^ p[i];
172172  }
172173  return (h % nSlot);
172174}
172175
172176static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
172177  int i;
172178  unsigned int h = 13;
172179  for(i=n-1; i>=0; i--){
172180    h = (h << 3) ^ h ^ p[i];
172181  }
172182  h = (h << 3) ^ h ^ b;
172183  return (h % nSlot);
172184}
172185
172186/*
172187** Resize the hash table by doubling the number of slots.
172188*/
172189static int fts5HashResize(Fts5Hash *pHash){
172190  int nNew = pHash->nSlot*2;
172191  int i;
172192  Fts5HashEntry **apNew;
172193  Fts5HashEntry **apOld = pHash->aSlot;
172194
172195  apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
172196  if( !apNew ) return SQLITE_NOMEM;
172197  memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
172198
172199  for(i=0; i<pHash->nSlot; i++){
172200    while( apOld[i] ){
172201      int iHash;
172202      Fts5HashEntry *p = apOld[i];
172203      apOld[i] = p->pHashNext;
172204      iHash = fts5HashKey(nNew, (u8*)p->zKey, strlen(p->zKey));
172205      p->pHashNext = apNew[iHash];
172206      apNew[iHash] = p;
172207    }
172208  }
172209
172210  sqlite3_free(apOld);
172211  pHash->nSlot = nNew;
172212  pHash->aSlot = apNew;
172213  return SQLITE_OK;
172214}
172215
172216static void fts5HashAddPoslistSize(Fts5HashEntry *p){
172217  if( p->iSzPoslist ){
172218    u8 *pPtr = (u8*)p;
172219    int nSz = (p->nData - p->iSzPoslist - 1);         /* Size in bytes */
172220    int nPos = nSz*2 + p->bDel;                       /* Value of nPos field */
172221
172222    assert( p->bDel==0 || p->bDel==1 );
172223    if( nPos<=127 ){
172224      pPtr[p->iSzPoslist] = nPos;
172225    }else{
172226      int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
172227      memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
172228      sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
172229      p->nData += (nByte-1);
172230    }
172231    p->bDel = 0;
172232    p->iSzPoslist = 0;
172233  }
172234}
172235
172236static int sqlite3Fts5HashWrite(
172237  Fts5Hash *pHash,
172238  i64 iRowid,                     /* Rowid for this entry */
172239  int iCol,                       /* Column token appears in (-ve -> delete) */
172240  int iPos,                       /* Position of token within column */
172241  char bByte,                     /* First byte of token */
172242  const char *pToken, int nToken  /* Token to add or remove to or from index */
172243){
172244  unsigned int iHash;
172245  Fts5HashEntry *p;
172246  u8 *pPtr;
172247  int nIncr = 0;                  /* Amount to increment (*pHash->pnByte) by */
172248
172249  /* Attempt to locate an existing hash entry */
172250  iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
172251  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
172252    if( p->zKey[0]==bByte
172253     && memcmp(&p->zKey[1], pToken, nToken)==0
172254     && p->zKey[nToken+1]==0
172255    ){
172256      break;
172257    }
172258  }
172259
172260  /* If an existing hash entry cannot be found, create a new one. */
172261  if( p==0 ){
172262    int nByte = FTS5_HASHENTRYSIZE + (nToken+1) + 1 + 64;
172263    if( nByte<128 ) nByte = 128;
172264
172265    if( (pHash->nEntry*2)>=pHash->nSlot ){
172266      int rc = fts5HashResize(pHash);
172267      if( rc!=SQLITE_OK ) return rc;
172268      iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
172269    }
172270
172271    p = (Fts5HashEntry*)sqlite3_malloc(nByte);
172272    if( !p ) return SQLITE_NOMEM;
172273    memset(p, 0, FTS5_HASHENTRYSIZE);
172274    p->nAlloc = nByte;
172275    p->zKey[0] = bByte;
172276    memcpy(&p->zKey[1], pToken, nToken);
172277    assert( iHash==fts5HashKey(pHash->nSlot, (u8*)p->zKey, nToken+1) );
172278    p->zKey[nToken+1] = '\0';
172279    p->nData = nToken+1 + 1 + FTS5_HASHENTRYSIZE;
172280    p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
172281    p->iSzPoslist = p->nData;
172282    p->nData += 1;
172283    p->iRowid = iRowid;
172284    p->pHashNext = pHash->aSlot[iHash];
172285    pHash->aSlot[iHash] = p;
172286    pHash->nEntry++;
172287    nIncr += p->nData;
172288  }
172289
172290  /* Check there is enough space to append a new entry. Worst case scenario
172291  ** is:
172292  **
172293  **     + 9 bytes for a new rowid,
172294  **     + 4 byte reserved for the "poslist size" varint.
172295  **     + 1 byte for a "new column" byte,
172296  **     + 3 bytes for a new column number (16-bit max) as a varint,
172297  **     + 5 bytes for the new position offset (32-bit max).
172298  */
172299  if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
172300    int nNew = p->nAlloc * 2;
172301    Fts5HashEntry *pNew;
172302    Fts5HashEntry **pp;
172303    pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
172304    if( pNew==0 ) return SQLITE_NOMEM;
172305    pNew->nAlloc = nNew;
172306    for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
172307    *pp = pNew;
172308    p = pNew;
172309  }
172310  pPtr = (u8*)p;
172311  nIncr -= p->nData;
172312
172313  /* If this is a new rowid, append the 4-byte size field for the previous
172314  ** entry, and the new rowid for this entry.  */
172315  if( iRowid!=p->iRowid ){
172316    fts5HashAddPoslistSize(p);
172317    p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
172318    p->iSzPoslist = p->nData;
172319    p->nData += 1;
172320    p->iCol = 0;
172321    p->iPos = 0;
172322    p->iRowid = iRowid;
172323  }
172324
172325  if( iCol>=0 ){
172326    /* Append a new column value, if necessary */
172327    assert( iCol>=p->iCol );
172328    if( iCol!=p->iCol ){
172329      pPtr[p->nData++] = 0x01;
172330      p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
172331      p->iCol = iCol;
172332      p->iPos = 0;
172333    }
172334
172335    /* Append the new position offset */
172336    p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
172337    p->iPos = iPos;
172338  }else{
172339    /* This is a delete. Set the delete flag. */
172340    p->bDel = 1;
172341  }
172342  nIncr += p->nData;
172343
172344  *pHash->pnByte += nIncr;
172345  return SQLITE_OK;
172346}
172347
172348
172349/*
172350** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
172351** each sorted in key order. This function merges the two lists into a
172352** single list and returns a pointer to its first element.
172353*/
172354static Fts5HashEntry *fts5HashEntryMerge(
172355  Fts5HashEntry *pLeft,
172356  Fts5HashEntry *pRight
172357){
172358  Fts5HashEntry *p1 = pLeft;
172359  Fts5HashEntry *p2 = pRight;
172360  Fts5HashEntry *pRet = 0;
172361  Fts5HashEntry **ppOut = &pRet;
172362
172363  while( p1 || p2 ){
172364    if( p1==0 ){
172365      *ppOut = p2;
172366      p2 = 0;
172367    }else if( p2==0 ){
172368      *ppOut = p1;
172369      p1 = 0;
172370    }else{
172371      int i = 0;
172372      while( p1->zKey[i]==p2->zKey[i] ) i++;
172373
172374      if( ((u8)p1->zKey[i])>((u8)p2->zKey[i]) ){
172375        /* p2 is smaller */
172376        *ppOut = p2;
172377        ppOut = &p2->pScanNext;
172378        p2 = p2->pScanNext;
172379      }else{
172380        /* p1 is smaller */
172381        *ppOut = p1;
172382        ppOut = &p1->pScanNext;
172383        p1 = p1->pScanNext;
172384      }
172385      *ppOut = 0;
172386    }
172387  }
172388
172389  return pRet;
172390}
172391
172392/*
172393** Extract all tokens from hash table iHash and link them into a list
172394** in sorted order. The hash table is cleared before returning. It is
172395** the responsibility of the caller to free the elements of the returned
172396** list.
172397*/
172398static int fts5HashEntrySort(
172399  Fts5Hash *pHash,
172400  const char *pTerm, int nTerm,   /* Query prefix, if any */
172401  Fts5HashEntry **ppSorted
172402){
172403  const int nMergeSlot = 32;
172404  Fts5HashEntry **ap;
172405  Fts5HashEntry *pList;
172406  int iSlot;
172407  int i;
172408
172409  *ppSorted = 0;
172410  ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
172411  if( !ap ) return SQLITE_NOMEM;
172412  memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
172413
172414  for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
172415    Fts5HashEntry *pIter;
172416    for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
172417      if( pTerm==0 || 0==memcmp(pIter->zKey, pTerm, nTerm) ){
172418        Fts5HashEntry *pEntry = pIter;
172419        pEntry->pScanNext = 0;
172420        for(i=0; ap[i]; i++){
172421          pEntry = fts5HashEntryMerge(pEntry, ap[i]);
172422          ap[i] = 0;
172423        }
172424        ap[i] = pEntry;
172425      }
172426    }
172427  }
172428
172429  pList = 0;
172430  for(i=0; i<nMergeSlot; i++){
172431    pList = fts5HashEntryMerge(pList, ap[i]);
172432  }
172433
172434  pHash->nEntry = 0;
172435  sqlite3_free(ap);
172436  *ppSorted = pList;
172437  return SQLITE_OK;
172438}
172439
172440/*
172441** Query the hash table for a doclist associated with term pTerm/nTerm.
172442*/
172443static int sqlite3Fts5HashQuery(
172444  Fts5Hash *pHash,                /* Hash table to query */
172445  const char *pTerm, int nTerm,   /* Query term */
172446  const u8 **ppDoclist,           /* OUT: Pointer to doclist for pTerm */
172447  int *pnDoclist                  /* OUT: Size of doclist in bytes */
172448){
172449  unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
172450  Fts5HashEntry *p;
172451
172452  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
172453    if( memcmp(p->zKey, pTerm, nTerm)==0 && p->zKey[nTerm]==0 ) break;
172454  }
172455
172456  if( p ){
172457    fts5HashAddPoslistSize(p);
172458    *ppDoclist = (const u8*)&p->zKey[nTerm+1];
172459    *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
172460  }else{
172461    *ppDoclist = 0;
172462    *pnDoclist = 0;
172463  }
172464
172465  return SQLITE_OK;
172466}
172467
172468static int sqlite3Fts5HashScanInit(
172469  Fts5Hash *p,                    /* Hash table to query */
172470  const char *pTerm, int nTerm    /* Query prefix */
172471){
172472  return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
172473}
172474
172475static void sqlite3Fts5HashScanNext(Fts5Hash *p){
172476  assert( !sqlite3Fts5HashScanEof(p) );
172477  p->pScan = p->pScan->pScanNext;
172478}
172479
172480static int sqlite3Fts5HashScanEof(Fts5Hash *p){
172481  return (p->pScan==0);
172482}
172483
172484static void sqlite3Fts5HashScanEntry(
172485  Fts5Hash *pHash,
172486  const char **pzTerm,            /* OUT: term (nul-terminated) */
172487  const u8 **ppDoclist,           /* OUT: pointer to doclist */
172488  int *pnDoclist                  /* OUT: size of doclist in bytes */
172489){
172490  Fts5HashEntry *p;
172491  if( (p = pHash->pScan) ){
172492    int nTerm = strlen(p->zKey);
172493    fts5HashAddPoslistSize(p);
172494    *pzTerm = p->zKey;
172495    *ppDoclist = (const u8*)&p->zKey[nTerm+1];
172496    *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
172497  }else{
172498    *pzTerm = 0;
172499    *ppDoclist = 0;
172500    *pnDoclist = 0;
172501  }
172502}
172503
172504
172505/*
172506** 2014 May 31
172507**
172508** The author disclaims copyright to this source code.  In place of
172509** a legal notice, here is a blessing:
172510**
172511**    May you do good and not evil.
172512**    May you find forgiveness for yourself and forgive others.
172513**    May you share freely, never taking more than you give.
172514**
172515******************************************************************************
172516**
172517** Low level access to the FTS index stored in the database file. The
172518** routines in this file file implement all read and write access to the
172519** %_data table. Other parts of the system access this functionality via
172520** the interface defined in fts5Int.h.
172521*/
172522
172523
172524
172525/*
172526** Overview:
172527**
172528** The %_data table contains all the FTS indexes for an FTS5 virtual table.
172529** As well as the main term index, there may be up to 31 prefix indexes.
172530** The format is similar to FTS3/4, except that:
172531**
172532**   * all segment b-tree leaf data is stored in fixed size page records
172533**     (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
172534**     taken to ensure it is possible to iterate in either direction through
172535**     the entries in a doclist, or to seek to a specific entry within a
172536**     doclist, without loading it into memory.
172537**
172538**   * large doclists that span many pages have associated "doclist index"
172539**     records that contain a copy of the first rowid on each page spanned by
172540**     the doclist. This is used to speed up seek operations, and merges of
172541**     large doclists with very small doclists.
172542**
172543**   * extra fields in the "structure record" record the state of ongoing
172544**     incremental merge operations.
172545**
172546*/
172547
172548
172549#define FTS5_OPT_WORK_UNIT  1000  /* Number of leaf pages per optimize step */
172550#define FTS5_WORK_UNIT      64    /* Number of leaf pages in unit of work */
172551
172552#define FTS5_MIN_DLIDX_SIZE 4     /* Add dlidx if this many empty pages */
172553
172554#define FTS5_MAIN_PREFIX '0'
172555
172556#if FTS5_MAX_PREFIX_INDEXES > 31
172557# error "FTS5_MAX_PREFIX_INDEXES is too large"
172558#endif
172559
172560/*
172561** Details:
172562**
172563** The %_data table managed by this module,
172564**
172565**     CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
172566**
172567** , contains the following 5 types of records. See the comments surrounding
172568** the FTS5_*_ROWID macros below for a description of how %_data rowids are
172569** assigned to each fo them.
172570**
172571** 1. Structure Records:
172572**
172573**   The set of segments that make up an index - the index structure - are
172574**   recorded in a single record within the %_data table. The record consists
172575**   of a single 32-bit configuration cookie value followed by a list of
172576**   SQLite varints. If the FTS table features more than one index (because
172577**   there are one or more prefix indexes), it is guaranteed that all share
172578**   the same cookie value.
172579**
172580**   Immediately following the configuration cookie, the record begins with
172581**   three varints:
172582**
172583**     + number of levels,
172584**     + total number of segments on all levels,
172585**     + value of write counter.
172586**
172587**   Then, for each level from 0 to nMax:
172588**
172589**     + number of input segments in ongoing merge.
172590**     + total number of segments in level.
172591**     + for each segment from oldest to newest:
172592**         + segment id (always > 0)
172593**         + first leaf page number (often 1, always greater than 0)
172594**         + final leaf page number
172595**
172596** 2. The Averages Record:
172597**
172598**   A single record within the %_data table. The data is a list of varints.
172599**   The first value is the number of rows in the index. Then, for each column
172600**   from left to right, the total number of tokens in the column for all
172601**   rows of the table.
172602**
172603** 3. Segment leaves:
172604**
172605**   TERM/DOCLIST FORMAT:
172606**
172607**     Most of each segment leaf is taken up by term/doclist data. The
172608**     general format of term/doclist, starting with the first term
172609**     on the leaf page, is:
172610**
172611**         varint : size of first term
172612**         blob:    first term data
172613**         doclist: first doclist
172614**         zero-or-more {
172615**           varint:  number of bytes in common with previous term
172616**           varint:  number of bytes of new term data (nNew)
172617**           blob:    nNew bytes of new term data
172618**           doclist: next doclist
172619**         }
172620**
172621**     doclist format:
172622**
172623**         varint:  first rowid
172624**         poslist: first poslist
172625**         zero-or-more {
172626**           varint:  rowid delta (always > 0)
172627**           poslist: next poslist
172628**         }
172629**
172630**     poslist format:
172631**
172632**         varint: size of poslist in bytes multiplied by 2, not including
172633**                 this field. Plus 1 if this entry carries the "delete" flag.
172634**         collist: collist for column 0
172635**         zero-or-more {
172636**           0x01 byte
172637**           varint: column number (I)
172638**           collist: collist for column I
172639**         }
172640**
172641**     collist format:
172642**
172643**         varint: first offset + 2
172644**         zero-or-more {
172645**           varint: offset delta + 2
172646**         }
172647**
172648**   PAGE FORMAT
172649**
172650**     Each leaf page begins with a 4-byte header containing 2 16-bit
172651**     unsigned integer fields in big-endian format. They are:
172652**
172653**       * The byte offset of the first rowid on the page, if it exists
172654**         and occurs before the first term (otherwise 0).
172655**
172656**       * The byte offset of the start of the page footer. If the page
172657**         footer is 0 bytes in size, then this field is the same as the
172658**         size of the leaf page in bytes.
172659**
172660**     The page footer consists of a single varint for each term located
172661**     on the page. Each varint is the byte offset of the current term
172662**     within the page, delta-compressed against the previous value. In
172663**     other words, the first varint in the footer is the byte offset of
172664**     the first term, the second is the byte offset of the second less that
172665**     of the first, and so on.
172666**
172667**     The term/doclist format described above is accurate if the entire
172668**     term/doclist data fits on a single leaf page. If this is not the case,
172669**     the format is changed in two ways:
172670**
172671**       + if the first rowid on a page occurs before the first term, it
172672**         is stored as a literal value:
172673**
172674**             varint:  first rowid
172675**
172676**       + the first term on each page is stored in the same way as the
172677**         very first term of the segment:
172678**
172679**             varint : size of first term
172680**             blob:    first term data
172681**
172682** 5. Segment doclist indexes:
172683**
172684**   Doclist indexes are themselves b-trees, however they usually consist of
172685**   a single leaf record only. The format of each doclist index leaf page
172686**   is:
172687**
172688**     * Flags byte. Bits are:
172689**         0x01: Clear if leaf is also the root page, otherwise set.
172690**
172691**     * Page number of fts index leaf page. As a varint.
172692**
172693**     * First rowid on page indicated by previous field. As a varint.
172694**
172695**     * A list of varints, one for each subsequent termless page. A
172696**       positive delta if the termless page contains at least one rowid,
172697**       or an 0x00 byte otherwise.
172698**
172699**   Internal doclist index nodes are:
172700**
172701**     * Flags byte. Bits are:
172702**         0x01: Clear for root page, otherwise set.
172703**
172704**     * Page number of first child page. As a varint.
172705**
172706**     * Copy of first rowid on page indicated by previous field. As a varint.
172707**
172708**     * A list of delta-encoded varints - the first rowid on each subsequent
172709**       child page.
172710**
172711*/
172712
172713/*
172714** Rowids for the averages and structure records in the %_data table.
172715*/
172716#define FTS5_AVERAGES_ROWID     1    /* Rowid used for the averages record */
172717#define FTS5_STRUCTURE_ROWID   10    /* The structure record */
172718
172719/*
172720** Macros determining the rowids used by segment leaves and dlidx leaves
172721** and nodes. All nodes and leaves are stored in the %_data table with large
172722** positive rowids.
172723**
172724** Each segment has a unique non-zero 16-bit id.
172725**
172726** The rowid for each segment leaf is found by passing the segment id and
172727** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
172728** sequentially starting from 1.
172729*/
172730#define FTS5_DATA_ID_B     16     /* Max seg id number 65535 */
172731#define FTS5_DATA_DLI_B     1     /* Doclist-index flag (1 bit) */
172732#define FTS5_DATA_HEIGHT_B  5     /* Max dlidx tree height of 32 */
172733#define FTS5_DATA_PAGE_B   31     /* Max page number of 2147483648 */
172734
172735#define fts5_dri(segid, dlidx, height, pgno) (                                 \
172736 ((i64)(segid)  << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) +    \
172737 ((i64)(dlidx)  << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) +                  \
172738 ((i64)(height) << (FTS5_DATA_PAGE_B)) +                                       \
172739 ((i64)(pgno))                                                                 \
172740)
172741
172742#define FTS5_SEGMENT_ROWID(segid, pgno)       fts5_dri(segid, 0, 0, pgno)
172743#define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
172744
172745/*
172746** Maximum segments permitted in a single index
172747*/
172748#define FTS5_MAX_SEGMENT 2000
172749
172750#ifdef SQLITE_DEBUG
172751static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
172752#endif
172753
172754
172755/*
172756** Each time a blob is read from the %_data table, it is padded with this
172757** many zero bytes. This makes it easier to decode the various record formats
172758** without overreading if the records are corrupt.
172759*/
172760#define FTS5_DATA_ZERO_PADDING 8
172761#define FTS5_DATA_PADDING 20
172762
172763typedef struct Fts5Data Fts5Data;
172764typedef struct Fts5DlidxIter Fts5DlidxIter;
172765typedef struct Fts5DlidxLvl Fts5DlidxLvl;
172766typedef struct Fts5DlidxWriter Fts5DlidxWriter;
172767typedef struct Fts5PageWriter Fts5PageWriter;
172768typedef struct Fts5SegIter Fts5SegIter;
172769typedef struct Fts5DoclistIter Fts5DoclistIter;
172770typedef struct Fts5SegWriter Fts5SegWriter;
172771typedef struct Fts5Structure Fts5Structure;
172772typedef struct Fts5StructureLevel Fts5StructureLevel;
172773typedef struct Fts5StructureSegment Fts5StructureSegment;
172774
172775struct Fts5Data {
172776  u8 *p;                          /* Pointer to buffer containing record */
172777  int nn;                         /* Size of record in bytes */
172778  int szLeaf;                     /* Size of leaf without page-index */
172779};
172780
172781/*
172782** One object per %_data table.
172783*/
172784struct Fts5Index {
172785  Fts5Config *pConfig;            /* Virtual table configuration */
172786  char *zDataTbl;                 /* Name of %_data table */
172787  int nWorkUnit;                  /* Leaf pages in a "unit" of work */
172788
172789  /*
172790  ** Variables related to the accumulation of tokens and doclists within the
172791  ** in-memory hash tables before they are flushed to disk.
172792  */
172793  Fts5Hash *pHash;                /* Hash table for in-memory data */
172794  int nMaxPendingData;            /* Max pending data before flush to disk */
172795  int nPendingData;               /* Current bytes of pending data */
172796  i64 iWriteRowid;                /* Rowid for current doc being written */
172797  int bDelete;                    /* Current write is a delete */
172798
172799  /* Error state. */
172800  int rc;                         /* Current error code */
172801
172802  /* State used by the fts5DataXXX() functions. */
172803  sqlite3_blob *pReader;          /* RO incr-blob open on %_data table */
172804  sqlite3_stmt *pWriter;          /* "INSERT ... %_data VALUES(?,?)" */
172805  sqlite3_stmt *pDeleter;         /* "DELETE FROM %_data ... id>=? AND id<=?" */
172806  sqlite3_stmt *pIdxWriter;       /* "INSERT ... %_idx VALUES(?,?,?,?)" */
172807  sqlite3_stmt *pIdxDeleter;      /* "DELETE FROM %_idx WHERE segid=? */
172808  sqlite3_stmt *pIdxSelect;
172809  int nRead;                      /* Total number of blocks read */
172810};
172811
172812struct Fts5DoclistIter {
172813  u8 *aEof;                       /* Pointer to 1 byte past end of doclist */
172814
172815  /* Output variables. aPoslist==0 at EOF */
172816  i64 iRowid;
172817  u8 *aPoslist;
172818  int nPoslist;
172819  int nSize;
172820};
172821
172822/*
172823** The contents of the "structure" record for each index are represented
172824** using an Fts5Structure record in memory. Which uses instances of the
172825** other Fts5StructureXXX types as components.
172826*/
172827struct Fts5StructureSegment {
172828  int iSegid;                     /* Segment id */
172829  int pgnoFirst;                  /* First leaf page number in segment */
172830  int pgnoLast;                   /* Last leaf page number in segment */
172831};
172832struct Fts5StructureLevel {
172833  int nMerge;                     /* Number of segments in incr-merge */
172834  int nSeg;                       /* Total number of segments on level */
172835  Fts5StructureSegment *aSeg;     /* Array of segments. aSeg[0] is oldest. */
172836};
172837struct Fts5Structure {
172838  int nRef;                       /* Object reference count */
172839  u64 nWriteCounter;              /* Total leaves written to level 0 */
172840  int nSegment;                   /* Total segments in this structure */
172841  int nLevel;                     /* Number of levels in this index */
172842  Fts5StructureLevel aLevel[1];   /* Array of nLevel level objects */
172843};
172844
172845/*
172846** An object of type Fts5SegWriter is used to write to segments.
172847*/
172848struct Fts5PageWriter {
172849  int pgno;                       /* Page number for this page */
172850  int iPrevPgidx;                 /* Previous value written into pgidx */
172851  Fts5Buffer buf;                 /* Buffer containing leaf data */
172852  Fts5Buffer pgidx;               /* Buffer containing page-index */
172853  Fts5Buffer term;                /* Buffer containing previous term on page */
172854};
172855struct Fts5DlidxWriter {
172856  int pgno;                       /* Page number for this page */
172857  int bPrevValid;                 /* True if iPrev is valid */
172858  i64 iPrev;                      /* Previous rowid value written to page */
172859  Fts5Buffer buf;                 /* Buffer containing page data */
172860};
172861struct Fts5SegWriter {
172862  int iSegid;                     /* Segid to write to */
172863  Fts5PageWriter writer;          /* PageWriter object */
172864  i64 iPrevRowid;                 /* Previous rowid written to current leaf */
172865  u8 bFirstRowidInDoclist;        /* True if next rowid is first in doclist */
172866  u8 bFirstRowidInPage;           /* True if next rowid is first in page */
172867  /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
172868  u8 bFirstTermInPage;            /* True if next term will be first in leaf */
172869  int nLeafWritten;               /* Number of leaf pages written */
172870  int nEmpty;                     /* Number of contiguous term-less nodes */
172871
172872  int nDlidx;                     /* Allocated size of aDlidx[] array */
172873  Fts5DlidxWriter *aDlidx;        /* Array of Fts5DlidxWriter objects */
172874
172875  /* Values to insert into the %_idx table */
172876  Fts5Buffer btterm;              /* Next term to insert into %_idx table */
172877  int iBtPage;                    /* Page number corresponding to btterm */
172878};
172879
172880/*
172881** Object for iterating through the merged results of one or more segments,
172882** visiting each term/rowid pair in the merged data.
172883**
172884** nSeg is always a power of two greater than or equal to the number of
172885** segments that this object is merging data from. Both the aSeg[] and
172886** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
172887** with zeroed objects - these are handled as if they were iterators opened
172888** on empty segments.
172889**
172890** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
172891** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
172892** comparison in this context is the index of the iterator that currently
172893** points to the smaller term/rowid combination. Iterators at EOF are
172894** considered to be greater than all other iterators.
172895**
172896** aFirst[1] contains the index in aSeg[] of the iterator that points to
172897** the smallest key overall. aFirst[0] is unused.
172898*/
172899
172900typedef struct Fts5CResult Fts5CResult;
172901struct Fts5CResult {
172902  u16 iFirst;                     /* aSeg[] index of firstest iterator */
172903  u8 bTermEq;                     /* True if the terms are equal */
172904};
172905
172906/*
172907** Object for iterating through a single segment, visiting each term/rowid
172908** pair in the segment.
172909**
172910** pSeg:
172911**   The segment to iterate through.
172912**
172913** iLeafPgno:
172914**   Current leaf page number within segment.
172915**
172916** iLeafOffset:
172917**   Byte offset within the current leaf that is the first byte of the
172918**   position list data (one byte passed the position-list size field).
172919**   rowid field of the current entry. Usually this is the size field of the
172920**   position list data. The exception is if the rowid for the current entry
172921**   is the last thing on the leaf page.
172922**
172923** pLeaf:
172924**   Buffer containing current leaf page data. Set to NULL at EOF.
172925**
172926** iTermLeafPgno, iTermLeafOffset:
172927**   Leaf page number containing the last term read from the segment. And
172928**   the offset immediately following the term data.
172929**
172930** flags:
172931**   Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
172932**
172933**   FTS5_SEGITER_ONETERM:
172934**     If set, set the iterator to point to EOF after the current doclist
172935**     has been exhausted. Do not proceed to the next term in the segment.
172936**
172937**   FTS5_SEGITER_REVERSE:
172938**     This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
172939**     it is set, iterate through rowid in descending order instead of the
172940**     default ascending order.
172941**
172942** iRowidOffset/nRowidOffset/aRowidOffset:
172943**     These are used if the FTS5_SEGITER_REVERSE flag is set.
172944**
172945**     For each rowid on the page corresponding to the current term, the
172946**     corresponding aRowidOffset[] entry is set to the byte offset of the
172947**     start of the "position-list-size" field within the page.
172948**
172949** iTermIdx:
172950**     Index of current term on iTermLeafPgno.
172951*/
172952struct Fts5SegIter {
172953  Fts5StructureSegment *pSeg;     /* Segment to iterate through */
172954  int flags;                      /* Mask of configuration flags */
172955  int iLeafPgno;                  /* Current leaf page number */
172956  Fts5Data *pLeaf;                /* Current leaf data */
172957  Fts5Data *pNextLeaf;            /* Leaf page (iLeafPgno+1) */
172958  int iLeafOffset;                /* Byte offset within current leaf */
172959
172960  /* The page and offset from which the current term was read. The offset
172961  ** is the offset of the first rowid in the current doclist.  */
172962  int iTermLeafPgno;
172963  int iTermLeafOffset;
172964
172965  int iPgidxOff;                  /* Next offset in pgidx */
172966  int iEndofDoclist;
172967
172968  /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
172969  int iRowidOffset;               /* Current entry in aRowidOffset[] */
172970  int nRowidOffset;               /* Allocated size of aRowidOffset[] array */
172971  int *aRowidOffset;              /* Array of offset to rowid fields */
172972
172973  Fts5DlidxIter *pDlidx;          /* If there is a doclist-index */
172974
172975  /* Variables populated based on current entry. */
172976  Fts5Buffer term;                /* Current term */
172977  i64 iRowid;                     /* Current rowid */
172978  int nPos;                       /* Number of bytes in current position list */
172979  int bDel;                       /* True if the delete flag is set */
172980};
172981
172982/*
172983** Argument is a pointer to an Fts5Data structure that contains a
172984** leaf page.
172985*/
172986#define ASSERT_SZLEAF_OK(x) assert( \
172987    (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
172988)
172989
172990#define FTS5_SEGITER_ONETERM 0x01
172991#define FTS5_SEGITER_REVERSE 0x02
172992
172993
172994/*
172995** Argument is a pointer to an Fts5Data structure that contains a leaf
172996** page. This macro evaluates to true if the leaf contains no terms, or
172997** false if it contains at least one term.
172998*/
172999#define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
173000
173001#define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
173002
173003#define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
173004
173005/*
173006** poslist:
173007**   Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
173008**   There is no way to tell if this is populated or not.
173009*/
173010struct Fts5IndexIter {
173011  Fts5Index *pIndex;              /* Index that owns this iterator */
173012  Fts5Structure *pStruct;         /* Database structure for this iterator */
173013  Fts5Buffer poslist;             /* Buffer containing current poslist */
173014
173015  int nSeg;                       /* Size of aSeg[] array */
173016  int bRev;                       /* True to iterate in reverse order */
173017  u8 bSkipEmpty;                  /* True to skip deleted entries */
173018  u8 bEof;                        /* True at EOF */
173019  u8 bFiltered;                   /* True if column-filter already applied */
173020
173021  i64 iSwitchRowid;               /* Firstest rowid of other than aFirst[1] */
173022  Fts5CResult *aFirst;            /* Current merge state (see above) */
173023  Fts5SegIter aSeg[1];            /* Array of segment iterators */
173024};
173025
173026
173027/*
173028** An instance of the following type is used to iterate through the contents
173029** of a doclist-index record.
173030**
173031** pData:
173032**   Record containing the doclist-index data.
173033**
173034** bEof:
173035**   Set to true once iterator has reached EOF.
173036**
173037** iOff:
173038**   Set to the current offset within record pData.
173039*/
173040struct Fts5DlidxLvl {
173041  Fts5Data *pData;              /* Data for current page of this level */
173042  int iOff;                     /* Current offset into pData */
173043  int bEof;                     /* At EOF already */
173044  int iFirstOff;                /* Used by reverse iterators */
173045
173046  /* Output variables */
173047  int iLeafPgno;                /* Page number of current leaf page */
173048  i64 iRowid;                   /* First rowid on leaf iLeafPgno */
173049};
173050struct Fts5DlidxIter {
173051  int nLvl;
173052  int iSegid;
173053  Fts5DlidxLvl aLvl[1];
173054};
173055
173056static void fts5PutU16(u8 *aOut, u16 iVal){
173057  aOut[0] = (iVal>>8);
173058  aOut[1] = (iVal&0xFF);
173059}
173060
173061static u16 fts5GetU16(const u8 *aIn){
173062  return ((u16)aIn[0] << 8) + aIn[1];
173063}
173064
173065/*
173066** Allocate and return a buffer at least nByte bytes in size.
173067**
173068** If an OOM error is encountered, return NULL and set the error code in
173069** the Fts5Index handle passed as the first argument.
173070*/
173071static void *fts5IdxMalloc(Fts5Index *p, int nByte){
173072  return sqlite3Fts5MallocZero(&p->rc, nByte);
173073}
173074
173075/*
173076** Compare the contents of the pLeft buffer with the pRight/nRight blob.
173077**
173078** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
173079** +ve if pRight is smaller than pLeft. In other words:
173080**
173081**     res = *pLeft - *pRight
173082*/
173083#ifdef SQLITE_DEBUG
173084static int fts5BufferCompareBlob(
173085  Fts5Buffer *pLeft,              /* Left hand side of comparison */
173086  const u8 *pRight, int nRight    /* Right hand side of comparison */
173087){
173088  int nCmp = MIN(pLeft->n, nRight);
173089  int res = memcmp(pLeft->p, pRight, nCmp);
173090  return (res==0 ? (pLeft->n - nRight) : res);
173091}
173092#endif
173093
173094/*
173095** Compare the contents of the two buffers using memcmp(). If one buffer
173096** is a prefix of the other, it is considered the lesser.
173097**
173098** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
173099** +ve if pRight is smaller than pLeft. In other words:
173100**
173101**     res = *pLeft - *pRight
173102*/
173103static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
173104  int nCmp = MIN(pLeft->n, pRight->n);
173105  int res = memcmp(pLeft->p, pRight->p, nCmp);
173106  return (res==0 ? (pLeft->n - pRight->n) : res);
173107}
173108
173109#ifdef SQLITE_DEBUG
173110static int fts5BlobCompare(
173111  const u8 *pLeft, int nLeft,
173112  const u8 *pRight, int nRight
173113){
173114  int nCmp = MIN(nLeft, nRight);
173115  int res = memcmp(pLeft, pRight, nCmp);
173116  return (res==0 ? (nLeft - nRight) : res);
173117}
173118#endif
173119
173120static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
173121  int ret;
173122  fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
173123  return ret;
173124}
173125
173126/*
173127** Close the read-only blob handle, if it is open.
173128*/
173129static void fts5CloseReader(Fts5Index *p){
173130  if( p->pReader ){
173131    sqlite3_blob *pReader = p->pReader;
173132    p->pReader = 0;
173133    sqlite3_blob_close(pReader);
173134  }
173135}
173136
173137
173138/*
173139** Retrieve a record from the %_data table.
173140**
173141** If an error occurs, NULL is returned and an error left in the
173142** Fts5Index object.
173143*/
173144static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
173145  Fts5Data *pRet = 0;
173146  if( p->rc==SQLITE_OK ){
173147    int rc = SQLITE_OK;
173148
173149    if( p->pReader ){
173150      /* This call may return SQLITE_ABORT if there has been a savepoint
173151      ** rollback since it was last used. In this case a new blob handle
173152      ** is required.  */
173153      sqlite3_blob *pBlob = p->pReader;
173154      p->pReader = 0;
173155      rc = sqlite3_blob_reopen(pBlob, iRowid);
173156      assert( p->pReader==0 );
173157      p->pReader = pBlob;
173158      if( rc!=SQLITE_OK ){
173159        fts5CloseReader(p);
173160      }
173161      if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
173162    }
173163
173164    /* If the blob handle is not open at this point, open it and seek
173165    ** to the requested entry.  */
173166    if( p->pReader==0 && rc==SQLITE_OK ){
173167      Fts5Config *pConfig = p->pConfig;
173168      rc = sqlite3_blob_open(pConfig->db,
173169          pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
173170      );
173171    }
173172
173173    /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
173174    ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
173175    ** All the reasons those functions might return SQLITE_ERROR - missing
173176    ** table, missing row, non-blob/text in block column - indicate
173177    ** backing store corruption.  */
173178    if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
173179
173180    if( rc==SQLITE_OK ){
173181      u8 *aOut = 0;               /* Read blob data into this buffer */
173182      int nByte = sqlite3_blob_bytes(p->pReader);
173183      int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
173184      pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
173185      if( pRet ){
173186        pRet->nn = nByte;
173187        aOut = pRet->p = (u8*)&pRet[1];
173188      }else{
173189        rc = SQLITE_NOMEM;
173190      }
173191
173192      if( rc==SQLITE_OK ){
173193        rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
173194      }
173195      if( rc!=SQLITE_OK ){
173196        sqlite3_free(pRet);
173197        pRet = 0;
173198      }else{
173199        /* TODO1: Fix this */
173200        pRet->szLeaf = fts5GetU16(&pRet->p[2]);
173201      }
173202    }
173203    p->rc = rc;
173204    p->nRead++;
173205  }
173206
173207  assert( (pRet==0)==(p->rc!=SQLITE_OK) );
173208  return pRet;
173209}
173210
173211/*
173212** Release a reference to data record returned by an earlier call to
173213** fts5DataRead().
173214*/
173215static void fts5DataRelease(Fts5Data *pData){
173216  sqlite3_free(pData);
173217}
173218
173219static int fts5IndexPrepareStmt(
173220  Fts5Index *p,
173221  sqlite3_stmt **ppStmt,
173222  char *zSql
173223){
173224  if( p->rc==SQLITE_OK ){
173225    if( zSql ){
173226      p->rc = sqlite3_prepare_v2(p->pConfig->db, zSql, -1, ppStmt, 0);
173227    }else{
173228      p->rc = SQLITE_NOMEM;
173229    }
173230  }
173231  sqlite3_free(zSql);
173232  return p->rc;
173233}
173234
173235
173236/*
173237** INSERT OR REPLACE a record into the %_data table.
173238*/
173239static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
173240  if( p->rc!=SQLITE_OK ) return;
173241
173242  if( p->pWriter==0 ){
173243    Fts5Config *pConfig = p->pConfig;
173244    fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
173245          "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
173246          pConfig->zDb, pConfig->zName
173247    ));
173248    if( p->rc ) return;
173249  }
173250
173251  sqlite3_bind_int64(p->pWriter, 1, iRowid);
173252  sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
173253  sqlite3_step(p->pWriter);
173254  p->rc = sqlite3_reset(p->pWriter);
173255}
173256
173257/*
173258** Execute the following SQL:
173259**
173260**     DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
173261*/
173262static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
173263  if( p->rc!=SQLITE_OK ) return;
173264
173265  if( p->pDeleter==0 ){
173266    int rc;
173267    Fts5Config *pConfig = p->pConfig;
173268    char *zSql = sqlite3_mprintf(
173269        "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
173270          pConfig->zDb, pConfig->zName
173271    );
173272    if( zSql==0 ){
173273      rc = SQLITE_NOMEM;
173274    }else{
173275      rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p->pDeleter, 0);
173276      sqlite3_free(zSql);
173277    }
173278    if( rc!=SQLITE_OK ){
173279      p->rc = rc;
173280      return;
173281    }
173282  }
173283
173284  sqlite3_bind_int64(p->pDeleter, 1, iFirst);
173285  sqlite3_bind_int64(p->pDeleter, 2, iLast);
173286  sqlite3_step(p->pDeleter);
173287  p->rc = sqlite3_reset(p->pDeleter);
173288}
173289
173290/*
173291** Remove all records associated with segment iSegid.
173292*/
173293static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
173294  i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
173295  i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
173296  fts5DataDelete(p, iFirst, iLast);
173297  if( p->pIdxDeleter==0 ){
173298    Fts5Config *pConfig = p->pConfig;
173299    fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
173300          "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
173301          pConfig->zDb, pConfig->zName
173302    ));
173303  }
173304  if( p->rc==SQLITE_OK ){
173305    sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
173306    sqlite3_step(p->pIdxDeleter);
173307    p->rc = sqlite3_reset(p->pIdxDeleter);
173308  }
173309}
173310
173311/*
173312** Release a reference to an Fts5Structure object returned by an earlier
173313** call to fts5StructureRead() or fts5StructureDecode().
173314*/
173315static void fts5StructureRelease(Fts5Structure *pStruct){
173316  if( pStruct && 0>=(--pStruct->nRef) ){
173317    int i;
173318    assert( pStruct->nRef==0 );
173319    for(i=0; i<pStruct->nLevel; i++){
173320      sqlite3_free(pStruct->aLevel[i].aSeg);
173321    }
173322    sqlite3_free(pStruct);
173323  }
173324}
173325
173326static void fts5StructureRef(Fts5Structure *pStruct){
173327  pStruct->nRef++;
173328}
173329
173330/*
173331** Deserialize and return the structure record currently stored in serialized
173332** form within buffer pData/nData.
173333**
173334** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
173335** are over-allocated by one slot. This allows the structure contents
173336** to be more easily edited.
173337**
173338** If an error occurs, *ppOut is set to NULL and an SQLite error code
173339** returned. Otherwise, *ppOut is set to point to the new object and
173340** SQLITE_OK returned.
173341*/
173342static int fts5StructureDecode(
173343  const u8 *pData,                /* Buffer containing serialized structure */
173344  int nData,                      /* Size of buffer pData in bytes */
173345  int *piCookie,                  /* Configuration cookie value */
173346  Fts5Structure **ppOut           /* OUT: Deserialized object */
173347){
173348  int rc = SQLITE_OK;
173349  int i = 0;
173350  int iLvl;
173351  int nLevel = 0;
173352  int nSegment = 0;
173353  int nByte;                      /* Bytes of space to allocate at pRet */
173354  Fts5Structure *pRet = 0;        /* Structure object to return */
173355
173356  /* Grab the cookie value */
173357  if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
173358  i = 4;
173359
173360  /* Read the total number of levels and segments from the start of the
173361  ** structure record.  */
173362  i += fts5GetVarint32(&pData[i], nLevel);
173363  i += fts5GetVarint32(&pData[i], nSegment);
173364  nByte = (
173365      sizeof(Fts5Structure) +                    /* Main structure */
173366      sizeof(Fts5StructureLevel) * (nLevel-1)    /* aLevel[] array */
173367  );
173368  pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
173369
173370  if( pRet ){
173371    pRet->nRef = 1;
173372    pRet->nLevel = nLevel;
173373    pRet->nSegment = nSegment;
173374    i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
173375
173376    for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
173377      Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
173378      int nTotal;
173379      int iSeg;
173380
173381      i += fts5GetVarint32(&pData[i], pLvl->nMerge);
173382      i += fts5GetVarint32(&pData[i], nTotal);
173383      assert( nTotal>=pLvl->nMerge );
173384      pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
173385          nTotal * sizeof(Fts5StructureSegment)
173386      );
173387
173388      if( rc==SQLITE_OK ){
173389        pLvl->nSeg = nTotal;
173390        for(iSeg=0; iSeg<nTotal; iSeg++){
173391          i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
173392          i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
173393          i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
173394        }
173395      }else{
173396        fts5StructureRelease(pRet);
173397        pRet = 0;
173398      }
173399    }
173400  }
173401
173402  *ppOut = pRet;
173403  return rc;
173404}
173405
173406/*
173407**
173408*/
173409static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
173410  if( *pRc==SQLITE_OK ){
173411    Fts5Structure *pStruct = *ppStruct;
173412    int nLevel = pStruct->nLevel;
173413    int nByte = (
173414        sizeof(Fts5Structure) +                  /* Main structure */
173415        sizeof(Fts5StructureLevel) * (nLevel+1)  /* aLevel[] array */
173416    );
173417
173418    pStruct = sqlite3_realloc(pStruct, nByte);
173419    if( pStruct ){
173420      memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
173421      pStruct->nLevel++;
173422      *ppStruct = pStruct;
173423    }else{
173424      *pRc = SQLITE_NOMEM;
173425    }
173426  }
173427}
173428
173429/*
173430** Extend level iLvl so that there is room for at least nExtra more
173431** segments.
173432*/
173433static void fts5StructureExtendLevel(
173434  int *pRc,
173435  Fts5Structure *pStruct,
173436  int iLvl,
173437  int nExtra,
173438  int bInsert
173439){
173440  if( *pRc==SQLITE_OK ){
173441    Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
173442    Fts5StructureSegment *aNew;
173443    int nByte;
173444
173445    nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
173446    aNew = sqlite3_realloc(pLvl->aSeg, nByte);
173447    if( aNew ){
173448      if( bInsert==0 ){
173449        memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
173450      }else{
173451        int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
173452        memmove(&aNew[nExtra], aNew, nMove);
173453        memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
173454      }
173455      pLvl->aSeg = aNew;
173456    }else{
173457      *pRc = SQLITE_NOMEM;
173458    }
173459  }
173460}
173461
173462/*
173463** Read, deserialize and return the structure record.
173464**
173465** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
173466** are over-allocated as described for function fts5StructureDecode()
173467** above.
173468**
173469** If an error occurs, NULL is returned and an error code left in the
173470** Fts5Index handle. If an error has already occurred when this function
173471** is called, it is a no-op.
173472*/
173473static Fts5Structure *fts5StructureRead(Fts5Index *p){
173474  Fts5Config *pConfig = p->pConfig;
173475  Fts5Structure *pRet = 0;        /* Object to return */
173476  int iCookie;                    /* Configuration cookie */
173477  Fts5Data *pData;
173478
173479  pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
173480  if( p->rc ) return 0;
173481  /* TODO: Do we need this if the leaf-index is appended? Probably... */
173482  memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
173483  p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
173484  if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
173485    p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
173486  }
173487
173488  fts5DataRelease(pData);
173489  if( p->rc!=SQLITE_OK ){
173490    fts5StructureRelease(pRet);
173491    pRet = 0;
173492  }
173493  return pRet;
173494}
173495
173496/*
173497** Return the total number of segments in index structure pStruct. This
173498** function is only ever used as part of assert() conditions.
173499*/
173500#ifdef SQLITE_DEBUG
173501static int fts5StructureCountSegments(Fts5Structure *pStruct){
173502  int nSegment = 0;               /* Total number of segments */
173503  if( pStruct ){
173504    int iLvl;                     /* Used to iterate through levels */
173505    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
173506      nSegment += pStruct->aLevel[iLvl].nSeg;
173507    }
173508  }
173509
173510  return nSegment;
173511}
173512#endif
173513
173514/*
173515** Serialize and store the "structure" record.
173516**
173517** If an error occurs, leave an error code in the Fts5Index object. If an
173518** error has already occurred, this function is a no-op.
173519*/
173520static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
173521  if( p->rc==SQLITE_OK ){
173522    Fts5Buffer buf;               /* Buffer to serialize record into */
173523    int iLvl;                     /* Used to iterate through levels */
173524    int iCookie;                  /* Cookie value to store */
173525
173526    assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
173527    memset(&buf, 0, sizeof(Fts5Buffer));
173528
173529    /* Append the current configuration cookie */
173530    iCookie = p->pConfig->iCookie;
173531    if( iCookie<0 ) iCookie = 0;
173532    fts5BufferAppend32(&p->rc, &buf, iCookie);
173533
173534    fts5BufferAppendVarint(&p->rc, &buf, pStruct->nLevel);
173535    fts5BufferAppendVarint(&p->rc, &buf, pStruct->nSegment);
173536    fts5BufferAppendVarint(&p->rc, &buf, (i64)pStruct->nWriteCounter);
173537
173538    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
173539      int iSeg;                     /* Used to iterate through segments */
173540      Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
173541      fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
173542      fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
173543      assert( pLvl->nMerge<=pLvl->nSeg );
173544
173545      for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
173546        fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
173547        fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
173548        fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
173549      }
173550    }
173551
173552    fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
173553    fts5BufferFree(&buf);
173554  }
173555}
173556
173557#if 0
173558static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
173559static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
173560  int rc = SQLITE_OK;
173561  Fts5Buffer buf;
173562  memset(&buf, 0, sizeof(buf));
173563  fts5DebugStructure(&rc, &buf, pStruct);
173564  fprintf(stdout, "%s: %s\n", zCaption, buf.p);
173565  fflush(stdout);
173566  fts5BufferFree(&buf);
173567}
173568#else
173569# define fts5PrintStructure(x,y)
173570#endif
173571
173572static int fts5SegmentSize(Fts5StructureSegment *pSeg){
173573  return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
173574}
173575
173576/*
173577** Return a copy of index structure pStruct. Except, promote as many
173578** segments as possible to level iPromote. If an OOM occurs, NULL is
173579** returned.
173580*/
173581static void fts5StructurePromoteTo(
173582  Fts5Index *p,
173583  int iPromote,
173584  int szPromote,
173585  Fts5Structure *pStruct
173586){
173587  int il, is;
173588  Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
173589
173590  if( pOut->nMerge==0 ){
173591    for(il=iPromote+1; il<pStruct->nLevel; il++){
173592      Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
173593      if( pLvl->nMerge ) return;
173594      for(is=pLvl->nSeg-1; is>=0; is--){
173595        int sz = fts5SegmentSize(&pLvl->aSeg[is]);
173596        if( sz>szPromote ) return;
173597        fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
173598        if( p->rc ) return;
173599        memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
173600        pOut->nSeg++;
173601        pLvl->nSeg--;
173602      }
173603    }
173604  }
173605}
173606
173607/*
173608** A new segment has just been written to level iLvl of index structure
173609** pStruct. This function determines if any segments should be promoted
173610** as a result. Segments are promoted in two scenarios:
173611**
173612**   a) If the segment just written is smaller than one or more segments
173613**      within the previous populated level, it is promoted to the previous
173614**      populated level.
173615**
173616**   b) If the segment just written is larger than the newest segment on
173617**      the next populated level, then that segment, and any other adjacent
173618**      segments that are also smaller than the one just written, are
173619**      promoted.
173620**
173621** If one or more segments are promoted, the structure object is updated
173622** to reflect this.
173623*/
173624static void fts5StructurePromote(
173625  Fts5Index *p,                   /* FTS5 backend object */
173626  int iLvl,                       /* Index level just updated */
173627  Fts5Structure *pStruct          /* Index structure */
173628){
173629  if( p->rc==SQLITE_OK ){
173630    int iTst;
173631    int iPromote = -1;
173632    int szPromote = 0;            /* Promote anything this size or smaller */
173633    Fts5StructureSegment *pSeg;   /* Segment just written */
173634    int szSeg;                    /* Size of segment just written */
173635    int nSeg = pStruct->aLevel[iLvl].nSeg;
173636
173637    if( nSeg==0 ) return;
173638    pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
173639    szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
173640
173641    /* Check for condition (a) */
173642    for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
173643    if( iTst>=0 ){
173644      int i;
173645      int szMax = 0;
173646      Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
173647      assert( pTst->nMerge==0 );
173648      for(i=0; i<pTst->nSeg; i++){
173649        int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
173650        if( sz>szMax ) szMax = sz;
173651      }
173652      if( szMax>=szSeg ){
173653        /* Condition (a) is true. Promote the newest segment on level
173654        ** iLvl to level iTst.  */
173655        iPromote = iTst;
173656        szPromote = szMax;
173657      }
173658    }
173659
173660    /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
173661    ** is a no-op if it is not.  */
173662    if( iPromote<0 ){
173663      iPromote = iLvl;
173664      szPromote = szSeg;
173665    }
173666    fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
173667  }
173668}
173669
173670
173671/*
173672** Advance the iterator passed as the only argument. If the end of the
173673** doclist-index page is reached, return non-zero.
173674*/
173675static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
173676  Fts5Data *pData = pLvl->pData;
173677
173678  if( pLvl->iOff==0 ){
173679    assert( pLvl->bEof==0 );
173680    pLvl->iOff = 1;
173681    pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
173682    pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
173683    pLvl->iFirstOff = pLvl->iOff;
173684  }else{
173685    int iOff;
173686    for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
173687      if( pData->p[iOff] ) break;
173688    }
173689
173690    if( iOff<pData->nn ){
173691      i64 iVal;
173692      pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
173693      iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
173694      pLvl->iRowid += iVal;
173695      pLvl->iOff = iOff;
173696    }else{
173697      pLvl->bEof = 1;
173698    }
173699  }
173700
173701  return pLvl->bEof;
173702}
173703
173704/*
173705** Advance the iterator passed as the only argument.
173706*/
173707static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
173708  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
173709
173710  assert( iLvl<pIter->nLvl );
173711  if( fts5DlidxLvlNext(pLvl) ){
173712    if( (iLvl+1) < pIter->nLvl ){
173713      fts5DlidxIterNextR(p, pIter, iLvl+1);
173714      if( pLvl[1].bEof==0 ){
173715        fts5DataRelease(pLvl->pData);
173716        memset(pLvl, 0, sizeof(Fts5DlidxLvl));
173717        pLvl->pData = fts5DataRead(p,
173718            FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
173719        );
173720        if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
173721      }
173722    }
173723  }
173724
173725  return pIter->aLvl[0].bEof;
173726}
173727static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
173728  return fts5DlidxIterNextR(p, pIter, 0);
173729}
173730
173731/*
173732** The iterator passed as the first argument has the following fields set
173733** as follows. This function sets up the rest of the iterator so that it
173734** points to the first rowid in the doclist-index.
173735**
173736**   pData:
173737**     pointer to doclist-index record,
173738**
173739** When this function is called pIter->iLeafPgno is the page number the
173740** doclist is associated with (the one featuring the term).
173741*/
173742static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
173743  int i;
173744  for(i=0; i<pIter->nLvl; i++){
173745    fts5DlidxLvlNext(&pIter->aLvl[i]);
173746  }
173747  return pIter->aLvl[0].bEof;
173748}
173749
173750
173751static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
173752  return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
173753}
173754
173755static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
173756  int i;
173757
173758  /* Advance each level to the last entry on the last page */
173759  for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
173760    Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
173761    while( fts5DlidxLvlNext(pLvl)==0 );
173762    pLvl->bEof = 0;
173763
173764    if( i>0 ){
173765      Fts5DlidxLvl *pChild = &pLvl[-1];
173766      fts5DataRelease(pChild->pData);
173767      memset(pChild, 0, sizeof(Fts5DlidxLvl));
173768      pChild->pData = fts5DataRead(p,
173769          FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
173770      );
173771    }
173772  }
173773}
173774
173775/*
173776** Move the iterator passed as the only argument to the previous entry.
173777*/
173778static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
173779  int iOff = pLvl->iOff;
173780
173781  assert( pLvl->bEof==0 );
173782  if( iOff<=pLvl->iFirstOff ){
173783    pLvl->bEof = 1;
173784  }else{
173785    u8 *a = pLvl->pData->p;
173786    i64 iVal;
173787    int iLimit;
173788    int ii;
173789    int nZero = 0;
173790
173791    /* Currently iOff points to the first byte of a varint. This block
173792    ** decrements iOff until it points to the first byte of the previous
173793    ** varint. Taking care not to read any memory locations that occur
173794    ** before the buffer in memory.  */
173795    iLimit = (iOff>9 ? iOff-9 : 0);
173796    for(iOff--; iOff>iLimit; iOff--){
173797      if( (a[iOff-1] & 0x80)==0 ) break;
173798    }
173799
173800    fts5GetVarint(&a[iOff], (u64*)&iVal);
173801    pLvl->iRowid -= iVal;
173802    pLvl->iLeafPgno--;
173803
173804    /* Skip backwards past any 0x00 varints. */
173805    for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
173806      nZero++;
173807    }
173808    if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
173809      /* The byte immediately before the last 0x00 byte has the 0x80 bit
173810      ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
173811      ** bytes before a[ii]. */
173812      int bZero = 0;              /* True if last 0x00 counts */
173813      if( (ii-8)>=pLvl->iFirstOff ){
173814        int j;
173815        for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
173816        bZero = (j>8);
173817      }
173818      if( bZero==0 ) nZero--;
173819    }
173820    pLvl->iLeafPgno -= nZero;
173821    pLvl->iOff = iOff - nZero;
173822  }
173823
173824  return pLvl->bEof;
173825}
173826
173827static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
173828  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
173829
173830  assert( iLvl<pIter->nLvl );
173831  if( fts5DlidxLvlPrev(pLvl) ){
173832    if( (iLvl+1) < pIter->nLvl ){
173833      fts5DlidxIterPrevR(p, pIter, iLvl+1);
173834      if( pLvl[1].bEof==0 ){
173835        fts5DataRelease(pLvl->pData);
173836        memset(pLvl, 0, sizeof(Fts5DlidxLvl));
173837        pLvl->pData = fts5DataRead(p,
173838            FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
173839        );
173840        if( pLvl->pData ){
173841          while( fts5DlidxLvlNext(pLvl)==0 );
173842          pLvl->bEof = 0;
173843        }
173844      }
173845    }
173846  }
173847
173848  return pIter->aLvl[0].bEof;
173849}
173850static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
173851  return fts5DlidxIterPrevR(p, pIter, 0);
173852}
173853
173854/*
173855** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
173856*/
173857static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
173858  if( pIter ){
173859    int i;
173860    for(i=0; i<pIter->nLvl; i++){
173861      fts5DataRelease(pIter->aLvl[i].pData);
173862    }
173863    sqlite3_free(pIter);
173864  }
173865}
173866
173867static Fts5DlidxIter *fts5DlidxIterInit(
173868  Fts5Index *p,                   /* Fts5 Backend to iterate within */
173869  int bRev,                       /* True for ORDER BY ASC */
173870  int iSegid,                     /* Segment id */
173871  int iLeafPg                     /* Leaf page number to load dlidx for */
173872){
173873  Fts5DlidxIter *pIter = 0;
173874  int i;
173875  int bDone = 0;
173876
173877  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
173878    int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
173879    Fts5DlidxIter *pNew;
173880
173881    pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
173882    if( pNew==0 ){
173883      p->rc = SQLITE_NOMEM;
173884    }else{
173885      i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
173886      Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
173887      pIter = pNew;
173888      memset(pLvl, 0, sizeof(Fts5DlidxLvl));
173889      pLvl->pData = fts5DataRead(p, iRowid);
173890      if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
173891        bDone = 1;
173892      }
173893      pIter->nLvl = i+1;
173894    }
173895  }
173896
173897  if( p->rc==SQLITE_OK ){
173898    pIter->iSegid = iSegid;
173899    if( bRev==0 ){
173900      fts5DlidxIterFirst(pIter);
173901    }else{
173902      fts5DlidxIterLast(p, pIter);
173903    }
173904  }
173905
173906  if( p->rc!=SQLITE_OK ){
173907    fts5DlidxIterFree(pIter);
173908    pIter = 0;
173909  }
173910
173911  return pIter;
173912}
173913
173914static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
173915  return pIter->aLvl[0].iRowid;
173916}
173917static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
173918  return pIter->aLvl[0].iLeafPgno;
173919}
173920
173921/*
173922** Load the next leaf page into the segment iterator.
173923*/
173924static void fts5SegIterNextPage(
173925  Fts5Index *p,                   /* FTS5 backend object */
173926  Fts5SegIter *pIter              /* Iterator to advance to next page */
173927){
173928  Fts5Data *pLeaf;
173929  Fts5StructureSegment *pSeg = pIter->pSeg;
173930  fts5DataRelease(pIter->pLeaf);
173931  pIter->iLeafPgno++;
173932  if( pIter->pNextLeaf ){
173933    pIter->pLeaf = pIter->pNextLeaf;
173934    pIter->pNextLeaf = 0;
173935  }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
173936    pIter->pLeaf = fts5DataRead(p,
173937        FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
173938    );
173939  }else{
173940    pIter->pLeaf = 0;
173941  }
173942  pLeaf = pIter->pLeaf;
173943
173944  if( pLeaf ){
173945    pIter->iPgidxOff = pLeaf->szLeaf;
173946    if( fts5LeafIsTermless(pLeaf) ){
173947      pIter->iEndofDoclist = pLeaf->nn+1;
173948    }else{
173949      pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
173950          pIter->iEndofDoclist
173951      );
173952    }
173953  }
173954}
173955
173956/*
173957** Argument p points to a buffer containing a varint to be interpreted as a
173958** position list size field. Read the varint and return the number of bytes
173959** read. Before returning, set *pnSz to the number of bytes in the position
173960** list, and *pbDel to true if the delete flag is set, or false otherwise.
173961*/
173962static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
173963  int nSz;
173964  int n = 0;
173965  fts5FastGetVarint32(p, n, nSz);
173966  assert_nc( nSz>=0 );
173967  *pnSz = nSz/2;
173968  *pbDel = nSz & 0x0001;
173969  return n;
173970}
173971
173972/*
173973** Fts5SegIter.iLeafOffset currently points to the first byte of a
173974** position-list size field. Read the value of the field and store it
173975** in the following variables:
173976**
173977**   Fts5SegIter.nPos
173978**   Fts5SegIter.bDel
173979**
173980** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
173981** position list content (if any).
173982*/
173983static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
173984  if( p->rc==SQLITE_OK ){
173985    int iOff = pIter->iLeafOffset;  /* Offset to read at */
173986    int nSz;
173987    ASSERT_SZLEAF_OK(pIter->pLeaf);
173988    fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
173989    pIter->bDel = (nSz & 0x0001);
173990    pIter->nPos = nSz>>1;
173991    pIter->iLeafOffset = iOff;
173992  }
173993}
173994
173995static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
173996  u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
173997  int iOff = pIter->iLeafOffset;
173998
173999  ASSERT_SZLEAF_OK(pIter->pLeaf);
174000  if( iOff>=pIter->pLeaf->szLeaf ){
174001    fts5SegIterNextPage(p, pIter);
174002    if( pIter->pLeaf==0 ){
174003      if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
174004      return;
174005    }
174006    iOff = 4;
174007    a = pIter->pLeaf->p;
174008  }
174009  iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
174010  pIter->iLeafOffset = iOff;
174011}
174012
174013/*
174014** Fts5SegIter.iLeafOffset currently points to the first byte of the
174015** "nSuffix" field of a term. Function parameter nKeep contains the value
174016** of the "nPrefix" field (if there was one - it is passed 0 if this is
174017** the first term in the segment).
174018**
174019** This function populates:
174020**
174021**   Fts5SegIter.term
174022**   Fts5SegIter.rowid
174023**
174024** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
174025** the first position list. The position list belonging to document
174026** (Fts5SegIter.iRowid).
174027*/
174028static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
174029  u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
174030  int iOff = pIter->iLeafOffset;  /* Offset to read at */
174031  int nNew;                       /* Bytes of new data */
174032
174033  iOff += fts5GetVarint32(&a[iOff], nNew);
174034  pIter->term.n = nKeep;
174035  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
174036  iOff += nNew;
174037  pIter->iTermLeafOffset = iOff;
174038  pIter->iTermLeafPgno = pIter->iLeafPgno;
174039  pIter->iLeafOffset = iOff;
174040
174041  if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
174042    pIter->iEndofDoclist = pIter->pLeaf->nn+1;
174043  }else{
174044    int nExtra;
174045    pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
174046    pIter->iEndofDoclist += nExtra;
174047  }
174048
174049  fts5SegIterLoadRowid(p, pIter);
174050}
174051
174052/*
174053** Initialize the iterator object pIter to iterate through the entries in
174054** segment pSeg. The iterator is left pointing to the first entry when
174055** this function returns.
174056**
174057** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
174058** an error has already occurred when this function is called, it is a no-op.
174059*/
174060static void fts5SegIterInit(
174061  Fts5Index *p,                   /* FTS index object */
174062  Fts5StructureSegment *pSeg,     /* Description of segment */
174063  Fts5SegIter *pIter              /* Object to populate */
174064){
174065  if( pSeg->pgnoFirst==0 ){
174066    /* This happens if the segment is being used as an input to an incremental
174067    ** merge and all data has already been "trimmed". See function
174068    ** fts5TrimSegments() for details. In this case leave the iterator empty.
174069    ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
174070    ** at EOF already. */
174071    assert( pIter->pLeaf==0 );
174072    return;
174073  }
174074
174075  if( p->rc==SQLITE_OK ){
174076    memset(pIter, 0, sizeof(*pIter));
174077    pIter->pSeg = pSeg;
174078    pIter->iLeafPgno = pSeg->pgnoFirst-1;
174079    fts5SegIterNextPage(p, pIter);
174080  }
174081
174082  if( p->rc==SQLITE_OK ){
174083    pIter->iLeafOffset = 4;
174084    assert_nc( pIter->pLeaf->nn>4 );
174085    assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
174086    pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
174087    fts5SegIterLoadTerm(p, pIter, 0);
174088    fts5SegIterLoadNPos(p, pIter);
174089  }
174090}
174091
174092/*
174093** This function is only ever called on iterators created by calls to
174094** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
174095**
174096** The iterator is in an unusual state when this function is called: the
174097** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
174098** the position-list size field for the first relevant rowid on the page.
174099** Fts5SegIter.rowid is set, but nPos and bDel are not.
174100**
174101** This function advances the iterator so that it points to the last
174102** relevant rowid on the page and, if necessary, initializes the
174103** aRowidOffset[] and iRowidOffset variables. At this point the iterator
174104** is in its regular state - Fts5SegIter.iLeafOffset points to the first
174105** byte of the position list content associated with said rowid.
174106*/
174107static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
174108  int n = pIter->pLeaf->szLeaf;
174109  int i = pIter->iLeafOffset;
174110  u8 *a = pIter->pLeaf->p;
174111  int iRowidOffset = 0;
174112
174113  if( n>pIter->iEndofDoclist ){
174114    n = pIter->iEndofDoclist;
174115  }
174116
174117  ASSERT_SZLEAF_OK(pIter->pLeaf);
174118  while( 1 ){
174119    i64 iDelta = 0;
174120    int nPos;
174121    int bDummy;
174122
174123    i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
174124    i += nPos;
174125    if( i>=n ) break;
174126    i += fts5GetVarint(&a[i], (u64*)&iDelta);
174127    pIter->iRowid += iDelta;
174128
174129    if( iRowidOffset>=pIter->nRowidOffset ){
174130      int nNew = pIter->nRowidOffset + 8;
174131      int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
174132      if( aNew==0 ){
174133        p->rc = SQLITE_NOMEM;
174134        break;
174135      }
174136      pIter->aRowidOffset = aNew;
174137      pIter->nRowidOffset = nNew;
174138    }
174139
174140    pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
174141    pIter->iLeafOffset = i;
174142  }
174143  pIter->iRowidOffset = iRowidOffset;
174144  fts5SegIterLoadNPos(p, pIter);
174145}
174146
174147/*
174148**
174149*/
174150static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
174151  assert( pIter->flags & FTS5_SEGITER_REVERSE );
174152  assert( pIter->flags & FTS5_SEGITER_ONETERM );
174153
174154  fts5DataRelease(pIter->pLeaf);
174155  pIter->pLeaf = 0;
174156  while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
174157    Fts5Data *pNew;
174158    pIter->iLeafPgno--;
174159    pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
174160          pIter->pSeg->iSegid, pIter->iLeafPgno
174161    ));
174162    if( pNew ){
174163      /* iTermLeafOffset may be equal to szLeaf if the term is the last
174164      ** thing on the page - i.e. the first rowid is on the following page.
174165      ** In this case leaf pIter->pLeaf==0, this iterator is at EOF. */
174166      if( pIter->iLeafPgno==pIter->iTermLeafPgno
174167       && pIter->iTermLeafOffset<pNew->szLeaf
174168      ){
174169        pIter->pLeaf = pNew;
174170        pIter->iLeafOffset = pIter->iTermLeafOffset;
174171      }else{
174172        int iRowidOff;
174173        iRowidOff = fts5LeafFirstRowidOff(pNew);
174174        if( iRowidOff ){
174175          pIter->pLeaf = pNew;
174176          pIter->iLeafOffset = iRowidOff;
174177        }
174178      }
174179
174180      if( pIter->pLeaf ){
174181        u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
174182        pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
174183        break;
174184      }else{
174185        fts5DataRelease(pNew);
174186      }
174187    }
174188  }
174189
174190  if( pIter->pLeaf ){
174191    pIter->iEndofDoclist = pIter->pLeaf->nn+1;
174192    fts5SegIterReverseInitPage(p, pIter);
174193  }
174194}
174195
174196/*
174197** Return true if the iterator passed as the second argument currently
174198** points to a delete marker. A delete marker is an entry with a 0 byte
174199** position-list.
174200*/
174201static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5IndexIter *pIter){
174202  Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
174203  return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
174204}
174205
174206/*
174207** Advance iterator pIter to the next entry.
174208**
174209** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
174210** is not considered an error if the iterator reaches EOF. If an error has
174211** already occurred when this function is called, it is a no-op.
174212*/
174213static void fts5SegIterNext(
174214  Fts5Index *p,                   /* FTS5 backend object */
174215  Fts5SegIter *pIter,             /* Iterator to advance */
174216  int *pbNewTerm                  /* OUT: Set for new term */
174217){
174218  assert( pbNewTerm==0 || *pbNewTerm==0 );
174219  if( p->rc==SQLITE_OK ){
174220    if( pIter->flags & FTS5_SEGITER_REVERSE ){
174221      assert( pIter->pNextLeaf==0 );
174222      if( pIter->iRowidOffset>0 ){
174223        u8 *a = pIter->pLeaf->p;
174224        int iOff;
174225        int nPos;
174226        int bDummy;
174227        i64 iDelta;
174228
174229        pIter->iRowidOffset--;
174230        pIter->iLeafOffset = iOff = pIter->aRowidOffset[pIter->iRowidOffset];
174231        iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDummy);
174232        iOff += nPos;
174233        fts5GetVarint(&a[iOff], (u64*)&iDelta);
174234        pIter->iRowid -= iDelta;
174235        fts5SegIterLoadNPos(p, pIter);
174236      }else{
174237        fts5SegIterReverseNewPage(p, pIter);
174238      }
174239    }else{
174240      Fts5Data *pLeaf = pIter->pLeaf;
174241      int iOff;
174242      int bNewTerm = 0;
174243      int nKeep = 0;
174244
174245      /* Search for the end of the position list within the current page. */
174246      u8 *a = pLeaf->p;
174247      int n = pLeaf->szLeaf;
174248
174249      ASSERT_SZLEAF_OK(pLeaf);
174250      iOff = pIter->iLeafOffset + pIter->nPos;
174251
174252      if( iOff<n ){
174253        /* The next entry is on the current page. */
174254        assert_nc( iOff<=pIter->iEndofDoclist );
174255        if( iOff>=pIter->iEndofDoclist ){
174256          bNewTerm = 1;
174257          if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
174258            iOff += fts5GetVarint32(&a[iOff], nKeep);
174259          }
174260        }else{
174261          u64 iDelta;
174262          iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
174263          pIter->iRowid += iDelta;
174264          assert_nc( iDelta>0 );
174265        }
174266        pIter->iLeafOffset = iOff;
174267
174268      }else if( pIter->pSeg==0 ){
174269        const u8 *pList = 0;
174270        const char *zTerm = 0;
174271        int nList = 0;
174272        if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
174273          sqlite3Fts5HashScanNext(p->pHash);
174274          sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
174275        }
174276        if( pList==0 ){
174277          fts5DataRelease(pIter->pLeaf);
174278          pIter->pLeaf = 0;
174279        }else{
174280          pIter->pLeaf->p = (u8*)pList;
174281          pIter->pLeaf->nn = nList;
174282          pIter->pLeaf->szLeaf = nList;
174283          pIter->iEndofDoclist = nList+1;
174284          sqlite3Fts5BufferSet(&p->rc, &pIter->term, strlen(zTerm), (u8*)zTerm);
174285          pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
174286          if( pbNewTerm ) *pbNewTerm = 1;
174287        }
174288      }else{
174289        iOff = 0;
174290        /* Next entry is not on the current page */
174291        while( iOff==0 ){
174292          fts5SegIterNextPage(p, pIter);
174293          pLeaf = pIter->pLeaf;
174294          if( pLeaf==0 ) break;
174295          ASSERT_SZLEAF_OK(pLeaf);
174296          if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
174297            iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
174298            pIter->iLeafOffset = iOff;
174299
174300            if( pLeaf->nn>pLeaf->szLeaf ){
174301              pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
174302                  &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
174303              );
174304            }
174305
174306          }
174307          else if( pLeaf->nn>pLeaf->szLeaf ){
174308            pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
174309                &pLeaf->p[pLeaf->szLeaf], iOff
174310            );
174311            pIter->iLeafOffset = iOff;
174312            pIter->iEndofDoclist = iOff;
174313            bNewTerm = 1;
174314          }
174315          if( iOff>=pLeaf->szLeaf ){
174316            p->rc = FTS5_CORRUPT;
174317            return;
174318          }
174319        }
174320      }
174321
174322      /* Check if the iterator is now at EOF. If so, return early. */
174323      if( pIter->pLeaf ){
174324        if( bNewTerm ){
174325          if( pIter->flags & FTS5_SEGITER_ONETERM ){
174326            fts5DataRelease(pIter->pLeaf);
174327            pIter->pLeaf = 0;
174328          }else{
174329            fts5SegIterLoadTerm(p, pIter, nKeep);
174330            fts5SegIterLoadNPos(p, pIter);
174331            if( pbNewTerm ) *pbNewTerm = 1;
174332          }
174333        }else{
174334          fts5SegIterLoadNPos(p, pIter);
174335        }
174336      }
174337    }
174338  }
174339}
174340
174341#define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
174342
174343/*
174344** Iterator pIter currently points to the first rowid in a doclist. This
174345** function sets the iterator up so that iterates in reverse order through
174346** the doclist.
174347*/
174348static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
174349  Fts5DlidxIter *pDlidx = pIter->pDlidx;
174350  Fts5Data *pLast = 0;
174351  int pgnoLast = 0;
174352
174353  if( pDlidx ){
174354    int iSegid = pIter->pSeg->iSegid;
174355    pgnoLast = fts5DlidxIterPgno(pDlidx);
174356    pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
174357  }else{
174358    Fts5Data *pLeaf = pIter->pLeaf;         /* Current leaf data */
174359
174360    /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
174361    ** position-list content for the current rowid. Back it up so that it
174362    ** points to the start of the position-list size field. */
174363    pIter->iLeafOffset -= sqlite3Fts5GetVarintLen(pIter->nPos*2+pIter->bDel);
174364
174365    /* If this condition is true then the largest rowid for the current
174366    ** term may not be stored on the current page. So search forward to
174367    ** see where said rowid really is.  */
174368    if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
174369      int pgno;
174370      Fts5StructureSegment *pSeg = pIter->pSeg;
174371
174372      /* The last rowid in the doclist may not be on the current page. Search
174373      ** forward to find the page containing the last rowid.  */
174374      for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
174375        i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
174376        Fts5Data *pNew = fts5DataRead(p, iAbs);
174377        if( pNew ){
174378          int iRowid, bTermless;
174379          iRowid = fts5LeafFirstRowidOff(pNew);
174380          bTermless = fts5LeafIsTermless(pNew);
174381          if( iRowid ){
174382            SWAPVAL(Fts5Data*, pNew, pLast);
174383            pgnoLast = pgno;
174384          }
174385          fts5DataRelease(pNew);
174386          if( bTermless==0 ) break;
174387        }
174388      }
174389    }
174390  }
174391
174392  /* If pLast is NULL at this point, then the last rowid for this doclist
174393  ** lies on the page currently indicated by the iterator. In this case
174394  ** pIter->iLeafOffset is already set to point to the position-list size
174395  ** field associated with the first relevant rowid on the page.
174396  **
174397  ** Or, if pLast is non-NULL, then it is the page that contains the last
174398  ** rowid. In this case configure the iterator so that it points to the
174399  ** first rowid on this page.
174400  */
174401  if( pLast ){
174402    int iOff;
174403    fts5DataRelease(pIter->pLeaf);
174404    pIter->pLeaf = pLast;
174405    pIter->iLeafPgno = pgnoLast;
174406    iOff = fts5LeafFirstRowidOff(pLast);
174407    iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
174408    pIter->iLeafOffset = iOff;
174409
174410    if( fts5LeafIsTermless(pLast) ){
174411      pIter->iEndofDoclist = pLast->nn+1;
174412    }else{
174413      pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
174414    }
174415
174416  }
174417
174418  fts5SegIterReverseInitPage(p, pIter);
174419}
174420
174421/*
174422** Iterator pIter currently points to the first rowid of a doclist.
174423** There is a doclist-index associated with the final term on the current
174424** page. If the current term is the last term on the page, load the
174425** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
174426*/
174427static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
174428  int iSeg = pIter->pSeg->iSegid;
174429  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
174430  Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
174431
174432  assert( pIter->flags & FTS5_SEGITER_ONETERM );
174433  assert( pIter->pDlidx==0 );
174434
174435  /* Check if the current doclist ends on this page. If it does, return
174436  ** early without loading the doclist-index (as it belongs to a different
174437  ** term. */
174438  if( pIter->iTermLeafPgno==pIter->iLeafPgno
174439   && pIter->iEndofDoclist<pLeaf->szLeaf
174440  ){
174441    return;
174442  }
174443
174444  pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
174445}
174446
174447#define fts5IndexSkipVarint(a, iOff) {            \
174448  int iEnd = iOff+9;                              \
174449  while( (a[iOff++] & 0x80) && iOff<iEnd );       \
174450}
174451
174452/*
174453** The iterator object passed as the second argument currently contains
174454** no valid values except for the Fts5SegIter.pLeaf member variable. This
174455** function searches the leaf page for a term matching (pTerm/nTerm).
174456**
174457** If the specified term is found on the page, then the iterator is left
174458** pointing to it. If argument bGe is zero and the term is not found,
174459** the iterator is left pointing at EOF.
174460**
174461** If bGe is non-zero and the specified term is not found, then the
174462** iterator is left pointing to the smallest term in the segment that
174463** is larger than the specified term, even if this term is not on the
174464** current page.
174465*/
174466static void fts5LeafSeek(
174467  Fts5Index *p,                   /* Leave any error code here */
174468  int bGe,                        /* True for a >= search */
174469  Fts5SegIter *pIter,             /* Iterator to seek */
174470  const u8 *pTerm, int nTerm      /* Term to search for */
174471){
174472  int iOff;
174473  const u8 *a = pIter->pLeaf->p;
174474  int szLeaf = pIter->pLeaf->szLeaf;
174475  int n = pIter->pLeaf->nn;
174476
174477  int nMatch = 0;
174478  int nKeep = 0;
174479  int nNew = 0;
174480  int iTermOff;
174481  int iPgidx;                     /* Current offset in pgidx */
174482  int bEndOfPage = 0;
174483
174484  assert( p->rc==SQLITE_OK );
174485
174486  iPgidx = szLeaf;
174487  iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
174488  iOff = iTermOff;
174489
174490  while( 1 ){
174491
174492    /* Figure out how many new bytes are in this term */
174493    fts5FastGetVarint32(a, iOff, nNew);
174494    if( nKeep<nMatch ){
174495      goto search_failed;
174496    }
174497
174498    assert( nKeep>=nMatch );
174499    if( nKeep==nMatch ){
174500      int nCmp;
174501      int i;
174502      nCmp = MIN(nNew, nTerm-nMatch);
174503      for(i=0; i<nCmp; i++){
174504        if( a[iOff+i]!=pTerm[nMatch+i] ) break;
174505      }
174506      nMatch += i;
174507
174508      if( nTerm==nMatch ){
174509        if( i==nNew ){
174510          goto search_success;
174511        }else{
174512          goto search_failed;
174513        }
174514      }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
174515        goto search_failed;
174516      }
174517    }
174518
174519    if( iPgidx>=n ){
174520      bEndOfPage = 1;
174521      break;
174522    }
174523
174524    iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
174525    iTermOff += nKeep;
174526    iOff = iTermOff;
174527
174528    /* Read the nKeep field of the next term. */
174529    fts5FastGetVarint32(a, iOff, nKeep);
174530  }
174531
174532 search_failed:
174533  if( bGe==0 ){
174534    fts5DataRelease(pIter->pLeaf);
174535    pIter->pLeaf = 0;
174536    return;
174537  }else if( bEndOfPage ){
174538    do {
174539      fts5SegIterNextPage(p, pIter);
174540      if( pIter->pLeaf==0 ) return;
174541      a = pIter->pLeaf->p;
174542      if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
174543        fts5GetVarint32(&pIter->pLeaf->p[pIter->pLeaf->szLeaf], iOff);
174544        if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
174545          p->rc = FTS5_CORRUPT;
174546        }else{
174547          nKeep = 0;
174548          iOff += fts5GetVarint32(&a[iOff], nNew);
174549          break;
174550        }
174551      }
174552    }while( 1 );
174553  }
174554
174555 search_success:
174556
174557  pIter->iLeafOffset = iOff + nNew;
174558  pIter->iTermLeafOffset = pIter->iLeafOffset;
174559  pIter->iTermLeafPgno = pIter->iLeafPgno;
174560
174561  fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
174562  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
174563
174564  if( iPgidx>=n ){
174565    pIter->iEndofDoclist = pIter->pLeaf->nn+1;
174566  }else{
174567    int nExtra;
174568    iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
174569    pIter->iEndofDoclist = iTermOff + nExtra;
174570  }
174571  pIter->iPgidxOff = iPgidx;
174572
174573  fts5SegIterLoadRowid(p, pIter);
174574  fts5SegIterLoadNPos(p, pIter);
174575}
174576
174577/*
174578** Initialize the object pIter to point to term pTerm/nTerm within segment
174579** pSeg. If there is no such term in the index, the iterator is set to EOF.
174580**
174581** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
174582** an error has already occurred when this function is called, it is a no-op.
174583*/
174584static void fts5SegIterSeekInit(
174585  Fts5Index *p,                   /* FTS5 backend */
174586  Fts5Buffer *pBuf,               /* Buffer to use for loading pages */
174587  const u8 *pTerm, int nTerm,     /* Term to seek to */
174588  int flags,                      /* Mask of FTS5INDEX_XXX flags */
174589  Fts5StructureSegment *pSeg,     /* Description of segment */
174590  Fts5SegIter *pIter              /* Object to populate */
174591){
174592  int iPg = 1;
174593  int bGe = (flags & FTS5INDEX_QUERY_SCAN);
174594  int bDlidx = 0;                 /* True if there is a doclist-index */
174595
174596  static int nCall = 0;
174597  nCall++;
174598
174599  assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
174600  assert( pTerm && nTerm );
174601  memset(pIter, 0, sizeof(*pIter));
174602  pIter->pSeg = pSeg;
174603
174604  /* This block sets stack variable iPg to the leaf page number that may
174605  ** contain term (pTerm/nTerm), if it is present in the segment. */
174606  if( p->pIdxSelect==0 ){
174607    Fts5Config *pConfig = p->pConfig;
174608    fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
174609          "SELECT pgno FROM '%q'.'%q_idx' WHERE "
174610          "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
174611          pConfig->zDb, pConfig->zName
174612    ));
174613  }
174614  if( p->rc ) return;
174615  sqlite3_bind_int(p->pIdxSelect, 1, pSeg->iSegid);
174616  sqlite3_bind_blob(p->pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
174617  if( SQLITE_ROW==sqlite3_step(p->pIdxSelect) ){
174618    i64 val = sqlite3_column_int(p->pIdxSelect, 0);
174619    iPg = (int)(val>>1);
174620    bDlidx = (val & 0x0001);
174621  }
174622  p->rc = sqlite3_reset(p->pIdxSelect);
174623
174624  if( iPg<pSeg->pgnoFirst ){
174625    iPg = pSeg->pgnoFirst;
174626    bDlidx = 0;
174627  }
174628
174629  pIter->iLeafPgno = iPg - 1;
174630  fts5SegIterNextPage(p, pIter);
174631
174632  if( pIter->pLeaf ){
174633    fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
174634  }
174635
174636  if( p->rc==SQLITE_OK && bGe==0 ){
174637    pIter->flags |= FTS5_SEGITER_ONETERM;
174638    if( pIter->pLeaf ){
174639      if( flags & FTS5INDEX_QUERY_DESC ){
174640        pIter->flags |= FTS5_SEGITER_REVERSE;
174641      }
174642      if( bDlidx ){
174643        fts5SegIterLoadDlidx(p, pIter);
174644      }
174645      if( flags & FTS5INDEX_QUERY_DESC ){
174646        fts5SegIterReverse(p, pIter);
174647      }
174648    }
174649  }
174650
174651  /* Either:
174652  **
174653  **   1) an error has occurred, or
174654  **   2) the iterator points to EOF, or
174655  **   3) the iterator points to an entry with term (pTerm/nTerm), or
174656  **   4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
174657  **      to an entry with a term greater than or equal to (pTerm/nTerm).
174658  */
174659  assert( p->rc!=SQLITE_OK                                          /* 1 */
174660   || pIter->pLeaf==0                                               /* 2 */
174661   || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0          /* 3 */
174662   || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0)  /* 4 */
174663  );
174664}
174665
174666/*
174667** Initialize the object pIter to point to term pTerm/nTerm within the
174668** in-memory hash table. If there is no such term in the hash-table, the
174669** iterator is set to EOF.
174670**
174671** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
174672** an error has already occurred when this function is called, it is a no-op.
174673*/
174674static void fts5SegIterHashInit(
174675  Fts5Index *p,                   /* FTS5 backend */
174676  const u8 *pTerm, int nTerm,     /* Term to seek to */
174677  int flags,                      /* Mask of FTS5INDEX_XXX flags */
174678  Fts5SegIter *pIter              /* Object to populate */
174679){
174680  const u8 *pList = 0;
174681  int nList = 0;
174682  const u8 *z = 0;
174683  int n = 0;
174684
174685  assert( p->pHash );
174686  assert( p->rc==SQLITE_OK );
174687
174688  if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
174689    p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
174690    sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
174691    n = (z ? strlen((const char*)z) : 0);
174692  }else{
174693    pIter->flags |= FTS5_SEGITER_ONETERM;
174694    sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
174695    z = pTerm;
174696    n = nTerm;
174697  }
174698
174699  if( pList ){
174700    Fts5Data *pLeaf;
174701    sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
174702    pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
174703    if( pLeaf==0 ) return;
174704    pLeaf->p = (u8*)pList;
174705    pLeaf->nn = pLeaf->szLeaf = nList;
174706    pIter->pLeaf = pLeaf;
174707    pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
174708    pIter->iEndofDoclist = pLeaf->nn+1;
174709
174710    if( flags & FTS5INDEX_QUERY_DESC ){
174711      pIter->flags |= FTS5_SEGITER_REVERSE;
174712      fts5SegIterReverseInitPage(p, pIter);
174713    }else{
174714      fts5SegIterLoadNPos(p, pIter);
174715    }
174716  }
174717}
174718
174719/*
174720** Zero the iterator passed as the only argument.
174721*/
174722static void fts5SegIterClear(Fts5SegIter *pIter){
174723  fts5BufferFree(&pIter->term);
174724  fts5DataRelease(pIter->pLeaf);
174725  fts5DataRelease(pIter->pNextLeaf);
174726  fts5DlidxIterFree(pIter->pDlidx);
174727  sqlite3_free(pIter->aRowidOffset);
174728  memset(pIter, 0, sizeof(Fts5SegIter));
174729}
174730
174731#ifdef SQLITE_DEBUG
174732
174733/*
174734** This function is used as part of the big assert() procedure implemented by
174735** fts5AssertMultiIterSetup(). It ensures that the result currently stored
174736** in *pRes is the correct result of comparing the current positions of the
174737** two iterators.
174738*/
174739static void fts5AssertComparisonResult(
174740  Fts5IndexIter *pIter,
174741  Fts5SegIter *p1,
174742  Fts5SegIter *p2,
174743  Fts5CResult *pRes
174744){
174745  int i1 = p1 - pIter->aSeg;
174746  int i2 = p2 - pIter->aSeg;
174747
174748  if( p1->pLeaf || p2->pLeaf ){
174749    if( p1->pLeaf==0 ){
174750      assert( pRes->iFirst==i2 );
174751    }else if( p2->pLeaf==0 ){
174752      assert( pRes->iFirst==i1 );
174753    }else{
174754      int nMin = MIN(p1->term.n, p2->term.n);
174755      int res = memcmp(p1->term.p, p2->term.p, nMin);
174756      if( res==0 ) res = p1->term.n - p2->term.n;
174757
174758      if( res==0 ){
174759        assert( pRes->bTermEq==1 );
174760        assert( p1->iRowid!=p2->iRowid );
174761        res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
174762      }else{
174763        assert( pRes->bTermEq==0 );
174764      }
174765
174766      if( res<0 ){
174767        assert( pRes->iFirst==i1 );
174768      }else{
174769        assert( pRes->iFirst==i2 );
174770      }
174771    }
174772  }
174773}
174774
174775/*
174776** This function is a no-op unless SQLITE_DEBUG is defined when this module
174777** is compiled. In that case, this function is essentially an assert()
174778** statement used to verify that the contents of the pIter->aFirst[] array
174779** are correct.
174780*/
174781static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5IndexIter *pIter){
174782  if( p->rc==SQLITE_OK ){
174783    Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
174784    int i;
174785
174786    assert( (pFirst->pLeaf==0)==pIter->bEof );
174787
174788    /* Check that pIter->iSwitchRowid is set correctly. */
174789    for(i=0; i<pIter->nSeg; i++){
174790      Fts5SegIter *p1 = &pIter->aSeg[i];
174791      assert( p1==pFirst
174792           || p1->pLeaf==0
174793           || fts5BufferCompare(&pFirst->term, &p1->term)
174794           || p1->iRowid==pIter->iSwitchRowid
174795           || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
174796      );
174797    }
174798
174799    for(i=0; i<pIter->nSeg; i+=2){
174800      Fts5SegIter *p1 = &pIter->aSeg[i];
174801      Fts5SegIter *p2 = &pIter->aSeg[i+1];
174802      Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
174803      fts5AssertComparisonResult(pIter, p1, p2, pRes);
174804    }
174805
174806    for(i=1; i<(pIter->nSeg / 2); i+=2){
174807      Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
174808      Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
174809      Fts5CResult *pRes = &pIter->aFirst[i];
174810      fts5AssertComparisonResult(pIter, p1, p2, pRes);
174811    }
174812  }
174813}
174814#else
174815# define fts5AssertMultiIterSetup(x,y)
174816#endif
174817
174818/*
174819** Do the comparison necessary to populate pIter->aFirst[iOut].
174820**
174821** If the returned value is non-zero, then it is the index of an entry
174822** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
174823** to a key that is a duplicate of another, higher priority,
174824** segment-iterator in the pSeg->aSeg[] array.
174825*/
174826static int fts5MultiIterDoCompare(Fts5IndexIter *pIter, int iOut){
174827  int i1;                         /* Index of left-hand Fts5SegIter */
174828  int i2;                         /* Index of right-hand Fts5SegIter */
174829  int iRes;
174830  Fts5SegIter *p1;                /* Left-hand Fts5SegIter */
174831  Fts5SegIter *p2;                /* Right-hand Fts5SegIter */
174832  Fts5CResult *pRes = &pIter->aFirst[iOut];
174833
174834  assert( iOut<pIter->nSeg && iOut>0 );
174835  assert( pIter->bRev==0 || pIter->bRev==1 );
174836
174837  if( iOut>=(pIter->nSeg/2) ){
174838    i1 = (iOut - pIter->nSeg/2) * 2;
174839    i2 = i1 + 1;
174840  }else{
174841    i1 = pIter->aFirst[iOut*2].iFirst;
174842    i2 = pIter->aFirst[iOut*2+1].iFirst;
174843  }
174844  p1 = &pIter->aSeg[i1];
174845  p2 = &pIter->aSeg[i2];
174846
174847  pRes->bTermEq = 0;
174848  if( p1->pLeaf==0 ){           /* If p1 is at EOF */
174849    iRes = i2;
174850  }else if( p2->pLeaf==0 ){     /* If p2 is at EOF */
174851    iRes = i1;
174852  }else{
174853    int res = fts5BufferCompare(&p1->term, &p2->term);
174854    if( res==0 ){
174855      assert( i2>i1 );
174856      assert( i2!=0 );
174857      pRes->bTermEq = 1;
174858      if( p1->iRowid==p2->iRowid ){
174859        p1->bDel = p2->bDel;
174860        return i2;
174861      }
174862      res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
174863    }
174864    assert( res!=0 );
174865    if( res<0 ){
174866      iRes = i1;
174867    }else{
174868      iRes = i2;
174869    }
174870  }
174871
174872  pRes->iFirst = iRes;
174873  return 0;
174874}
174875
174876/*
174877** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
174878** It is an error if leaf iLeafPgno does not exist or contains no rowids.
174879*/
174880static void fts5SegIterGotoPage(
174881  Fts5Index *p,                   /* FTS5 backend object */
174882  Fts5SegIter *pIter,             /* Iterator to advance */
174883  int iLeafPgno
174884){
174885  assert( iLeafPgno>pIter->iLeafPgno );
174886
174887  if( iLeafPgno>pIter->pSeg->pgnoLast ){
174888    p->rc = FTS5_CORRUPT;
174889  }else{
174890    fts5DataRelease(pIter->pNextLeaf);
174891    pIter->pNextLeaf = 0;
174892    pIter->iLeafPgno = iLeafPgno-1;
174893    fts5SegIterNextPage(p, pIter);
174894    assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
174895
174896    if( p->rc==SQLITE_OK ){
174897      int iOff;
174898      u8 *a = pIter->pLeaf->p;
174899      int n = pIter->pLeaf->szLeaf;
174900
174901      iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
174902      if( iOff<4 || iOff>=n ){
174903        p->rc = FTS5_CORRUPT;
174904      }else{
174905        iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
174906        pIter->iLeafOffset = iOff;
174907        fts5SegIterLoadNPos(p, pIter);
174908      }
174909    }
174910  }
174911}
174912
174913/*
174914** Advance the iterator passed as the second argument until it is at or
174915** past rowid iFrom. Regardless of the value of iFrom, the iterator is
174916** always advanced at least once.
174917*/
174918static void fts5SegIterNextFrom(
174919  Fts5Index *p,                   /* FTS5 backend object */
174920  Fts5SegIter *pIter,             /* Iterator to advance */
174921  i64 iMatch                      /* Advance iterator at least this far */
174922){
174923  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
174924  Fts5DlidxIter *pDlidx = pIter->pDlidx;
174925  int iLeafPgno = pIter->iLeafPgno;
174926  int bMove = 1;
174927
174928  assert( pIter->flags & FTS5_SEGITER_ONETERM );
174929  assert( pIter->pDlidx );
174930  assert( pIter->pLeaf );
174931
174932  if( bRev==0 ){
174933    while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
174934      iLeafPgno = fts5DlidxIterPgno(pDlidx);
174935      fts5DlidxIterNext(p, pDlidx);
174936    }
174937    assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
174938    if( iLeafPgno>pIter->iLeafPgno ){
174939      fts5SegIterGotoPage(p, pIter, iLeafPgno);
174940      bMove = 0;
174941    }
174942  }else{
174943    assert( pIter->pNextLeaf==0 );
174944    assert( iMatch<pIter->iRowid );
174945    while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
174946      fts5DlidxIterPrev(p, pDlidx);
174947    }
174948    iLeafPgno = fts5DlidxIterPgno(pDlidx);
174949
174950    assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
174951
174952    if( iLeafPgno<pIter->iLeafPgno ){
174953      pIter->iLeafPgno = iLeafPgno+1;
174954      fts5SegIterReverseNewPage(p, pIter);
174955      bMove = 0;
174956    }
174957  }
174958
174959  do{
174960    if( bMove ) fts5SegIterNext(p, pIter, 0);
174961    if( pIter->pLeaf==0 ) break;
174962    if( bRev==0 && pIter->iRowid>=iMatch ) break;
174963    if( bRev!=0 && pIter->iRowid<=iMatch ) break;
174964    bMove = 1;
174965  }while( p->rc==SQLITE_OK );
174966}
174967
174968
174969/*
174970** Free the iterator object passed as the second argument.
174971*/
174972static void fts5MultiIterFree(Fts5Index *p, Fts5IndexIter *pIter){
174973  if( pIter ){
174974    int i;
174975    for(i=0; i<pIter->nSeg; i++){
174976      fts5SegIterClear(&pIter->aSeg[i]);
174977    }
174978    fts5StructureRelease(pIter->pStruct);
174979    fts5BufferFree(&pIter->poslist);
174980    sqlite3_free(pIter);
174981  }
174982}
174983
174984static void fts5MultiIterAdvanced(
174985  Fts5Index *p,                   /* FTS5 backend to iterate within */
174986  Fts5IndexIter *pIter,           /* Iterator to update aFirst[] array for */
174987  int iChanged,                   /* Index of sub-iterator just advanced */
174988  int iMinset                     /* Minimum entry in aFirst[] to set */
174989){
174990  int i;
174991  for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
174992    int iEq;
174993    if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
174994      fts5SegIterNext(p, &pIter->aSeg[iEq], 0);
174995      i = pIter->nSeg + iEq;
174996    }
174997  }
174998}
174999
175000/*
175001** Sub-iterator iChanged of iterator pIter has just been advanced. It still
175002** points to the same term though - just a different rowid. This function
175003** attempts to update the contents of the pIter->aFirst[] accordingly.
175004** If it does so successfully, 0 is returned. Otherwise 1.
175005**
175006** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
175007** on the iterator instead. That function does the same as this one, except
175008** that it deals with more complicated cases as well.
175009*/
175010static int fts5MultiIterAdvanceRowid(
175011  Fts5Index *p,                   /* FTS5 backend to iterate within */
175012  Fts5IndexIter *pIter,           /* Iterator to update aFirst[] array for */
175013  int iChanged                    /* Index of sub-iterator just advanced */
175014){
175015  Fts5SegIter *pNew = &pIter->aSeg[iChanged];
175016
175017  if( pNew->iRowid==pIter->iSwitchRowid
175018   || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
175019  ){
175020    int i;
175021    Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
175022    pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
175023    for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
175024      Fts5CResult *pRes = &pIter->aFirst[i];
175025
175026      assert( pNew->pLeaf );
175027      assert( pRes->bTermEq==0 || pOther->pLeaf );
175028
175029      if( pRes->bTermEq ){
175030        if( pNew->iRowid==pOther->iRowid ){
175031          return 1;
175032        }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
175033          pIter->iSwitchRowid = pOther->iRowid;
175034          pNew = pOther;
175035        }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
175036          pIter->iSwitchRowid = pOther->iRowid;
175037        }
175038      }
175039      pRes->iFirst = (pNew - pIter->aSeg);
175040      if( i==1 ) break;
175041
175042      pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
175043    }
175044  }
175045
175046  return 0;
175047}
175048
175049/*
175050** Set the pIter->bEof variable based on the state of the sub-iterators.
175051*/
175052static void fts5MultiIterSetEof(Fts5IndexIter *pIter){
175053  Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
175054  pIter->bEof = pSeg->pLeaf==0;
175055  pIter->iSwitchRowid = pSeg->iRowid;
175056}
175057
175058/*
175059** Move the iterator to the next entry.
175060**
175061** If an error occurs, an error code is left in Fts5Index.rc. It is not
175062** considered an error if the iterator reaches EOF, or if it is already at
175063** EOF when this function is called.
175064*/
175065static void fts5MultiIterNext(
175066  Fts5Index *p,
175067  Fts5IndexIter *pIter,
175068  int bFrom,                      /* True if argument iFrom is valid */
175069  i64 iFrom                       /* Advance at least as far as this */
175070){
175071  if( p->rc==SQLITE_OK ){
175072    int bUseFrom = bFrom;
175073    do {
175074      int iFirst = pIter->aFirst[1].iFirst;
175075      int bNewTerm = 0;
175076      Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
175077      assert( p->rc==SQLITE_OK );
175078      if( bUseFrom && pSeg->pDlidx ){
175079        fts5SegIterNextFrom(p, pSeg, iFrom);
175080      }else{
175081        fts5SegIterNext(p, pSeg, &bNewTerm);
175082      }
175083
175084      if( pSeg->pLeaf==0 || bNewTerm
175085       || fts5MultiIterAdvanceRowid(p, pIter, iFirst)
175086      ){
175087        fts5MultiIterAdvanced(p, pIter, iFirst, 1);
175088        fts5MultiIterSetEof(pIter);
175089      }
175090      fts5AssertMultiIterSetup(p, pIter);
175091
175092      bUseFrom = 0;
175093    }while( pIter->bSkipEmpty && fts5MultiIterIsEmpty(p, pIter) );
175094  }
175095}
175096
175097static Fts5IndexIter *fts5MultiIterAlloc(
175098  Fts5Index *p,                   /* FTS5 backend to iterate within */
175099  int nSeg
175100){
175101  Fts5IndexIter *pNew;
175102  int nSlot;                      /* Power of two >= nSeg */
175103
175104  for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
175105  pNew = fts5IdxMalloc(p,
175106      sizeof(Fts5IndexIter) +             /* pNew */
175107      sizeof(Fts5SegIter) * (nSlot-1) +   /* pNew->aSeg[] */
175108      sizeof(Fts5CResult) * nSlot         /* pNew->aFirst[] */
175109  );
175110  if( pNew ){
175111    pNew->nSeg = nSlot;
175112    pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
175113    pNew->pIndex = p;
175114  }
175115  return pNew;
175116}
175117
175118/*
175119** Allocate a new Fts5IndexIter object.
175120**
175121** The new object will be used to iterate through data in structure pStruct.
175122** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
175123** is zero or greater, data from the first nSegment segments on level iLevel
175124** is merged.
175125**
175126** The iterator initially points to the first term/rowid entry in the
175127** iterated data.
175128*/
175129static void fts5MultiIterNew(
175130  Fts5Index *p,                   /* FTS5 backend to iterate within */
175131  Fts5Structure *pStruct,         /* Structure of specific index */
175132  int bSkipEmpty,                 /* True to ignore delete-keys */
175133  int flags,                      /* FTS5INDEX_QUERY_XXX flags */
175134  const u8 *pTerm, int nTerm,     /* Term to seek to (or NULL/0) */
175135  int iLevel,                     /* Level to iterate (-1 for all) */
175136  int nSegment,                   /* Number of segments to merge (iLevel>=0) */
175137  Fts5IndexIter **ppOut           /* New object */
175138){
175139  int nSeg = 0;                   /* Number of segment-iters in use */
175140  int iIter = 0;                  /* */
175141  int iSeg;                       /* Used to iterate through segments */
175142  Fts5Buffer buf = {0,0,0};       /* Buffer used by fts5SegIterSeekInit() */
175143  Fts5StructureLevel *pLvl;
175144  Fts5IndexIter *pNew;
175145
175146  assert( (pTerm==0 && nTerm==0) || iLevel<0 );
175147
175148  /* Allocate space for the new multi-seg-iterator. */
175149  if( p->rc==SQLITE_OK ){
175150    if( iLevel<0 ){
175151      assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
175152      nSeg = pStruct->nSegment;
175153      nSeg += (p->pHash ? 1 : 0);
175154    }else{
175155      nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
175156    }
175157  }
175158  *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
175159  if( pNew==0 ) return;
175160  pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
175161  pNew->bSkipEmpty = bSkipEmpty;
175162  pNew->pStruct = pStruct;
175163  fts5StructureRef(pStruct);
175164
175165  /* Initialize each of the component segment iterators. */
175166  if( iLevel<0 ){
175167    Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
175168    if( p->pHash ){
175169      /* Add a segment iterator for the current contents of the hash table. */
175170      Fts5SegIter *pIter = &pNew->aSeg[iIter++];
175171      fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
175172    }
175173    for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
175174      for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
175175        Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
175176        Fts5SegIter *pIter = &pNew->aSeg[iIter++];
175177        if( pTerm==0 ){
175178          fts5SegIterInit(p, pSeg, pIter);
175179        }else{
175180          fts5SegIterSeekInit(p, &buf, pTerm, nTerm, flags, pSeg, pIter);
175181        }
175182      }
175183    }
175184  }else{
175185    pLvl = &pStruct->aLevel[iLevel];
175186    for(iSeg=nSeg-1; iSeg>=0; iSeg--){
175187      fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
175188    }
175189  }
175190  assert( iIter==nSeg );
175191
175192  /* If the above was successful, each component iterators now points
175193  ** to the first entry in its segment. In this case initialize the
175194  ** aFirst[] array. Or, if an error has occurred, free the iterator
175195  ** object and set the output variable to NULL.  */
175196  if( p->rc==SQLITE_OK ){
175197    for(iIter=pNew->nSeg-1; iIter>0; iIter--){
175198      int iEq;
175199      if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
175200        fts5SegIterNext(p, &pNew->aSeg[iEq], 0);
175201        fts5MultiIterAdvanced(p, pNew, iEq, iIter);
175202      }
175203    }
175204    fts5MultiIterSetEof(pNew);
175205    fts5AssertMultiIterSetup(p, pNew);
175206
175207    if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
175208      fts5MultiIterNext(p, pNew, 0, 0);
175209    }
175210  }else{
175211    fts5MultiIterFree(p, pNew);
175212    *ppOut = 0;
175213  }
175214  fts5BufferFree(&buf);
175215}
175216
175217/*
175218** Create an Fts5IndexIter that iterates through the doclist provided
175219** as the second argument.
175220*/
175221static void fts5MultiIterNew2(
175222  Fts5Index *p,                   /* FTS5 backend to iterate within */
175223  Fts5Data *pData,                /* Doclist to iterate through */
175224  int bDesc,                      /* True for descending rowid order */
175225  Fts5IndexIter **ppOut           /* New object */
175226){
175227  Fts5IndexIter *pNew;
175228  pNew = fts5MultiIterAlloc(p, 2);
175229  if( pNew ){
175230    Fts5SegIter *pIter = &pNew->aSeg[1];
175231
175232    pNew->bFiltered = 1;
175233    pIter->flags = FTS5_SEGITER_ONETERM;
175234    if( pData->szLeaf>0 ){
175235      pIter->pLeaf = pData;
175236      pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
175237      pIter->iEndofDoclist = pData->nn;
175238      pNew->aFirst[1].iFirst = 1;
175239      if( bDesc ){
175240        pNew->bRev = 1;
175241        pIter->flags |= FTS5_SEGITER_REVERSE;
175242        fts5SegIterReverseInitPage(p, pIter);
175243      }else{
175244        fts5SegIterLoadNPos(p, pIter);
175245      }
175246      pData = 0;
175247    }else{
175248      pNew->bEof = 1;
175249    }
175250
175251    *ppOut = pNew;
175252  }
175253
175254  fts5DataRelease(pData);
175255}
175256
175257/*
175258** Return true if the iterator is at EOF or if an error has occurred.
175259** False otherwise.
175260*/
175261static int fts5MultiIterEof(Fts5Index *p, Fts5IndexIter *pIter){
175262  assert( p->rc
175263      || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->bEof
175264  );
175265  return (p->rc || pIter->bEof);
175266}
175267
175268/*
175269** Return the rowid of the entry that the iterator currently points
175270** to. If the iterator points to EOF when this function is called the
175271** results are undefined.
175272*/
175273static i64 fts5MultiIterRowid(Fts5IndexIter *pIter){
175274  assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
175275  return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
175276}
175277
175278/*
175279** Move the iterator to the next entry at or following iMatch.
175280*/
175281static void fts5MultiIterNextFrom(
175282  Fts5Index *p,
175283  Fts5IndexIter *pIter,
175284  i64 iMatch
175285){
175286  while( 1 ){
175287    i64 iRowid;
175288    fts5MultiIterNext(p, pIter, 1, iMatch);
175289    if( fts5MultiIterEof(p, pIter) ) break;
175290    iRowid = fts5MultiIterRowid(pIter);
175291    if( pIter->bRev==0 && iRowid>=iMatch ) break;
175292    if( pIter->bRev!=0 && iRowid<=iMatch ) break;
175293  }
175294}
175295
175296/*
175297** Return a pointer to a buffer containing the term associated with the
175298** entry that the iterator currently points to.
175299*/
175300static const u8 *fts5MultiIterTerm(Fts5IndexIter *pIter, int *pn){
175301  Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
175302  *pn = p->term.n;
175303  return p->term.p;
175304}
175305
175306static void fts5ChunkIterate(
175307  Fts5Index *p,                   /* Index object */
175308  Fts5SegIter *pSeg,              /* Poslist of this iterator */
175309  void *pCtx,                     /* Context pointer for xChunk callback */
175310  void (*xChunk)(Fts5Index*, void*, const u8*, int)
175311){
175312  int nRem = pSeg->nPos;          /* Number of bytes still to come */
175313  Fts5Data *pData = 0;
175314  u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
175315  int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
175316  int pgno = pSeg->iLeafPgno;
175317  int pgnoSave = 0;
175318
175319  if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
175320    pgnoSave = pgno+1;
175321  }
175322
175323  while( 1 ){
175324    xChunk(p, pCtx, pChunk, nChunk);
175325    nRem -= nChunk;
175326    fts5DataRelease(pData);
175327    if( nRem<=0 ){
175328      break;
175329    }else{
175330      pgno++;
175331      pData = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
175332      if( pData==0 ) break;
175333      pChunk = &pData->p[4];
175334      nChunk = MIN(nRem, pData->szLeaf - 4);
175335      if( pgno==pgnoSave ){
175336        assert( pSeg->pNextLeaf==0 );
175337        pSeg->pNextLeaf = pData;
175338        pData = 0;
175339      }
175340    }
175341  }
175342}
175343
175344
175345
175346/*
175347** Allocate a new segment-id for the structure pStruct. The new segment
175348** id must be between 1 and 65335 inclusive, and must not be used by
175349** any currently existing segment. If a free segment id cannot be found,
175350** SQLITE_FULL is returned.
175351**
175352** If an error has already occurred, this function is a no-op. 0 is
175353** returned in this case.
175354*/
175355static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
175356  int iSegid = 0;
175357
175358  if( p->rc==SQLITE_OK ){
175359    if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
175360      p->rc = SQLITE_FULL;
175361    }else{
175362      while( iSegid==0 ){
175363        int iLvl, iSeg;
175364        sqlite3_randomness(sizeof(u32), (void*)&iSegid);
175365        iSegid = iSegid & ((1 << FTS5_DATA_ID_B)-1);
175366        for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
175367          for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
175368            if( iSegid==pStruct->aLevel[iLvl].aSeg[iSeg].iSegid ){
175369              iSegid = 0;
175370            }
175371          }
175372        }
175373      }
175374    }
175375  }
175376
175377  return iSegid;
175378}
175379
175380/*
175381** Discard all data currently cached in the hash-tables.
175382*/
175383static void fts5IndexDiscardData(Fts5Index *p){
175384  assert( p->pHash || p->nPendingData==0 );
175385  if( p->pHash ){
175386    sqlite3Fts5HashClear(p->pHash);
175387    p->nPendingData = 0;
175388  }
175389}
175390
175391/*
175392** Return the size of the prefix, in bytes, that buffer (nNew/pNew) shares
175393** with buffer (nOld/pOld).
175394*/
175395static int fts5PrefixCompress(
175396  int nOld, const u8 *pOld,
175397  int nNew, const u8 *pNew
175398){
175399  int i;
175400  assert( fts5BlobCompare(pOld, nOld, pNew, nNew)<0 );
175401  for(i=0; i<nOld; i++){
175402    if( pOld[i]!=pNew[i] ) break;
175403  }
175404  return i;
175405}
175406
175407static void fts5WriteDlidxClear(
175408  Fts5Index *p,
175409  Fts5SegWriter *pWriter,
175410  int bFlush                      /* If true, write dlidx to disk */
175411){
175412  int i;
175413  assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
175414  for(i=0; i<pWriter->nDlidx; i++){
175415    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
175416    if( pDlidx->buf.n==0 ) break;
175417    if( bFlush ){
175418      assert( pDlidx->pgno!=0 );
175419      fts5DataWrite(p,
175420          FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
175421          pDlidx->buf.p, pDlidx->buf.n
175422      );
175423    }
175424    sqlite3Fts5BufferZero(&pDlidx->buf);
175425    pDlidx->bPrevValid = 0;
175426  }
175427}
175428
175429/*
175430** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
175431** Any new array elements are zeroed before returning.
175432*/
175433static int fts5WriteDlidxGrow(
175434  Fts5Index *p,
175435  Fts5SegWriter *pWriter,
175436  int nLvl
175437){
175438  if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
175439    Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
175440        pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
175441    );
175442    if( aDlidx==0 ){
175443      p->rc = SQLITE_NOMEM;
175444    }else{
175445      int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
175446      memset(&aDlidx[pWriter->nDlidx], 0, nByte);
175447      pWriter->aDlidx = aDlidx;
175448      pWriter->nDlidx = nLvl;
175449    }
175450  }
175451  return p->rc;
175452}
175453
175454/*
175455** If the current doclist-index accumulating in pWriter->aDlidx[] is large
175456** enough, flush it to disk and return 1. Otherwise discard it and return
175457** zero.
175458*/
175459static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
175460  int bFlag = 0;
175461
175462  /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
175463  ** to the database, also write the doclist-index to disk.  */
175464  if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
175465    bFlag = 1;
175466  }
175467  fts5WriteDlidxClear(p, pWriter, bFlag);
175468  pWriter->nEmpty = 0;
175469  return bFlag;
175470}
175471
175472/*
175473** This function is called whenever processing of the doclist for the
175474** last term on leaf page (pWriter->iBtPage) is completed.
175475**
175476** The doclist-index for that term is currently stored in-memory within the
175477** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
175478** writes it out to disk. Or, if it is too small to bother with, discards
175479** it.
175480**
175481** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
175482*/
175483static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
175484  int bFlag;
175485
175486  assert( pWriter->iBtPage || pWriter->nEmpty==0 );
175487  if( pWriter->iBtPage==0 ) return;
175488  bFlag = fts5WriteFlushDlidx(p, pWriter);
175489
175490  if( p->rc==SQLITE_OK ){
175491    const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
175492    /* The following was already done in fts5WriteInit(): */
175493    /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
175494    sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
175495    sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
175496    sqlite3_step(p->pIdxWriter);
175497    p->rc = sqlite3_reset(p->pIdxWriter);
175498  }
175499  pWriter->iBtPage = 0;
175500}
175501
175502/*
175503** This is called once for each leaf page except the first that contains
175504** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
175505** is larger than all terms written to earlier leaves, and equal to or
175506** smaller than the first term on the new leaf.
175507**
175508** If an error occurs, an error code is left in Fts5Index.rc. If an error
175509** has already occurred when this function is called, it is a no-op.
175510*/
175511static void fts5WriteBtreeTerm(
175512  Fts5Index *p,                   /* FTS5 backend object */
175513  Fts5SegWriter *pWriter,         /* Writer object */
175514  int nTerm, const u8 *pTerm      /* First term on new page */
175515){
175516  fts5WriteFlushBtree(p, pWriter);
175517  fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
175518  pWriter->iBtPage = pWriter->writer.pgno;
175519}
175520
175521/*
175522** This function is called when flushing a leaf page that contains no
175523** terms at all to disk.
175524*/
175525static void fts5WriteBtreeNoTerm(
175526  Fts5Index *p,                   /* FTS5 backend object */
175527  Fts5SegWriter *pWriter          /* Writer object */
175528){
175529  /* If there were no rowids on the leaf page either and the doclist-index
175530  ** has already been started, append an 0x00 byte to it.  */
175531  if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
175532    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
175533    assert( pDlidx->bPrevValid );
175534    sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
175535  }
175536
175537  /* Increment the "number of sequential leaves without a term" counter. */
175538  pWriter->nEmpty++;
175539}
175540
175541static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
175542  i64 iRowid;
175543  int iOff;
175544
175545  iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
175546  fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
175547  return iRowid;
175548}
175549
175550/*
175551** Rowid iRowid has just been appended to the current leaf page. It is the
175552** first on the page. This function appends an appropriate entry to the current
175553** doclist-index.
175554*/
175555static void fts5WriteDlidxAppend(
175556  Fts5Index *p,
175557  Fts5SegWriter *pWriter,
175558  i64 iRowid
175559){
175560  int i;
175561  int bDone = 0;
175562
175563  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
175564    i64 iVal;
175565    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
175566
175567    if( pDlidx->buf.n>=p->pConfig->pgsz ){
175568      /* The current doclist-index page is full. Write it to disk and push
175569      ** a copy of iRowid (which will become the first rowid on the next
175570      ** doclist-index leaf page) up into the next level of the b-tree
175571      ** hierarchy. If the node being flushed is currently the root node,
175572      ** also push its first rowid upwards. */
175573      pDlidx->buf.p[0] = 0x01;    /* Not the root node */
175574      fts5DataWrite(p,
175575          FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
175576          pDlidx->buf.p, pDlidx->buf.n
175577      );
175578      fts5WriteDlidxGrow(p, pWriter, i+2);
175579      pDlidx = &pWriter->aDlidx[i];
175580      if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
175581        i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
175582
175583        /* This was the root node. Push its first rowid up to the new root. */
175584        pDlidx[1].pgno = pDlidx->pgno;
175585        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
175586        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
175587        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
175588        pDlidx[1].bPrevValid = 1;
175589        pDlidx[1].iPrev = iFirst;
175590      }
175591
175592      sqlite3Fts5BufferZero(&pDlidx->buf);
175593      pDlidx->bPrevValid = 0;
175594      pDlidx->pgno++;
175595    }else{
175596      bDone = 1;
175597    }
175598
175599    if( pDlidx->bPrevValid ){
175600      iVal = iRowid - pDlidx->iPrev;
175601    }else{
175602      i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
175603      assert( pDlidx->buf.n==0 );
175604      sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
175605      sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
175606      iVal = iRowid;
175607    }
175608
175609    sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
175610    pDlidx->bPrevValid = 1;
175611    pDlidx->iPrev = iRowid;
175612  }
175613}
175614
175615static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
175616  static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
175617  Fts5PageWriter *pPage = &pWriter->writer;
175618  i64 iRowid;
175619
175620  assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
175621
175622  /* Set the szLeaf header field. */
175623  assert( 0==fts5GetU16(&pPage->buf.p[2]) );
175624  fts5PutU16(&pPage->buf.p[2], pPage->buf.n);
175625
175626  if( pWriter->bFirstTermInPage ){
175627    /* No term was written to this page. */
175628    assert( pPage->pgidx.n==0 );
175629    fts5WriteBtreeNoTerm(p, pWriter);
175630  }else{
175631    /* Append the pgidx to the page buffer. Set the szLeaf header field. */
175632    fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
175633  }
175634
175635  /* Write the page out to disk */
175636  iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
175637  fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
175638
175639  /* Initialize the next page. */
175640  fts5BufferZero(&pPage->buf);
175641  fts5BufferZero(&pPage->pgidx);
175642  fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
175643  pPage->iPrevPgidx = 0;
175644  pPage->pgno++;
175645
175646  /* Increase the leaves written counter */
175647  pWriter->nLeafWritten++;
175648
175649  /* The new leaf holds no terms or rowids */
175650  pWriter->bFirstTermInPage = 1;
175651  pWriter->bFirstRowidInPage = 1;
175652}
175653
175654/*
175655** Append term pTerm/nTerm to the segment being written by the writer passed
175656** as the second argument.
175657**
175658** If an error occurs, set the Fts5Index.rc error code. If an error has
175659** already occurred, this function is a no-op.
175660*/
175661static void fts5WriteAppendTerm(
175662  Fts5Index *p,
175663  Fts5SegWriter *pWriter,
175664  int nTerm, const u8 *pTerm
175665){
175666  int nPrefix;                    /* Bytes of prefix compression for term */
175667  Fts5PageWriter *pPage = &pWriter->writer;
175668  Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
175669
175670  assert( p->rc==SQLITE_OK );
175671  assert( pPage->buf.n>=4 );
175672  assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
175673
175674  /* If the current leaf page is full, flush it to disk. */
175675  if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
175676    if( pPage->buf.n>4 ){
175677      fts5WriteFlushLeaf(p, pWriter);
175678    }
175679    fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
175680  }
175681
175682  /* TODO1: Updating pgidx here. */
175683  pPgidx->n += sqlite3Fts5PutVarint(
175684      &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
175685  );
175686  pPage->iPrevPgidx = pPage->buf.n;
175687#if 0
175688  fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
175689  pPgidx->n += 2;
175690#endif
175691
175692  if( pWriter->bFirstTermInPage ){
175693    nPrefix = 0;
175694    if( pPage->pgno!=1 ){
175695      /* This is the first term on a leaf that is not the leftmost leaf in
175696      ** the segment b-tree. In this case it is necessary to add a term to
175697      ** the b-tree hierarchy that is (a) larger than the largest term
175698      ** already written to the segment and (b) smaller than or equal to
175699      ** this term. In other words, a prefix of (pTerm/nTerm) that is one
175700      ** byte longer than the longest prefix (pTerm/nTerm) shares with the
175701      ** previous term.
175702      **
175703      ** Usually, the previous term is available in pPage->term. The exception
175704      ** is if this is the first term written in an incremental-merge step.
175705      ** In this case the previous term is not available, so just write a
175706      ** copy of (pTerm/nTerm) into the parent node. This is slightly
175707      ** inefficient, but still correct.  */
175708      int n = nTerm;
175709      if( pPage->term.n ){
175710        n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, nTerm, pTerm);
175711      }
175712      fts5WriteBtreeTerm(p, pWriter, n, pTerm);
175713      pPage = &pWriter->writer;
175714    }
175715  }else{
175716    nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, nTerm, pTerm);
175717    fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
175718  }
175719
175720  /* Append the number of bytes of new data, then the term data itself
175721  ** to the page. */
175722  fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
175723  fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
175724
175725  /* Update the Fts5PageWriter.term field. */
175726  fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
175727  pWriter->bFirstTermInPage = 0;
175728
175729  pWriter->bFirstRowidInPage = 0;
175730  pWriter->bFirstRowidInDoclist = 1;
175731
175732  assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
175733  pWriter->aDlidx[0].pgno = pPage->pgno;
175734}
175735
175736/*
175737** Append a rowid and position-list size field to the writers output.
175738*/
175739static void fts5WriteAppendRowid(
175740  Fts5Index *p,
175741  Fts5SegWriter *pWriter,
175742  i64 iRowid,
175743  int nPos
175744){
175745  if( p->rc==SQLITE_OK ){
175746    Fts5PageWriter *pPage = &pWriter->writer;
175747
175748    if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
175749      fts5WriteFlushLeaf(p, pWriter);
175750    }
175751
175752    /* If this is to be the first rowid written to the page, set the
175753    ** rowid-pointer in the page-header. Also append a value to the dlidx
175754    ** buffer, in case a doclist-index is required.  */
175755    if( pWriter->bFirstRowidInPage ){
175756      fts5PutU16(pPage->buf.p, pPage->buf.n);
175757      fts5WriteDlidxAppend(p, pWriter, iRowid);
175758    }
175759
175760    /* Write the rowid. */
175761    if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
175762      fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
175763    }else{
175764      assert( p->rc || iRowid>pWriter->iPrevRowid );
175765      fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
175766    }
175767    pWriter->iPrevRowid = iRowid;
175768    pWriter->bFirstRowidInDoclist = 0;
175769    pWriter->bFirstRowidInPage = 0;
175770
175771    fts5BufferAppendVarint(&p->rc, &pPage->buf, nPos);
175772  }
175773}
175774
175775static void fts5WriteAppendPoslistData(
175776  Fts5Index *p,
175777  Fts5SegWriter *pWriter,
175778  const u8 *aData,
175779  int nData
175780){
175781  Fts5PageWriter *pPage = &pWriter->writer;
175782  const u8 *a = aData;
175783  int n = nData;
175784
175785  assert( p->pConfig->pgsz>0 );
175786  while( p->rc==SQLITE_OK
175787     && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
175788  ){
175789    int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
175790    int nCopy = 0;
175791    while( nCopy<nReq ){
175792      i64 dummy;
175793      nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
175794    }
175795    fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
175796    a += nCopy;
175797    n -= nCopy;
175798    fts5WriteFlushLeaf(p, pWriter);
175799  }
175800  if( n>0 ){
175801    fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
175802  }
175803}
175804
175805/*
175806** Flush any data cached by the writer object to the database. Free any
175807** allocations associated with the writer.
175808*/
175809static void fts5WriteFinish(
175810  Fts5Index *p,
175811  Fts5SegWriter *pWriter,         /* Writer object */
175812  int *pnLeaf                     /* OUT: Number of leaf pages in b-tree */
175813){
175814  int i;
175815  Fts5PageWriter *pLeaf = &pWriter->writer;
175816  if( p->rc==SQLITE_OK ){
175817    assert( pLeaf->pgno>=1 );
175818    if( pLeaf->buf.n>4 ){
175819      fts5WriteFlushLeaf(p, pWriter);
175820    }
175821    *pnLeaf = pLeaf->pgno-1;
175822    fts5WriteFlushBtree(p, pWriter);
175823  }
175824  fts5BufferFree(&pLeaf->term);
175825  fts5BufferFree(&pLeaf->buf);
175826  fts5BufferFree(&pLeaf->pgidx);
175827  fts5BufferFree(&pWriter->btterm);
175828
175829  for(i=0; i<pWriter->nDlidx; i++){
175830    sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
175831  }
175832  sqlite3_free(pWriter->aDlidx);
175833}
175834
175835static void fts5WriteInit(
175836  Fts5Index *p,
175837  Fts5SegWriter *pWriter,
175838  int iSegid
175839){
175840  const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
175841
175842  memset(pWriter, 0, sizeof(Fts5SegWriter));
175843  pWriter->iSegid = iSegid;
175844
175845  fts5WriteDlidxGrow(p, pWriter, 1);
175846  pWriter->writer.pgno = 1;
175847  pWriter->bFirstTermInPage = 1;
175848  pWriter->iBtPage = 1;
175849
175850  /* Grow the two buffers to pgsz + padding bytes in size. */
175851  fts5BufferGrow(&p->rc, &pWriter->writer.pgidx, nBuffer);
175852  fts5BufferGrow(&p->rc, &pWriter->writer.buf, nBuffer);
175853
175854  if( p->pIdxWriter==0 ){
175855    Fts5Config *pConfig = p->pConfig;
175856    fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
175857          "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
175858          pConfig->zDb, pConfig->zName
175859    ));
175860  }
175861
175862  if( p->rc==SQLITE_OK ){
175863    /* Initialize the 4-byte leaf-page header to 0x00. */
175864    memset(pWriter->writer.buf.p, 0, 4);
175865    pWriter->writer.buf.n = 4;
175866
175867    /* Bind the current output segment id to the index-writer. This is an
175868    ** optimization over binding the same value over and over as rows are
175869    ** inserted into %_idx by the current writer.  */
175870    sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
175871  }
175872}
175873
175874/*
175875** Iterator pIter was used to iterate through the input segments of on an
175876** incremental merge operation. This function is called if the incremental
175877** merge step has finished but the input has not been completely exhausted.
175878*/
175879static void fts5TrimSegments(Fts5Index *p, Fts5IndexIter *pIter){
175880  int i;
175881  Fts5Buffer buf;
175882  memset(&buf, 0, sizeof(Fts5Buffer));
175883  for(i=0; i<pIter->nSeg; i++){
175884    Fts5SegIter *pSeg = &pIter->aSeg[i];
175885    if( pSeg->pSeg==0 ){
175886      /* no-op */
175887    }else if( pSeg->pLeaf==0 ){
175888      /* All keys from this input segment have been transfered to the output.
175889      ** Set both the first and last page-numbers to 0 to indicate that the
175890      ** segment is now empty. */
175891      pSeg->pSeg->pgnoLast = 0;
175892      pSeg->pSeg->pgnoFirst = 0;
175893    }else{
175894      int iOff = pSeg->iTermLeafOffset;     /* Offset on new first leaf page */
175895      i64 iLeafRowid;
175896      Fts5Data *pData;
175897      int iId = pSeg->pSeg->iSegid;
175898      u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
175899
175900      iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
175901      pData = fts5DataRead(p, iLeafRowid);
175902      if( pData ){
175903        fts5BufferZero(&buf);
175904        fts5BufferGrow(&p->rc, &buf, pData->nn);
175905        fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
175906        fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
175907        fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
175908        fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
175909        if( p->rc==SQLITE_OK ){
175910          /* Set the szLeaf field */
175911          fts5PutU16(&buf.p[2], buf.n);
175912        }
175913
175914        /* Set up the new page-index array */
175915        fts5BufferAppendVarint(&p->rc, &buf, 4);
175916        if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
175917         && pSeg->iEndofDoclist<pData->szLeaf
175918        ){
175919          int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
175920          fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
175921          fts5BufferAppendBlob(&p->rc, &buf,
175922              pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
175923          );
175924        }
175925
175926        fts5DataRelease(pData);
175927        pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
175928        fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
175929        fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
175930      }
175931    }
175932  }
175933  fts5BufferFree(&buf);
175934}
175935
175936static void fts5MergeChunkCallback(
175937  Fts5Index *p,
175938  void *pCtx,
175939  const u8 *pChunk, int nChunk
175940){
175941  Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
175942  fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
175943}
175944
175945/*
175946**
175947*/
175948static void fts5IndexMergeLevel(
175949  Fts5Index *p,                   /* FTS5 backend object */
175950  Fts5Structure **ppStruct,       /* IN/OUT: Stucture of index */
175951  int iLvl,                       /* Level to read input from */
175952  int *pnRem                      /* Write up to this many output leaves */
175953){
175954  Fts5Structure *pStruct = *ppStruct;
175955  Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
175956  Fts5StructureLevel *pLvlOut;
175957  Fts5IndexIter *pIter = 0;       /* Iterator to read input data */
175958  int nRem = pnRem ? *pnRem : 0;  /* Output leaf pages left to write */
175959  int nInput;                     /* Number of input segments */
175960  Fts5SegWriter writer;           /* Writer object */
175961  Fts5StructureSegment *pSeg;     /* Output segment */
175962  Fts5Buffer term;
175963  int bOldest;                    /* True if the output segment is the oldest */
175964
175965  assert( iLvl<pStruct->nLevel );
175966  assert( pLvl->nMerge<=pLvl->nSeg );
175967
175968  memset(&writer, 0, sizeof(Fts5SegWriter));
175969  memset(&term, 0, sizeof(Fts5Buffer));
175970  if( pLvl->nMerge ){
175971    pLvlOut = &pStruct->aLevel[iLvl+1];
175972    assert( pLvlOut->nSeg>0 );
175973    nInput = pLvl->nMerge;
175974    pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
175975
175976    fts5WriteInit(p, &writer, pSeg->iSegid);
175977    writer.writer.pgno = pSeg->pgnoLast+1;
175978    writer.iBtPage = 0;
175979  }else{
175980    int iSegid = fts5AllocateSegid(p, pStruct);
175981
175982    /* Extend the Fts5Structure object as required to ensure the output
175983    ** segment exists. */
175984    if( iLvl==pStruct->nLevel-1 ){
175985      fts5StructureAddLevel(&p->rc, ppStruct);
175986      pStruct = *ppStruct;
175987    }
175988    fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
175989    if( p->rc ) return;
175990    pLvl = &pStruct->aLevel[iLvl];
175991    pLvlOut = &pStruct->aLevel[iLvl+1];
175992
175993    fts5WriteInit(p, &writer, iSegid);
175994
175995    /* Add the new segment to the output level */
175996    pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
175997    pLvlOut->nSeg++;
175998    pSeg->pgnoFirst = 1;
175999    pSeg->iSegid = iSegid;
176000    pStruct->nSegment++;
176001
176002    /* Read input from all segments in the input level */
176003    nInput = pLvl->nSeg;
176004  }
176005  bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
176006
176007  assert( iLvl>=0 );
176008  for(fts5MultiIterNew(p, pStruct, 0, 0, 0, 0, iLvl, nInput, &pIter);
176009      fts5MultiIterEof(p, pIter)==0;
176010      fts5MultiIterNext(p, pIter, 0, 0)
176011  ){
176012    Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
176013    int nPos;                     /* position-list size field value */
176014    int nTerm;
176015    const u8 *pTerm;
176016
176017    /* Check for key annihilation. */
176018    if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
176019
176020    pTerm = fts5MultiIterTerm(pIter, &nTerm);
176021    if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
176022      if( pnRem && writer.nLeafWritten>nRem ){
176023        break;
176024      }
176025
176026      /* This is a new term. Append a term to the output segment. */
176027      fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
176028      fts5BufferSet(&p->rc, &term, nTerm, pTerm);
176029    }
176030
176031    /* Append the rowid to the output */
176032    /* WRITEPOSLISTSIZE */
176033    nPos = pSegIter->nPos*2 + pSegIter->bDel;
176034    fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter), nPos);
176035
176036    /* Append the position-list data to the output */
176037    fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
176038  }
176039
176040  /* Flush the last leaf page to disk. Set the output segment b-tree height
176041  ** and last leaf page number at the same time.  */
176042  fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
176043
176044  if( fts5MultiIterEof(p, pIter) ){
176045    int i;
176046
176047    /* Remove the redundant segments from the %_data table */
176048    for(i=0; i<nInput; i++){
176049      fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
176050    }
176051
176052    /* Remove the redundant segments from the input level */
176053    if( pLvl->nSeg!=nInput ){
176054      int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
176055      memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
176056    }
176057    pStruct->nSegment -= nInput;
176058    pLvl->nSeg -= nInput;
176059    pLvl->nMerge = 0;
176060    if( pSeg->pgnoLast==0 ){
176061      pLvlOut->nSeg--;
176062      pStruct->nSegment--;
176063    }
176064  }else{
176065    assert( pSeg->pgnoLast>0 );
176066    fts5TrimSegments(p, pIter);
176067    pLvl->nMerge = nInput;
176068  }
176069
176070  fts5MultiIterFree(p, pIter);
176071  fts5BufferFree(&term);
176072  if( pnRem ) *pnRem -= writer.nLeafWritten;
176073}
176074
176075/*
176076** Do up to nPg pages of automerge work on the index.
176077*/
176078static void fts5IndexMerge(
176079  Fts5Index *p,                   /* FTS5 backend object */
176080  Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
176081  int nPg                         /* Pages of work to do */
176082){
176083  int nRem = nPg;
176084  Fts5Structure *pStruct = *ppStruct;
176085  while( nRem>0 && p->rc==SQLITE_OK ){
176086    int iLvl;                   /* To iterate through levels */
176087    int iBestLvl = 0;           /* Level offering the most input segments */
176088    int nBest = 0;              /* Number of input segments on best level */
176089
176090    /* Set iBestLvl to the level to read input segments from. */
176091    assert( pStruct->nLevel>0 );
176092    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
176093      Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
176094      if( pLvl->nMerge ){
176095        if( pLvl->nMerge>nBest ){
176096          iBestLvl = iLvl;
176097          nBest = pLvl->nMerge;
176098        }
176099        break;
176100      }
176101      if( pLvl->nSeg>nBest ){
176102        nBest = pLvl->nSeg;
176103        iBestLvl = iLvl;
176104      }
176105    }
176106
176107    /* If nBest is still 0, then the index must be empty. */
176108#ifdef SQLITE_DEBUG
176109    for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
176110      assert( pStruct->aLevel[iLvl].nSeg==0 );
176111    }
176112#endif
176113
176114    if( nBest<p->pConfig->nAutomerge
176115        && pStruct->aLevel[iBestLvl].nMerge==0
176116      ){
176117      break;
176118    }
176119    fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
176120    if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
176121      fts5StructurePromote(p, iBestLvl+1, pStruct);
176122    }
176123  }
176124  *ppStruct = pStruct;
176125}
176126
176127/*
176128** A total of nLeaf leaf pages of data has just been flushed to a level-0
176129** segment. This function updates the write-counter accordingly and, if
176130** necessary, performs incremental merge work.
176131**
176132** If an error occurs, set the Fts5Index.rc error code. If an error has
176133** already occurred, this function is a no-op.
176134*/
176135static void fts5IndexAutomerge(
176136  Fts5Index *p,                   /* FTS5 backend object */
176137  Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
176138  int nLeaf                       /* Number of output leaves just written */
176139){
176140  if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
176141    Fts5Structure *pStruct = *ppStruct;
176142    u64 nWrite;                   /* Initial value of write-counter */
176143    int nWork;                    /* Number of work-quanta to perform */
176144    int nRem;                     /* Number of leaf pages left to write */
176145
176146    /* Update the write-counter. While doing so, set nWork. */
176147    nWrite = pStruct->nWriteCounter;
176148    nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
176149    pStruct->nWriteCounter += nLeaf;
176150    nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
176151
176152    fts5IndexMerge(p, ppStruct, nRem);
176153  }
176154}
176155
176156static void fts5IndexCrisismerge(
176157  Fts5Index *p,                   /* FTS5 backend object */
176158  Fts5Structure **ppStruct        /* IN/OUT: Current structure of index */
176159){
176160  const int nCrisis = p->pConfig->nCrisisMerge;
176161  Fts5Structure *pStruct = *ppStruct;
176162  int iLvl = 0;
176163
176164  assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
176165  while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
176166    fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
176167    assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
176168    fts5StructurePromote(p, iLvl+1, pStruct);
176169    iLvl++;
176170  }
176171  *ppStruct = pStruct;
176172}
176173
176174static int fts5IndexReturn(Fts5Index *p){
176175  int rc = p->rc;
176176  p->rc = SQLITE_OK;
176177  return rc;
176178}
176179
176180typedef struct Fts5FlushCtx Fts5FlushCtx;
176181struct Fts5FlushCtx {
176182  Fts5Index *pIdx;
176183  Fts5SegWriter writer;
176184};
176185
176186/*
176187** Buffer aBuf[] contains a list of varints, all small enough to fit
176188** in a 32-bit integer. Return the size of the largest prefix of this
176189** list nMax bytes or less in size.
176190*/
176191static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
176192  int ret;
176193  u32 dummy;
176194  ret = fts5GetVarint32(aBuf, dummy);
176195  if( ret<nMax ){
176196    while( 1 ){
176197      int i = fts5GetVarint32(&aBuf[ret], dummy);
176198      if( (ret + i) > nMax ) break;
176199      ret += i;
176200    }
176201  }
176202  return ret;
176203}
176204
176205#define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) {     \
176206  assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) );             \
176207  memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob);             \
176208  (pBuf)->n += nBlob;                                      \
176209}
176210
176211#define fts5BufferSafeAppendVarint(pBuf, iVal) {                \
176212  (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal));  \
176213  assert( (pBuf)->nSpace>=(pBuf)->n );                          \
176214}
176215
176216/*
176217** Flush the contents of in-memory hash table iHash to a new level-0
176218** segment on disk. Also update the corresponding structure record.
176219**
176220** If an error occurs, set the Fts5Index.rc error code. If an error has
176221** already occurred, this function is a no-op.
176222*/
176223static void fts5FlushOneHash(Fts5Index *p){
176224  Fts5Hash *pHash = p->pHash;
176225  Fts5Structure *pStruct;
176226  int iSegid;
176227  int pgnoLast = 0;                 /* Last leaf page number in segment */
176228
176229  /* Obtain a reference to the index structure and allocate a new segment-id
176230  ** for the new level-0 segment.  */
176231  pStruct = fts5StructureRead(p);
176232  iSegid = fts5AllocateSegid(p, pStruct);
176233
176234  if( iSegid ){
176235    const int pgsz = p->pConfig->pgsz;
176236
176237    Fts5StructureSegment *pSeg;   /* New segment within pStruct */
176238    Fts5Buffer *pBuf;             /* Buffer in which to assemble leaf page */
176239    Fts5Buffer *pPgidx;           /* Buffer in which to assemble pgidx */
176240
176241    Fts5SegWriter writer;
176242    fts5WriteInit(p, &writer, iSegid);
176243
176244    pBuf = &writer.writer.buf;
176245    pPgidx = &writer.writer.pgidx;
176246
176247    /* fts5WriteInit() should have initialized the buffers to (most likely)
176248    ** the maximum space required. */
176249    assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
176250    assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
176251
176252    /* Begin scanning through hash table entries. This loop runs once for each
176253    ** term/doclist currently stored within the hash table. */
176254    if( p->rc==SQLITE_OK ){
176255      p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
176256    }
176257    while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
176258      const char *zTerm;          /* Buffer containing term */
176259      const u8 *pDoclist;         /* Pointer to doclist for this term */
176260      int nDoclist;               /* Size of doclist in bytes */
176261
176262      /* Write the term for this entry to disk. */
176263      sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
176264      fts5WriteAppendTerm(p, &writer, strlen(zTerm), (const u8*)zTerm);
176265
176266      assert( writer.bFirstRowidInPage==0 );
176267      if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
176268        /* The entire doclist will fit on the current leaf. */
176269        fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
176270      }else{
176271        i64 iRowid = 0;
176272        i64 iDelta = 0;
176273        int iOff = 0;
176274
176275        /* The entire doclist will not fit on this leaf. The following
176276        ** loop iterates through the poslists that make up the current
176277        ** doclist.  */
176278        while( p->rc==SQLITE_OK && iOff<nDoclist ){
176279          int nPos;
176280          int nCopy;
176281          int bDummy;
176282          iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
176283          nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
176284          nCopy += nPos;
176285          iRowid += iDelta;
176286
176287          if( writer.bFirstRowidInPage ){
176288            fts5PutU16(&pBuf->p[0], pBuf->n);   /* first rowid on page */
176289            pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
176290            writer.bFirstRowidInPage = 0;
176291            fts5WriteDlidxAppend(p, &writer, iRowid);
176292          }else{
176293            pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
176294          }
176295          assert( pBuf->n<=pBuf->nSpace );
176296
176297          if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
176298            /* The entire poslist will fit on the current leaf. So copy
176299            ** it in one go. */
176300            fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
176301          }else{
176302            /* The entire poslist will not fit on this leaf. So it needs
176303            ** to be broken into sections. The only qualification being
176304            ** that each varint must be stored contiguously.  */
176305            const u8 *pPoslist = &pDoclist[iOff];
176306            int iPos = 0;
176307            while( p->rc==SQLITE_OK ){
176308              int nSpace = pgsz - pBuf->n - pPgidx->n;
176309              int n = 0;
176310              if( (nCopy - iPos)<=nSpace ){
176311                n = nCopy - iPos;
176312              }else{
176313                n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
176314              }
176315              assert( n>0 );
176316              fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
176317              iPos += n;
176318              if( (pBuf->n + pPgidx->n)>=pgsz ){
176319                fts5WriteFlushLeaf(p, &writer);
176320              }
176321              if( iPos>=nCopy ) break;
176322            }
176323          }
176324          iOff += nCopy;
176325        }
176326      }
176327
176328      /* TODO2: Doclist terminator written here. */
176329      /* pBuf->p[pBuf->n++] = '\0'; */
176330      assert( pBuf->n<=pBuf->nSpace );
176331      sqlite3Fts5HashScanNext(pHash);
176332    }
176333    sqlite3Fts5HashClear(pHash);
176334    fts5WriteFinish(p, &writer, &pgnoLast);
176335
176336    /* Update the Fts5Structure. It is written back to the database by the
176337    ** fts5StructureRelease() call below.  */
176338    if( pStruct->nLevel==0 ){
176339      fts5StructureAddLevel(&p->rc, &pStruct);
176340    }
176341    fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
176342    if( p->rc==SQLITE_OK ){
176343      pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
176344      pSeg->iSegid = iSegid;
176345      pSeg->pgnoFirst = 1;
176346      pSeg->pgnoLast = pgnoLast;
176347      pStruct->nSegment++;
176348    }
176349    fts5StructurePromote(p, 0, pStruct);
176350  }
176351
176352  fts5IndexAutomerge(p, &pStruct, pgnoLast);
176353  fts5IndexCrisismerge(p, &pStruct);
176354  fts5StructureWrite(p, pStruct);
176355  fts5StructureRelease(pStruct);
176356}
176357
176358/*
176359** Flush any data stored in the in-memory hash tables to the database.
176360*/
176361static void fts5IndexFlush(Fts5Index *p){
176362  /* Unless it is empty, flush the hash table to disk */
176363  if( p->nPendingData ){
176364    assert( p->pHash );
176365    p->nPendingData = 0;
176366    fts5FlushOneHash(p);
176367  }
176368}
176369
176370
176371static int sqlite3Fts5IndexOptimize(Fts5Index *p){
176372  Fts5Structure *pStruct;
176373  Fts5Structure *pNew = 0;
176374  int nSeg = 0;
176375
176376  assert( p->rc==SQLITE_OK );
176377  fts5IndexFlush(p);
176378  pStruct = fts5StructureRead(p);
176379
176380  if( pStruct ){
176381    assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
176382    nSeg = pStruct->nSegment;
176383    if( nSeg>1 ){
176384      int nByte = sizeof(Fts5Structure);
176385      nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
176386      pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
176387    }
176388  }
176389  if( pNew ){
176390    Fts5StructureLevel *pLvl;
176391    int nByte = nSeg * sizeof(Fts5StructureSegment);
176392    pNew->nLevel = pStruct->nLevel+1;
176393    pNew->nRef = 1;
176394    pNew->nWriteCounter = pStruct->nWriteCounter;
176395    pLvl = &pNew->aLevel[pStruct->nLevel];
176396    pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
176397    if( pLvl->aSeg ){
176398      int iLvl, iSeg;
176399      int iSegOut = 0;
176400      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
176401        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
176402          pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
176403          iSegOut++;
176404        }
176405      }
176406      pNew->nSegment = pLvl->nSeg = nSeg;
176407    }else{
176408      sqlite3_free(pNew);
176409      pNew = 0;
176410    }
176411  }
176412
176413  if( pNew ){
176414    int iLvl = pNew->nLevel-1;
176415    while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
176416      int nRem = FTS5_OPT_WORK_UNIT;
176417      fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
176418    }
176419
176420    fts5StructureWrite(p, pNew);
176421    fts5StructureRelease(pNew);
176422  }
176423
176424  fts5StructureRelease(pStruct);
176425  return fts5IndexReturn(p);
176426}
176427
176428static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
176429  Fts5Structure *pStruct;
176430
176431  pStruct = fts5StructureRead(p);
176432  if( pStruct && pStruct->nLevel ){
176433    fts5IndexMerge(p, &pStruct, nMerge);
176434    fts5StructureWrite(p, pStruct);
176435  }
176436  fts5StructureRelease(pStruct);
176437
176438  return fts5IndexReturn(p);
176439}
176440
176441static void fts5PoslistCallback(
176442  Fts5Index *p,
176443  void *pContext,
176444  const u8 *pChunk, int nChunk
176445){
176446  assert_nc( nChunk>=0 );
176447  if( nChunk>0 ){
176448    fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
176449  }
176450}
176451
176452typedef struct PoslistCallbackCtx PoslistCallbackCtx;
176453struct PoslistCallbackCtx {
176454  Fts5Buffer *pBuf;               /* Append to this buffer */
176455  Fts5Colset *pColset;            /* Restrict matches to this column */
176456  int eState;                     /* See above */
176457};
176458
176459/*
176460** TODO: Make this more efficient!
176461*/
176462static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
176463  int i;
176464  for(i=0; i<pColset->nCol; i++){
176465    if( pColset->aiCol[i]==iCol ) return 1;
176466  }
176467  return 0;
176468}
176469
176470static void fts5PoslistFilterCallback(
176471  Fts5Index *p,
176472  void *pContext,
176473  const u8 *pChunk, int nChunk
176474){
176475  PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
176476  assert_nc( nChunk>=0 );
176477  if( nChunk>0 ){
176478    /* Search through to find the first varint with value 1. This is the
176479    ** start of the next columns hits. */
176480    int i = 0;
176481    int iStart = 0;
176482
176483    if( pCtx->eState==2 ){
176484      int iCol;
176485      fts5FastGetVarint32(pChunk, i, iCol);
176486      if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
176487        pCtx->eState = 1;
176488        fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
176489      }else{
176490        pCtx->eState = 0;
176491      }
176492    }
176493
176494    do {
176495      while( i<nChunk && pChunk[i]!=0x01 ){
176496        while( pChunk[i] & 0x80 ) i++;
176497        i++;
176498      }
176499      if( pCtx->eState ){
176500        fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
176501      }
176502      if( i<nChunk ){
176503        int iCol;
176504        iStart = i;
176505        i++;
176506        if( i>=nChunk ){
176507          pCtx->eState = 2;
176508        }else{
176509          fts5FastGetVarint32(pChunk, i, iCol);
176510          pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
176511          if( pCtx->eState ){
176512            fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
176513            iStart = i;
176514          }
176515        }
176516      }
176517    }while( i<nChunk );
176518  }
176519}
176520
176521/*
176522** Iterator pIter currently points to a valid entry (not EOF). This
176523** function appends the position list data for the current entry to
176524** buffer pBuf. It does not make a copy of the position-list size
176525** field.
176526*/
176527static void fts5SegiterPoslist(
176528  Fts5Index *p,
176529  Fts5SegIter *pSeg,
176530  Fts5Colset *pColset,
176531  Fts5Buffer *pBuf
176532){
176533  if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
176534    if( pColset==0 ){
176535      fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
176536    }else{
176537      PoslistCallbackCtx sCtx;
176538      sCtx.pBuf = pBuf;
176539      sCtx.pColset = pColset;
176540      sCtx.eState = pColset ? fts5IndexColsetTest(pColset, 0) : 1;
176541      assert( sCtx.eState==0 || sCtx.eState==1 );
176542      fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
176543    }
176544  }
176545}
176546
176547/*
176548** IN/OUT parameter (*pa) points to a position list n bytes in size. If
176549** the position list contains entries for column iCol, then (*pa) is set
176550** to point to the sub-position-list for that column and the number of
176551** bytes in it returned. Or, if the argument position list does not
176552** contain any entries for column iCol, return 0.
176553*/
176554static int fts5IndexExtractCol(
176555  const u8 **pa,                  /* IN/OUT: Pointer to poslist */
176556  int n,                          /* IN: Size of poslist in bytes */
176557  int iCol                        /* Column to extract from poslist */
176558){
176559  int iCurrent = 0;               /* Anything before the first 0x01 is col 0 */
176560  const u8 *p = *pa;
176561  const u8 *pEnd = &p[n];         /* One byte past end of position list */
176562  u8 prev = 0;
176563
176564  while( iCol!=iCurrent ){
176565    /* Advance pointer p until it points to pEnd or an 0x01 byte that is
176566    ** not part of a varint */
176567    while( (prev & 0x80) || *p!=0x01 ){
176568      prev = *p++;
176569      if( p==pEnd ) return 0;
176570    }
176571    *pa = p++;
176572    p += fts5GetVarint32(p, iCurrent);
176573  }
176574
176575  /* Advance pointer p until it points to pEnd or an 0x01 byte that is
176576  ** not part of a varint */
176577  assert( (prev & 0x80)==0 );
176578  while( p<pEnd && ((prev & 0x80) || *p!=0x01) ){
176579    prev = *p++;
176580  }
176581  return p - (*pa);
176582}
176583
176584
176585/*
176586** Iterator pMulti currently points to a valid entry (not EOF). This
176587** function appends the following to buffer pBuf:
176588**
176589**   * The varint iDelta, and
176590**   * the position list that currently points to, including the size field.
176591**
176592** If argument pColset is NULL, then the position list is filtered according
176593** to pColset before being appended to the buffer. If this means there are
176594** no entries in the position list, nothing is appended to the buffer (not
176595** even iDelta).
176596**
176597** If an error occurs, an error code is left in p->rc.
176598*/
176599static int fts5AppendPoslist(
176600  Fts5Index *p,
176601  i64 iDelta,
176602  Fts5IndexIter *pMulti,
176603  Fts5Colset *pColset,
176604  Fts5Buffer *pBuf
176605){
176606  if( p->rc==SQLITE_OK ){
176607    Fts5SegIter *pSeg = &pMulti->aSeg[ pMulti->aFirst[1].iFirst ];
176608    assert( fts5MultiIterEof(p, pMulti)==0 );
176609    assert( pSeg->nPos>0 );
176610    if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos+9+9) ){
176611      int iSv1;
176612      int iSv2;
176613      int iData;
176614
176615      /* Append iDelta */
176616      iSv1 = pBuf->n;
176617      fts5BufferSafeAppendVarint(pBuf, iDelta);
176618
176619      /* WRITEPOSLISTSIZE */
176620      iSv2 = pBuf->n;
176621      fts5BufferSafeAppendVarint(pBuf, pSeg->nPos*2);
176622      iData = pBuf->n;
176623
176624      if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf
176625       && (pColset==0 || pColset->nCol==1)
176626      ){
176627        const u8 *pPos = &pSeg->pLeaf->p[pSeg->iLeafOffset];
176628        int nPos;
176629        if( pColset ){
176630          nPos = fts5IndexExtractCol(&pPos, pSeg->nPos, pColset->aiCol[0]);
176631        }else{
176632          nPos = pSeg->nPos;
176633        }
176634        fts5BufferSafeAppendBlob(pBuf, pPos, nPos);
176635      }else{
176636        fts5SegiterPoslist(p, pSeg, pColset, pBuf);
176637      }
176638
176639      if( pColset ){
176640        int nActual = pBuf->n - iData;
176641        if( nActual!=pSeg->nPos ){
176642          if( nActual==0 ){
176643            pBuf->n = iSv1;
176644            return 1;
176645          }else{
176646            int nReq = sqlite3Fts5GetVarintLen((u32)(nActual*2));
176647            while( iSv2<(iData-nReq) ){ pBuf->p[iSv2++] = 0x80; }
176648            sqlite3Fts5PutVarint(&pBuf->p[iSv2], nActual*2);
176649          }
176650        }
176651      }
176652    }
176653  }
176654
176655  return 0;
176656}
176657
176658static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
176659  u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
176660
176661  assert( pIter->aPoslist );
176662  if( p>=pIter->aEof ){
176663    pIter->aPoslist = 0;
176664  }else{
176665    i64 iDelta;
176666
176667    p += fts5GetVarint(p, (u64*)&iDelta);
176668    pIter->iRowid += iDelta;
176669
176670    /* Read position list size */
176671    if( p[0] & 0x80 ){
176672      int nPos;
176673      pIter->nSize = fts5GetVarint32(p, nPos);
176674      pIter->nPoslist = (nPos>>1);
176675    }else{
176676      pIter->nPoslist = ((int)(p[0])) >> 1;
176677      pIter->nSize = 1;
176678    }
176679
176680    pIter->aPoslist = p;
176681  }
176682}
176683
176684static void fts5DoclistIterInit(
176685  Fts5Buffer *pBuf,
176686  Fts5DoclistIter *pIter
176687){
176688  memset(pIter, 0, sizeof(*pIter));
176689  pIter->aPoslist = pBuf->p;
176690  pIter->aEof = &pBuf->p[pBuf->n];
176691  fts5DoclistIterNext(pIter);
176692}
176693
176694#if 0
176695/*
176696** Append a doclist to buffer pBuf.
176697**
176698** This function assumes that space within the buffer has already been
176699** allocated.
176700*/
176701static void fts5MergeAppendDocid(
176702  Fts5Buffer *pBuf,               /* Buffer to write to */
176703  i64 *piLastRowid,               /* IN/OUT: Previous rowid written (if any) */
176704  i64 iRowid                      /* Rowid to append */
176705){
176706  assert( pBuf->n!=0 || (*piLastRowid)==0 );
176707  fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
176708  *piLastRowid = iRowid;
176709}
176710#endif
176711
176712#define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) {       \
176713  assert( (pBuf)->n!=0 || (iLastRowid)==0 );                   \
176714  fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
176715  (iLastRowid) = (iRowid);                                     \
176716}
176717
176718/*
176719** Buffers p1 and p2 contain doclists. This function merges the content
176720** of the two doclists together and sets buffer p1 to the result before
176721** returning.
176722**
176723** If an error occurs, an error code is left in p->rc. If an error has
176724** already occurred, this function is a no-op.
176725*/
176726static void fts5MergePrefixLists(
176727  Fts5Index *p,                   /* FTS5 backend object */
176728  Fts5Buffer *p1,                 /* First list to merge */
176729  Fts5Buffer *p2                  /* Second list to merge */
176730){
176731  if( p2->n ){
176732    i64 iLastRowid = 0;
176733    Fts5DoclistIter i1;
176734    Fts5DoclistIter i2;
176735    Fts5Buffer out;
176736    Fts5Buffer tmp;
176737    memset(&out, 0, sizeof(out));
176738    memset(&tmp, 0, sizeof(tmp));
176739
176740    sqlite3Fts5BufferGrow(&p->rc, &out, p1->n + p2->n);
176741    fts5DoclistIterInit(p1, &i1);
176742    fts5DoclistIterInit(p2, &i2);
176743    while( p->rc==SQLITE_OK && (i1.aPoslist!=0 || i2.aPoslist!=0) ){
176744      if( i2.aPoslist==0 || (i1.aPoslist && i1.iRowid<i2.iRowid) ){
176745        /* Copy entry from i1 */
176746        fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
176747        fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
176748        fts5DoclistIterNext(&i1);
176749      }
176750      else if( i1.aPoslist==0 || i2.iRowid!=i1.iRowid ){
176751        /* Copy entry from i2 */
176752        fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
176753        fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
176754        fts5DoclistIterNext(&i2);
176755      }
176756      else{
176757        i64 iPos1 = 0;
176758        i64 iPos2 = 0;
176759        int iOff1 = 0;
176760        int iOff2 = 0;
176761        u8 *a1 = &i1.aPoslist[i1.nSize];
176762        u8 *a2 = &i2.aPoslist[i2.nSize];
176763
176764        Fts5PoslistWriter writer;
176765        memset(&writer, 0, sizeof(writer));
176766
176767        /* Merge the two position lists. */
176768        fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
176769        fts5BufferZero(&tmp);
176770
176771        sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
176772        sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
176773
176774        while( p->rc==SQLITE_OK && (iPos1>=0 || iPos2>=0) ){
176775          i64 iNew;
176776          if( iPos2<0 || (iPos1>=0 && iPos1<iPos2) ){
176777            iNew = iPos1;
176778            sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
176779          }else{
176780            iNew = iPos2;
176781            sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
176782            if( iPos1==iPos2 ){
176783              sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1,&iPos1);
176784            }
176785          }
176786          p->rc = sqlite3Fts5PoslistWriterAppend(&tmp, &writer, iNew);
176787        }
176788
176789        /* WRITEPOSLISTSIZE */
176790        fts5BufferSafeAppendVarint(&out, tmp.n * 2);
176791        fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
176792        fts5DoclistIterNext(&i1);
176793        fts5DoclistIterNext(&i2);
176794      }
176795    }
176796
176797    fts5BufferSet(&p->rc, p1, out.n, out.p);
176798    fts5BufferFree(&tmp);
176799    fts5BufferFree(&out);
176800  }
176801}
176802
176803static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
176804  Fts5Buffer tmp = *p1;
176805  *p1 = *p2;
176806  *p2 = tmp;
176807}
176808
176809static void fts5SetupPrefixIter(
176810  Fts5Index *p,                   /* Index to read from */
176811  int bDesc,                      /* True for "ORDER BY rowid DESC" */
176812  const u8 *pToken,               /* Buffer containing prefix to match */
176813  int nToken,                     /* Size of buffer pToken in bytes */
176814  Fts5Colset *pColset,            /* Restrict matches to these columns */
176815  Fts5IndexIter **ppIter          /* OUT: New iterator */
176816){
176817  Fts5Structure *pStruct;
176818  Fts5Buffer *aBuf;
176819  const int nBuf = 32;
176820
176821  aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
176822  pStruct = fts5StructureRead(p);
176823
176824  if( aBuf && pStruct ){
176825    const int flags = FTS5INDEX_QUERY_SCAN;
176826    int i;
176827    i64 iLastRowid = 0;
176828    Fts5IndexIter *p1 = 0;     /* Iterator used to gather data from index */
176829    Fts5Data *pData;
176830    Fts5Buffer doclist;
176831
176832    memset(&doclist, 0, sizeof(doclist));
176833    for(fts5MultiIterNew(p, pStruct, 1, flags, pToken, nToken, -1, 0, &p1);
176834        fts5MultiIterEof(p, p1)==0;
176835        fts5MultiIterNext(p, p1, 0, 0)
176836    ){
176837      i64 iRowid = fts5MultiIterRowid(p1);
176838      int nTerm;
176839      const u8 *pTerm = fts5MultiIterTerm(p1, &nTerm);
176840      assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
176841      if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
176842
176843      if( doclist.n>0 && iRowid<=iLastRowid ){
176844        for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
176845          assert( i<nBuf );
176846          if( aBuf[i].n==0 ){
176847            fts5BufferSwap(&doclist, &aBuf[i]);
176848            fts5BufferZero(&doclist);
176849          }else{
176850            fts5MergePrefixLists(p, &doclist, &aBuf[i]);
176851            fts5BufferZero(&aBuf[i]);
176852          }
176853        }
176854        iLastRowid = 0;
176855      }
176856
176857      if( !fts5AppendPoslist(p, iRowid-iLastRowid, p1, pColset, &doclist) ){
176858        iLastRowid = iRowid;
176859      }
176860    }
176861
176862    for(i=0; i<nBuf; i++){
176863      if( p->rc==SQLITE_OK ){
176864        fts5MergePrefixLists(p, &doclist, &aBuf[i]);
176865      }
176866      fts5BufferFree(&aBuf[i]);
176867    }
176868    fts5MultiIterFree(p, p1);
176869
176870    pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
176871    if( pData ){
176872      pData->p = (u8*)&pData[1];
176873      pData->nn = pData->szLeaf = doclist.n;
176874      memcpy(pData->p, doclist.p, doclist.n);
176875      fts5MultiIterNew2(p, pData, bDesc, ppIter);
176876    }
176877    fts5BufferFree(&doclist);
176878  }
176879
176880  fts5StructureRelease(pStruct);
176881  sqlite3_free(aBuf);
176882}
176883
176884
176885/*
176886** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
176887** to the document with rowid iRowid.
176888*/
176889static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
176890  assert( p->rc==SQLITE_OK );
176891
176892  /* Allocate the hash table if it has not already been allocated */
176893  if( p->pHash==0 ){
176894    p->rc = sqlite3Fts5HashNew(&p->pHash, &p->nPendingData);
176895  }
176896
176897  /* Flush the hash table to disk if required */
176898  if( iRowid<p->iWriteRowid
176899   || (iRowid==p->iWriteRowid && p->bDelete==0)
176900   || (p->nPendingData > p->nMaxPendingData)
176901  ){
176902    fts5IndexFlush(p);
176903  }
176904
176905  p->iWriteRowid = iRowid;
176906  p->bDelete = bDelete;
176907  return fts5IndexReturn(p);
176908}
176909
176910/*
176911** Commit data to disk.
176912*/
176913static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit){
176914  assert( p->rc==SQLITE_OK );
176915  fts5IndexFlush(p);
176916  if( bCommit ) fts5CloseReader(p);
176917  return fts5IndexReturn(p);
176918}
176919
176920/*
176921** Discard any data stored in the in-memory hash tables. Do not write it
176922** to the database. Additionally, assume that the contents of the %_data
176923** table may have changed on disk. So any in-memory caches of %_data
176924** records must be invalidated.
176925*/
176926static int sqlite3Fts5IndexRollback(Fts5Index *p){
176927  fts5CloseReader(p);
176928  fts5IndexDiscardData(p);
176929  assert( p->rc==SQLITE_OK );
176930  return SQLITE_OK;
176931}
176932
176933/*
176934** The %_data table is completely empty when this function is called. This
176935** function populates it with the initial structure objects for each index,
176936** and the initial version of the "averages" record (a zero-byte blob).
176937*/
176938static int sqlite3Fts5IndexReinit(Fts5Index *p){
176939  Fts5Structure s;
176940  memset(&s, 0, sizeof(Fts5Structure));
176941  fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
176942  fts5StructureWrite(p, &s);
176943  return fts5IndexReturn(p);
176944}
176945
176946/*
176947** Open a new Fts5Index handle. If the bCreate argument is true, create
176948** and initialize the underlying %_data table.
176949**
176950** If successful, set *pp to point to the new object and return SQLITE_OK.
176951** Otherwise, set *pp to NULL and return an SQLite error code.
176952*/
176953static int sqlite3Fts5IndexOpen(
176954  Fts5Config *pConfig,
176955  int bCreate,
176956  Fts5Index **pp,
176957  char **pzErr
176958){
176959  int rc = SQLITE_OK;
176960  Fts5Index *p;                   /* New object */
176961
176962  *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
176963  if( rc==SQLITE_OK ){
176964    p->pConfig = pConfig;
176965    p->nWorkUnit = FTS5_WORK_UNIT;
176966    p->nMaxPendingData = 1024*1024;
176967    p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
176968    if( p->zDataTbl && bCreate ){
176969      rc = sqlite3Fts5CreateTable(
176970          pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
176971      );
176972      if( rc==SQLITE_OK ){
176973        rc = sqlite3Fts5CreateTable(pConfig, "idx",
176974            "segid, term, pgno, PRIMARY KEY(segid, term)",
176975            1, pzErr
176976        );
176977      }
176978      if( rc==SQLITE_OK ){
176979        rc = sqlite3Fts5IndexReinit(p);
176980      }
176981    }
176982  }
176983
176984  assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
176985  if( rc ){
176986    sqlite3Fts5IndexClose(p);
176987    *pp = 0;
176988  }
176989  return rc;
176990}
176991
176992/*
176993** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
176994*/
176995static int sqlite3Fts5IndexClose(Fts5Index *p){
176996  int rc = SQLITE_OK;
176997  if( p ){
176998    assert( p->pReader==0 );
176999    sqlite3_finalize(p->pWriter);
177000    sqlite3_finalize(p->pDeleter);
177001    sqlite3_finalize(p->pIdxWriter);
177002    sqlite3_finalize(p->pIdxDeleter);
177003    sqlite3_finalize(p->pIdxSelect);
177004    sqlite3Fts5HashFree(p->pHash);
177005    sqlite3_free(p->zDataTbl);
177006    sqlite3_free(p);
177007  }
177008  return rc;
177009}
177010
177011/*
177012** Argument p points to a buffer containing utf-8 text that is n bytes in
177013** size. Return the number of bytes in the nChar character prefix of the
177014** buffer, or 0 if there are less than nChar characters in total.
177015*/
177016static int fts5IndexCharlenToBytelen(const char *p, int nByte, int nChar){
177017  int n = 0;
177018  int i;
177019  for(i=0; i<nChar; i++){
177020    if( n>=nByte ) return 0;      /* Input contains fewer than nChar chars */
177021    if( (unsigned char)p[n++]>=0xc0 ){
177022      while( (p[n] & 0xc0)==0x80 ) n++;
177023    }
177024  }
177025  return n;
177026}
177027
177028/*
177029** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
177030** unicode characters in the string.
177031*/
177032static int fts5IndexCharlen(const char *pIn, int nIn){
177033  int nChar = 0;
177034  int i = 0;
177035  while( i<nIn ){
177036    if( (unsigned char)pIn[i++]>=0xc0 ){
177037      while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
177038    }
177039    nChar++;
177040  }
177041  return nChar;
177042}
177043
177044/*
177045** Insert or remove data to or from the index. Each time a document is
177046** added to or removed from the index, this function is called one or more
177047** times.
177048**
177049** For an insert, it must be called once for each token in the new document.
177050** If the operation is a delete, it must be called (at least) once for each
177051** unique token in the document with an iCol value less than zero. The iPos
177052** argument is ignored for a delete.
177053*/
177054static int sqlite3Fts5IndexWrite(
177055  Fts5Index *p,                   /* Index to write to */
177056  int iCol,                       /* Column token appears in (-ve -> delete) */
177057  int iPos,                       /* Position of token within column */
177058  const char *pToken, int nToken  /* Token to add or remove to or from index */
177059){
177060  int i;                          /* Used to iterate through indexes */
177061  int rc = SQLITE_OK;             /* Return code */
177062  Fts5Config *pConfig = p->pConfig;
177063
177064  assert( p->rc==SQLITE_OK );
177065  assert( (iCol<0)==p->bDelete );
177066
177067  /* Add the entry to the main terms index. */
177068  rc = sqlite3Fts5HashWrite(
177069      p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
177070  );
177071
177072  for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
177073    int nByte = fts5IndexCharlenToBytelen(pToken, nToken, pConfig->aPrefix[i]);
177074    if( nByte ){
177075      rc = sqlite3Fts5HashWrite(p->pHash,
177076          p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX+i+1, pToken, nByte
177077      );
177078    }
177079  }
177080
177081  return rc;
177082}
177083
177084/*
177085** Open a new iterator to iterate though all rowid that match the
177086** specified token or token prefix.
177087*/
177088static int sqlite3Fts5IndexQuery(
177089  Fts5Index *p,                   /* FTS index to query */
177090  const char *pToken, int nToken, /* Token (or prefix) to query for */
177091  int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
177092  Fts5Colset *pColset,            /* Match these columns only */
177093  Fts5IndexIter **ppIter          /* OUT: New iterator object */
177094){
177095  Fts5Config *pConfig = p->pConfig;
177096  Fts5IndexIter *pRet = 0;
177097  int iIdx = 0;
177098  Fts5Buffer buf = {0, 0, 0};
177099
177100  /* If the QUERY_SCAN flag is set, all other flags must be clear. */
177101  assert( (flags & FTS5INDEX_QUERY_SCAN)==0
177102       || (flags & FTS5INDEX_QUERY_SCAN)==FTS5INDEX_QUERY_SCAN
177103  );
177104
177105  if( sqlite3Fts5BufferGrow(&p->rc, &buf, nToken+1)==0 ){
177106    memcpy(&buf.p[1], pToken, nToken);
177107
177108#ifdef SQLITE_DEBUG
177109    /* If the QUERY_TEST_NOIDX flag was specified, then this must be a
177110    ** prefix-query. Instead of using a prefix-index (if one exists),
177111    ** evaluate the prefix query using the main FTS index. This is used
177112    ** for internal sanity checking by the integrity-check in debug
177113    ** mode only.  */
177114    if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
177115      assert( flags & FTS5INDEX_QUERY_PREFIX );
177116      iIdx = 1+pConfig->nPrefix;
177117    }else
177118#endif
177119    if( flags & FTS5INDEX_QUERY_PREFIX ){
177120      int nChar = fts5IndexCharlen(pToken, nToken);
177121      for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
177122        if( pConfig->aPrefix[iIdx-1]==nChar ) break;
177123      }
177124    }
177125
177126    if( iIdx<=pConfig->nPrefix ){
177127      Fts5Structure *pStruct = fts5StructureRead(p);
177128      buf.p[0] = FTS5_MAIN_PREFIX + iIdx;
177129      if( pStruct ){
177130        fts5MultiIterNew(p, pStruct, 1, flags, buf.p, nToken+1, -1, 0, &pRet);
177131        fts5StructureRelease(pStruct);
177132      }
177133    }else{
177134      int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
177135      buf.p[0] = FTS5_MAIN_PREFIX;
177136      fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
177137    }
177138
177139    if( p->rc ){
177140      sqlite3Fts5IterClose(pRet);
177141      pRet = 0;
177142      fts5CloseReader(p);
177143    }
177144    *ppIter = pRet;
177145    sqlite3Fts5BufferFree(&buf);
177146  }
177147  return fts5IndexReturn(p);
177148}
177149
177150/*
177151** Return true if the iterator passed as the only argument is at EOF.
177152*/
177153static int sqlite3Fts5IterEof(Fts5IndexIter *pIter){
177154  assert( pIter->pIndex->rc==SQLITE_OK );
177155  return pIter->bEof;
177156}
177157
177158/*
177159** Move to the next matching rowid.
177160*/
177161static int sqlite3Fts5IterNext(Fts5IndexIter *pIter){
177162  assert( pIter->pIndex->rc==SQLITE_OK );
177163  fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
177164  return fts5IndexReturn(pIter->pIndex);
177165}
177166
177167/*
177168** Move to the next matching term/rowid. Used by the fts5vocab module.
177169*/
177170static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIter){
177171  Fts5Index *p = pIter->pIndex;
177172
177173  assert( pIter->pIndex->rc==SQLITE_OK );
177174
177175  fts5MultiIterNext(p, pIter, 0, 0);
177176  if( p->rc==SQLITE_OK ){
177177    Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
177178    if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
177179      fts5DataRelease(pSeg->pLeaf);
177180      pSeg->pLeaf = 0;
177181      pIter->bEof = 1;
177182    }
177183  }
177184
177185  return fts5IndexReturn(pIter->pIndex);
177186}
177187
177188/*
177189** Move to the next matching rowid that occurs at or after iMatch. The
177190** definition of "at or after" depends on whether this iterator iterates
177191** in ascending or descending rowid order.
177192*/
177193static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIter, i64 iMatch){
177194  fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
177195  return fts5IndexReturn(pIter->pIndex);
177196}
177197
177198/*
177199** Return the current rowid.
177200*/
177201static i64 sqlite3Fts5IterRowid(Fts5IndexIter *pIter){
177202  return fts5MultiIterRowid(pIter);
177203}
177204
177205/*
177206** Return the current term.
177207*/
177208static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIter, int *pn){
177209  int n;
177210  const char *z = (const char*)fts5MultiIterTerm(pIter, &n);
177211  *pn = n-1;
177212  return &z[1];
177213}
177214
177215
177216static int fts5IndexExtractColset (
177217  Fts5Colset *pColset,            /* Colset to filter on */
177218  const u8 *pPos, int nPos,       /* Position list */
177219  Fts5Buffer *pBuf                /* Output buffer */
177220){
177221  int rc = SQLITE_OK;
177222  int i;
177223
177224  fts5BufferZero(pBuf);
177225  for(i=0; i<pColset->nCol; i++){
177226    const u8 *pSub = pPos;
177227    int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
177228    if( nSub ){
177229      fts5BufferAppendBlob(&rc, pBuf, nSub, pSub);
177230    }
177231  }
177232  return rc;
177233}
177234
177235
177236/*
177237** Return a pointer to a buffer containing a copy of the position list for
177238** the current entry. Output variable *pn is set to the size of the buffer
177239** in bytes before returning.
177240**
177241** The returned position list does not include the "number of bytes" varint
177242** field that starts the position list on disk.
177243*/
177244static int sqlite3Fts5IterPoslist(
177245  Fts5IndexIter *pIter,
177246  Fts5Colset *pColset,            /* Column filter (or NULL) */
177247  const u8 **pp,                  /* OUT: Pointer to position-list data */
177248  int *pn,                        /* OUT: Size of position-list in bytes */
177249  i64 *piRowid                    /* OUT: Current rowid */
177250){
177251  Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
177252  assert( pIter->pIndex->rc==SQLITE_OK );
177253  *piRowid = pSeg->iRowid;
177254  if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
177255    u8 *pPos = &pSeg->pLeaf->p[pSeg->iLeafOffset];
177256    if( pColset==0 || pIter->bFiltered ){
177257      *pn = pSeg->nPos;
177258      *pp = pPos;
177259    }else if( pColset->nCol==1 ){
177260      *pp = pPos;
177261      *pn = fts5IndexExtractCol(pp, pSeg->nPos, pColset->aiCol[0]);
177262    }else{
177263      fts5BufferZero(&pIter->poslist);
177264      fts5IndexExtractColset(pColset, pPos, pSeg->nPos, &pIter->poslist);
177265      *pp = pIter->poslist.p;
177266      *pn = pIter->poslist.n;
177267    }
177268  }else{
177269    fts5BufferZero(&pIter->poslist);
177270    fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
177271    *pp = pIter->poslist.p;
177272    *pn = pIter->poslist.n;
177273  }
177274  return fts5IndexReturn(pIter->pIndex);
177275}
177276
177277/*
177278** This function is similar to sqlite3Fts5IterPoslist(), except that it
177279** copies the position list into the buffer supplied as the second
177280** argument.
177281*/
177282static int sqlite3Fts5IterPoslistBuffer(Fts5IndexIter *pIter, Fts5Buffer *pBuf){
177283  Fts5Index *p = pIter->pIndex;
177284  Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
177285  assert( p->rc==SQLITE_OK );
177286  fts5BufferZero(pBuf);
177287  fts5SegiterPoslist(p, pSeg, 0, pBuf);
177288  return fts5IndexReturn(p);
177289}
177290
177291/*
177292** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
177293*/
177294static void sqlite3Fts5IterClose(Fts5IndexIter *pIter){
177295  if( pIter ){
177296    Fts5Index *pIndex = pIter->pIndex;
177297    fts5MultiIterFree(pIter->pIndex, pIter);
177298    fts5CloseReader(pIndex);
177299  }
177300}
177301
177302/*
177303** Read and decode the "averages" record from the database.
177304**
177305** Parameter anSize must point to an array of size nCol, where nCol is
177306** the number of user defined columns in the FTS table.
177307*/
177308static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
177309  int nCol = p->pConfig->nCol;
177310  Fts5Data *pData;
177311
177312  *pnRow = 0;
177313  memset(anSize, 0, sizeof(i64) * nCol);
177314  pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
177315  if( p->rc==SQLITE_OK && pData->nn ){
177316    int i = 0;
177317    int iCol;
177318    i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
177319    for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
177320      i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
177321    }
177322  }
177323
177324  fts5DataRelease(pData);
177325  return fts5IndexReturn(p);
177326}
177327
177328/*
177329** Replace the current "averages" record with the contents of the buffer
177330** supplied as the second argument.
177331*/
177332static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
177333  assert( p->rc==SQLITE_OK );
177334  fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
177335  return fts5IndexReturn(p);
177336}
177337
177338/*
177339** Return the total number of blocks this module has read from the %_data
177340** table since it was created.
177341*/
177342static int sqlite3Fts5IndexReads(Fts5Index *p){
177343  return p->nRead;
177344}
177345
177346/*
177347** Set the 32-bit cookie value stored at the start of all structure
177348** records to the value passed as the second argument.
177349**
177350** Return SQLITE_OK if successful, or an SQLite error code if an error
177351** occurs.
177352*/
177353static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
177354  int rc;                              /* Return code */
177355  Fts5Config *pConfig = p->pConfig;    /* Configuration object */
177356  u8 aCookie[4];                       /* Binary representation of iNew */
177357  sqlite3_blob *pBlob = 0;
177358
177359  assert( p->rc==SQLITE_OK );
177360  sqlite3Fts5Put32(aCookie, iNew);
177361
177362  rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
177363      "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
177364  );
177365  if( rc==SQLITE_OK ){
177366    sqlite3_blob_write(pBlob, aCookie, 4, 0);
177367    rc = sqlite3_blob_close(pBlob);
177368  }
177369
177370  return rc;
177371}
177372
177373static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
177374  Fts5Structure *pStruct;
177375  pStruct = fts5StructureRead(p);
177376  fts5StructureRelease(pStruct);
177377  return fts5IndexReturn(p);
177378}
177379
177380
177381/*************************************************************************
177382**************************************************************************
177383** Below this point is the implementation of the integrity-check
177384** functionality.
177385*/
177386
177387/*
177388** Return a simple checksum value based on the arguments.
177389*/
177390static u64 fts5IndexEntryCksum(
177391  i64 iRowid,
177392  int iCol,
177393  int iPos,
177394  int iIdx,
177395  const char *pTerm,
177396  int nTerm
177397){
177398  int i;
177399  u64 ret = iRowid;
177400  ret += (ret<<3) + iCol;
177401  ret += (ret<<3) + iPos;
177402  if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
177403  for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
177404  return ret;
177405}
177406
177407#ifdef SQLITE_DEBUG
177408/*
177409** This function is purely an internal test. It does not contribute to
177410** FTS functionality, or even the integrity-check, in any way.
177411**
177412** Instead, it tests that the same set of pgno/rowid combinations are
177413** visited regardless of whether the doclist-index identified by parameters
177414** iSegid/iLeaf is iterated in forwards or reverse order.
177415*/
177416static void fts5TestDlidxReverse(
177417  Fts5Index *p,
177418  int iSegid,                     /* Segment id to load from */
177419  int iLeaf                       /* Load doclist-index for this leaf */
177420){
177421  Fts5DlidxIter *pDlidx = 0;
177422  u64 cksum1 = 13;
177423  u64 cksum2 = 13;
177424
177425  for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
177426      fts5DlidxIterEof(p, pDlidx)==0;
177427      fts5DlidxIterNext(p, pDlidx)
177428  ){
177429    i64 iRowid = fts5DlidxIterRowid(pDlidx);
177430    int pgno = fts5DlidxIterPgno(pDlidx);
177431    assert( pgno>iLeaf );
177432    cksum1 += iRowid + ((i64)pgno<<32);
177433  }
177434  fts5DlidxIterFree(pDlidx);
177435  pDlidx = 0;
177436
177437  for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
177438      fts5DlidxIterEof(p, pDlidx)==0;
177439      fts5DlidxIterPrev(p, pDlidx)
177440  ){
177441    i64 iRowid = fts5DlidxIterRowid(pDlidx);
177442    int pgno = fts5DlidxIterPgno(pDlidx);
177443    assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
177444    cksum2 += iRowid + ((i64)pgno<<32);
177445  }
177446  fts5DlidxIterFree(pDlidx);
177447  pDlidx = 0;
177448
177449  if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
177450}
177451
177452static int fts5QueryCksum(
177453  Fts5Index *p,                   /* Fts5 index object */
177454  int iIdx,
177455  const char *z,                  /* Index key to query for */
177456  int n,                          /* Size of index key in bytes */
177457  int flags,                      /* Flags for Fts5IndexQuery */
177458  u64 *pCksum                     /* IN/OUT: Checksum value */
177459){
177460  u64 cksum = *pCksum;
177461  Fts5IndexIter *pIdxIter = 0;
177462  int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIdxIter);
177463
177464  while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIdxIter) ){
177465    i64 dummy;
177466    const u8 *pPos;
177467    int nPos;
177468    i64 rowid = sqlite3Fts5IterRowid(pIdxIter);
177469    rc = sqlite3Fts5IterPoslist(pIdxIter, 0, &pPos, &nPos, &dummy);
177470    if( rc==SQLITE_OK ){
177471      Fts5PoslistReader sReader;
177472      for(sqlite3Fts5PoslistReaderInit(pPos, nPos, &sReader);
177473          sReader.bEof==0;
177474          sqlite3Fts5PoslistReaderNext(&sReader)
177475      ){
177476        int iCol = FTS5_POS2COLUMN(sReader.iPos);
177477        int iOff = FTS5_POS2OFFSET(sReader.iPos);
177478        cksum ^= fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
177479      }
177480      rc = sqlite3Fts5IterNext(pIdxIter);
177481    }
177482  }
177483  sqlite3Fts5IterClose(pIdxIter);
177484
177485  *pCksum = cksum;
177486  return rc;
177487}
177488
177489
177490/*
177491** This function is also purely an internal test. It does not contribute to
177492** FTS functionality, or even the integrity-check, in any way.
177493*/
177494static void fts5TestTerm(
177495  Fts5Index *p,
177496  Fts5Buffer *pPrev,              /* Previous term */
177497  const char *z, int n,           /* Possibly new term to test */
177498  u64 expected,
177499  u64 *pCksum
177500){
177501  int rc = p->rc;
177502  if( pPrev->n==0 ){
177503    fts5BufferSet(&rc, pPrev, n, (const u8*)z);
177504  }else
177505  if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
177506    u64 cksum3 = *pCksum;
177507    const char *zTerm = (const char*)&pPrev->p[1];  /* term sans prefix-byte */
177508    int nTerm = pPrev->n-1;            /* Size of zTerm in bytes */
177509    int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
177510    int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
177511    u64 ck1 = 0;
177512    u64 ck2 = 0;
177513
177514    /* Check that the results returned for ASC and DESC queries are
177515    ** the same. If not, call this corruption.  */
177516    rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
177517    if( rc==SQLITE_OK ){
177518      int f = flags|FTS5INDEX_QUERY_DESC;
177519      rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
177520    }
177521    if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
177522
177523    /* If this is a prefix query, check that the results returned if the
177524    ** the index is disabled are the same. In both ASC and DESC order.
177525    **
177526    ** This check may only be performed if the hash table is empty. This
177527    ** is because the hash table only supports a single scan query at
177528    ** a time, and the multi-iter loop from which this function is called
177529    ** is already performing such a scan. */
177530    if( p->nPendingData==0 ){
177531      if( iIdx>0 && rc==SQLITE_OK ){
177532        int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
177533        ck2 = 0;
177534        rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
177535        if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
177536      }
177537      if( iIdx>0 && rc==SQLITE_OK ){
177538        int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
177539        ck2 = 0;
177540        rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
177541        if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
177542      }
177543    }
177544
177545    cksum3 ^= ck1;
177546    fts5BufferSet(&rc, pPrev, n, (const u8*)z);
177547
177548    if( rc==SQLITE_OK && cksum3!=expected ){
177549      rc = FTS5_CORRUPT;
177550    }
177551    *pCksum = cksum3;
177552  }
177553  p->rc = rc;
177554}
177555
177556#else
177557# define fts5TestDlidxReverse(x,y,z)
177558# define fts5TestTerm(u,v,w,x,y,z)
177559#endif
177560
177561/*
177562** Check that:
177563**
177564**   1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
177565**      contain zero terms.
177566**   2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
177567**      contain zero rowids.
177568*/
177569static void fts5IndexIntegrityCheckEmpty(
177570  Fts5Index *p,
177571  Fts5StructureSegment *pSeg,     /* Segment to check internal consistency */
177572  int iFirst,
177573  int iNoRowid,
177574  int iLast
177575){
177576  int i;
177577
177578  /* Now check that the iter.nEmpty leaves following the current leaf
177579  ** (a) exist and (b) contain no terms. */
177580  for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
177581    Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
177582    if( pLeaf ){
177583      if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
177584      if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
177585    }
177586    fts5DataRelease(pLeaf);
177587  }
177588}
177589
177590static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
177591  int iTermOff = 0;
177592  int ii;
177593
177594  Fts5Buffer buf1 = {0,0,0};
177595  Fts5Buffer buf2 = {0,0,0};
177596
177597  ii = pLeaf->szLeaf;
177598  while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
177599    int res;
177600    int iOff;
177601    int nIncr;
177602
177603    ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
177604    iTermOff += nIncr;
177605    iOff = iTermOff;
177606
177607    if( iOff>=pLeaf->szLeaf ){
177608      p->rc = FTS5_CORRUPT;
177609    }else if( iTermOff==nIncr ){
177610      int nByte;
177611      iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
177612      if( (iOff+nByte)>pLeaf->szLeaf ){
177613        p->rc = FTS5_CORRUPT;
177614      }else{
177615        fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
177616      }
177617    }else{
177618      int nKeep, nByte;
177619      iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
177620      iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
177621      if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
177622        p->rc = FTS5_CORRUPT;
177623      }else{
177624        buf1.n = nKeep;
177625        fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
177626      }
177627
177628      if( p->rc==SQLITE_OK ){
177629        res = fts5BufferCompare(&buf1, &buf2);
177630        if( res<=0 ) p->rc = FTS5_CORRUPT;
177631      }
177632    }
177633    fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
177634  }
177635
177636  fts5BufferFree(&buf1);
177637  fts5BufferFree(&buf2);
177638}
177639
177640static void fts5IndexIntegrityCheckSegment(
177641  Fts5Index *p,                   /* FTS5 backend object */
177642  Fts5StructureSegment *pSeg      /* Segment to check internal consistency */
177643){
177644  Fts5Config *pConfig = p->pConfig;
177645  sqlite3_stmt *pStmt = 0;
177646  int rc2;
177647  int iIdxPrevLeaf = pSeg->pgnoFirst-1;
177648  int iDlidxPrevLeaf = pSeg->pgnoLast;
177649
177650  if( pSeg->pgnoFirst==0 ) return;
177651
177652  fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
177653      "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
177654      pConfig->zDb, pConfig->zName, pSeg->iSegid
177655  ));
177656
177657  /* Iterate through the b-tree hierarchy.  */
177658  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
177659    i64 iRow;                     /* Rowid for this leaf */
177660    Fts5Data *pLeaf;              /* Data for this leaf */
177661
177662    int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
177663    const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
177664    int iIdxLeaf = sqlite3_column_int(pStmt, 2);
177665    int bIdxDlidx = sqlite3_column_int(pStmt, 3);
177666
177667    /* If the leaf in question has already been trimmed from the segment,
177668    ** ignore this b-tree entry. Otherwise, load it into memory. */
177669    if( iIdxLeaf<pSeg->pgnoFirst ) continue;
177670    iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
177671    pLeaf = fts5DataRead(p, iRow);
177672    if( pLeaf==0 ) break;
177673
177674    /* Check that the leaf contains at least one term, and that it is equal
177675    ** to or larger than the split-key in zIdxTerm.  Also check that if there
177676    ** is also a rowid pointer within the leaf page header, it points to a
177677    ** location before the term.  */
177678    if( pLeaf->nn<=pLeaf->szLeaf ){
177679      p->rc = FTS5_CORRUPT;
177680    }else{
177681      int iOff;                   /* Offset of first term on leaf */
177682      int iRowidOff;              /* Offset of first rowid on leaf */
177683      int nTerm;                  /* Size of term on leaf in bytes */
177684      int res;                    /* Comparison of term and split-key */
177685
177686      iOff = fts5LeafFirstTermOff(pLeaf);
177687      iRowidOff = fts5LeafFirstRowidOff(pLeaf);
177688      if( iRowidOff>=iOff ){
177689        p->rc = FTS5_CORRUPT;
177690      }else{
177691        iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
177692        res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
177693        if( res==0 ) res = nTerm - nIdxTerm;
177694        if( res<0 ) p->rc = FTS5_CORRUPT;
177695      }
177696
177697      fts5IntegrityCheckPgidx(p, pLeaf);
177698    }
177699    fts5DataRelease(pLeaf);
177700    if( p->rc ) break;
177701
177702
177703    /* Now check that the iter.nEmpty leaves following the current leaf
177704    ** (a) exist and (b) contain no terms. */
177705    fts5IndexIntegrityCheckEmpty(
177706        p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
177707    );
177708    if( p->rc ) break;
177709
177710    /* If there is a doclist-index, check that it looks right. */
177711    if( bIdxDlidx ){
177712      Fts5DlidxIter *pDlidx = 0;  /* For iterating through doclist index */
177713      int iPrevLeaf = iIdxLeaf;
177714      int iSegid = pSeg->iSegid;
177715      int iPg = 0;
177716      i64 iKey;
177717
177718      for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
177719          fts5DlidxIterEof(p, pDlidx)==0;
177720          fts5DlidxIterNext(p, pDlidx)
177721      ){
177722
177723        /* Check any rowid-less pages that occur before the current leaf. */
177724        for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
177725          iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
177726          pLeaf = fts5DataRead(p, iKey);
177727          if( pLeaf ){
177728            if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
177729            fts5DataRelease(pLeaf);
177730          }
177731        }
177732        iPrevLeaf = fts5DlidxIterPgno(pDlidx);
177733
177734        /* Check that the leaf page indicated by the iterator really does
177735        ** contain the rowid suggested by the same. */
177736        iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
177737        pLeaf = fts5DataRead(p, iKey);
177738        if( pLeaf ){
177739          i64 iRowid;
177740          int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
177741          ASSERT_SZLEAF_OK(pLeaf);
177742          if( iRowidOff>=pLeaf->szLeaf ){
177743            p->rc = FTS5_CORRUPT;
177744          }else{
177745            fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
177746            if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
177747          }
177748          fts5DataRelease(pLeaf);
177749        }
177750      }
177751
177752      iDlidxPrevLeaf = iPg;
177753      fts5DlidxIterFree(pDlidx);
177754      fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
177755    }else{
177756      iDlidxPrevLeaf = pSeg->pgnoLast;
177757      /* TODO: Check there is no doclist index */
177758    }
177759
177760    iIdxPrevLeaf = iIdxLeaf;
177761  }
177762
177763  rc2 = sqlite3_finalize(pStmt);
177764  if( p->rc==SQLITE_OK ) p->rc = rc2;
177765
177766  /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
177767#if 0
177768  if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
177769    p->rc = FTS5_CORRUPT;
177770  }
177771#endif
177772}
177773
177774
177775/*
177776** Run internal checks to ensure that the FTS index (a) is internally
177777** consistent and (b) contains entries for which the XOR of the checksums
177778** as calculated by fts5IndexEntryCksum() is cksum.
177779**
177780** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
177781** checksum does not match. Return SQLITE_OK if all checks pass without
177782** error, or some other SQLite error code if another error (e.g. OOM)
177783** occurs.
177784*/
177785static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
177786  u64 cksum2 = 0;                 /* Checksum based on contents of indexes */
177787  Fts5Buffer poslist = {0,0,0};   /* Buffer used to hold a poslist */
177788  Fts5IndexIter *pIter;           /* Used to iterate through entire index */
177789  Fts5Structure *pStruct;         /* Index structure */
177790
177791  /* Used by extra internal tests only run if NDEBUG is not defined */
177792  u64 cksum3 = 0;                 /* Checksum based on contents of indexes */
177793  Fts5Buffer term = {0,0,0};      /* Buffer used to hold most recent term */
177794
177795  /* Load the FTS index structure */
177796  pStruct = fts5StructureRead(p);
177797
177798  /* Check that the internal nodes of each segment match the leaves */
177799  if( pStruct ){
177800    int iLvl, iSeg;
177801    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
177802      for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
177803        Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
177804        fts5IndexIntegrityCheckSegment(p, pSeg);
177805      }
177806    }
177807  }
177808
177809  /* The cksum argument passed to this function is a checksum calculated
177810  ** based on all expected entries in the FTS index (including prefix index
177811  ** entries). This block checks that a checksum calculated based on the
177812  ** actual contents of FTS index is identical.
177813  **
177814  ** Two versions of the same checksum are calculated. The first (stack
177815  ** variable cksum2) based on entries extracted from the full-text index
177816  ** while doing a linear scan of each individual index in turn.
177817  **
177818  ** As each term visited by the linear scans, a separate query for the
177819  ** same term is performed. cksum3 is calculated based on the entries
177820  ** extracted by these queries.
177821  */
177822  for(fts5MultiIterNew(p, pStruct, 0, 0, 0, 0, -1, 0, &pIter);
177823      fts5MultiIterEof(p, pIter)==0;
177824      fts5MultiIterNext(p, pIter, 0, 0)
177825  ){
177826    int n;                      /* Size of term in bytes */
177827    i64 iPos = 0;               /* Position read from poslist */
177828    int iOff = 0;               /* Offset within poslist */
177829    i64 iRowid = fts5MultiIterRowid(pIter);
177830    char *z = (char*)fts5MultiIterTerm(pIter, &n);
177831
177832    /* If this is a new term, query for it. Update cksum3 with the results. */
177833    fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
177834
177835    poslist.n = 0;
177836    fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst] , 0, &poslist);
177837    while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
177838      int iCol = FTS5_POS2COLUMN(iPos);
177839      int iTokOff = FTS5_POS2OFFSET(iPos);
177840      cksum2 ^= fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
177841    }
177842  }
177843  fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
177844
177845  fts5MultiIterFree(p, pIter);
177846  if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
177847
177848  fts5StructureRelease(pStruct);
177849  fts5BufferFree(&term);
177850  fts5BufferFree(&poslist);
177851  return fts5IndexReturn(p);
177852}
177853
177854
177855/*
177856** Calculate and return a checksum that is the XOR of the index entry
177857** checksum of all entries that would be generated by the token specified
177858** by the final 5 arguments.
177859*/
177860static u64 sqlite3Fts5IndexCksum(
177861  Fts5Config *pConfig,            /* Configuration object */
177862  i64 iRowid,                     /* Document term appears in */
177863  int iCol,                       /* Column term appears in */
177864  int iPos,                       /* Position term appears in */
177865  const char *pTerm, int nTerm    /* Term at iPos */
177866){
177867  u64 ret = 0;                    /* Return value */
177868  int iIdx;                       /* For iterating through indexes */
177869
177870  ret = fts5IndexEntryCksum(iRowid, iCol, iPos, 0, pTerm, nTerm);
177871
177872  for(iIdx=0; iIdx<pConfig->nPrefix; iIdx++){
177873    int nByte = fts5IndexCharlenToBytelen(pTerm, nTerm, pConfig->aPrefix[iIdx]);
177874    if( nByte ){
177875      ret ^= fts5IndexEntryCksum(iRowid, iCol, iPos, iIdx+1, pTerm, nByte);
177876    }
177877  }
177878
177879  return ret;
177880}
177881
177882/*************************************************************************
177883**************************************************************************
177884** Below this point is the implementation of the fts5_decode() scalar
177885** function only.
177886*/
177887
177888/*
177889** Decode a segment-data rowid from the %_data table. This function is
177890** the opposite of macro FTS5_SEGMENT_ROWID().
177891*/
177892static void fts5DecodeRowid(
177893  i64 iRowid,                     /* Rowid from %_data table */
177894  int *piSegid,                   /* OUT: Segment id */
177895  int *pbDlidx,                   /* OUT: Dlidx flag */
177896  int *piHeight,                  /* OUT: Height */
177897  int *piPgno                     /* OUT: Page number */
177898){
177899  *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
177900  iRowid >>= FTS5_DATA_PAGE_B;
177901
177902  *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
177903  iRowid >>= FTS5_DATA_HEIGHT_B;
177904
177905  *pbDlidx = (int)(iRowid & 0x0001);
177906  iRowid >>= FTS5_DATA_DLI_B;
177907
177908  *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
177909}
177910
177911static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
177912  int iSegid, iHeight, iPgno, bDlidx;       /* Rowid compenents */
177913  fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
177914
177915  if( iSegid==0 ){
177916    if( iKey==FTS5_AVERAGES_ROWID ){
177917      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
177918    }else{
177919      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
177920    }
177921  }
177922  else{
177923    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
177924        bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
177925    );
177926  }
177927}
177928
177929static void fts5DebugStructure(
177930  int *pRc,                       /* IN/OUT: error code */
177931  Fts5Buffer *pBuf,
177932  Fts5Structure *p
177933){
177934  int iLvl, iSeg;                 /* Iterate through levels, segments */
177935
177936  for(iLvl=0; iLvl<p->nLevel; iLvl++){
177937    Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
177938    sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
177939        " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
177940    );
177941    for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
177942      Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
177943      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
177944          pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
177945      );
177946    }
177947    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
177948  }
177949}
177950
177951/*
177952** This is part of the fts5_decode() debugging aid.
177953**
177954** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
177955** function appends a human-readable representation of the same object
177956** to the buffer passed as the second argument.
177957*/
177958static void fts5DecodeStructure(
177959  int *pRc,                       /* IN/OUT: error code */
177960  Fts5Buffer *pBuf,
177961  const u8 *pBlob, int nBlob
177962){
177963  int rc;                         /* Return code */
177964  Fts5Structure *p = 0;           /* Decoded structure object */
177965
177966  rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
177967  if( rc!=SQLITE_OK ){
177968    *pRc = rc;
177969    return;
177970  }
177971
177972  fts5DebugStructure(pRc, pBuf, p);
177973  fts5StructureRelease(p);
177974}
177975
177976/*
177977** This is part of the fts5_decode() debugging aid.
177978**
177979** Arguments pBlob/nBlob contain an "averages" record. This function
177980** appends a human-readable representation of record to the buffer passed
177981** as the second argument.
177982*/
177983static void fts5DecodeAverages(
177984  int *pRc,                       /* IN/OUT: error code */
177985  Fts5Buffer *pBuf,
177986  const u8 *pBlob, int nBlob
177987){
177988  int i = 0;
177989  const char *zSpace = "";
177990
177991  while( i<nBlob ){
177992    u64 iVal;
177993    i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
177994    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
177995    zSpace = " ";
177996  }
177997}
177998
177999/*
178000** Buffer (a/n) is assumed to contain a list of serialized varints. Read
178001** each varint and append its string representation to buffer pBuf. Return
178002** after either the input buffer is exhausted or a 0 value is read.
178003**
178004** The return value is the number of bytes read from the input buffer.
178005*/
178006static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
178007  int iOff = 0;
178008  while( iOff<n ){
178009    int iVal;
178010    iOff += fts5GetVarint32(&a[iOff], iVal);
178011    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
178012  }
178013  return iOff;
178014}
178015
178016/*
178017** The start of buffer (a/n) contains the start of a doclist. The doclist
178018** may or may not finish within the buffer. This function appends a text
178019** representation of the part of the doclist that is present to buffer
178020** pBuf.
178021**
178022** The return value is the number of bytes read from the input buffer.
178023*/
178024static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
178025  i64 iDocid = 0;
178026  int iOff = 0;
178027
178028  if( n>0 ){
178029    iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
178030    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
178031  }
178032  while( iOff<n ){
178033    int nPos;
178034    int bDummy;
178035    iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDummy);
178036    iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
178037    if( iOff<n ){
178038      i64 iDelta;
178039      iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
178040      iDocid += iDelta;
178041      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
178042    }
178043  }
178044
178045  return iOff;
178046}
178047
178048/*
178049** The implementation of user-defined scalar function fts5_decode().
178050*/
178051static void fts5DecodeFunction(
178052  sqlite3_context *pCtx,          /* Function call context */
178053  int nArg,                       /* Number of args (always 2) */
178054  sqlite3_value **apVal           /* Function arguments */
178055){
178056  i64 iRowid;                     /* Rowid for record being decoded */
178057  int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
178058  const u8 *aBlob; int n;         /* Record to decode */
178059  u8 *a = 0;
178060  Fts5Buffer s;                   /* Build up text to return here */
178061  int rc = SQLITE_OK;             /* Return code */
178062  int nSpace = 0;
178063
178064  assert( nArg==2 );
178065  memset(&s, 0, sizeof(Fts5Buffer));
178066  iRowid = sqlite3_value_int64(apVal[0]);
178067
178068  /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
178069  ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
178070  ** buffer overreads even if the record is corrupt.  */
178071  n = sqlite3_value_bytes(apVal[1]);
178072  aBlob = sqlite3_value_blob(apVal[1]);
178073  nSpace = n + FTS5_DATA_ZERO_PADDING;
178074  a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
178075  if( a==0 ) goto decode_out;
178076  memcpy(a, aBlob, n);
178077
178078
178079  fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
178080
178081  fts5DebugRowid(&rc, &s, iRowid);
178082  if( bDlidx ){
178083    Fts5Data dlidx;
178084    Fts5DlidxLvl lvl;
178085
178086    dlidx.p = a;
178087    dlidx.nn = n;
178088
178089    memset(&lvl, 0, sizeof(Fts5DlidxLvl));
178090    lvl.pData = &dlidx;
178091    lvl.iLeafPgno = iPgno;
178092
178093    for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
178094      sqlite3Fts5BufferAppendPrintf(&rc, &s,
178095          " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
178096      );
178097    }
178098  }else if( iSegid==0 ){
178099    if( iRowid==FTS5_AVERAGES_ROWID ){
178100      fts5DecodeAverages(&rc, &s, a, n);
178101    }else{
178102      fts5DecodeStructure(&rc, &s, a, n);
178103    }
178104  }else{
178105    Fts5Buffer term;              /* Current term read from page */
178106    int szLeaf;                   /* Offset of pgidx in a[] */
178107    int iPgidxOff;
178108    int iPgidxPrev = 0;           /* Previous value read from pgidx */
178109    int iTermOff = 0;
178110    int iRowidOff = 0;
178111    int iOff;
178112    int nDoclist;
178113
178114    memset(&term, 0, sizeof(Fts5Buffer));
178115
178116    if( n<4 ){
178117      sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
178118      goto decode_out;
178119    }else{
178120      iRowidOff = fts5GetU16(&a[0]);
178121      iPgidxOff = szLeaf = fts5GetU16(&a[2]);
178122      if( iPgidxOff<n ){
178123        fts5GetVarint32(&a[iPgidxOff], iTermOff);
178124      }
178125    }
178126
178127    /* Decode the position list tail at the start of the page */
178128    if( iRowidOff!=0 ){
178129      iOff = iRowidOff;
178130    }else if( iTermOff!=0 ){
178131      iOff = iTermOff;
178132    }else{
178133      iOff = szLeaf;
178134    }
178135    fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
178136
178137    /* Decode any more doclist data that appears on the page before the
178138    ** first term. */
178139    nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
178140    fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
178141
178142    while( iPgidxOff<n ){
178143      int bFirst = (iPgidxOff==szLeaf);     /* True for first term on page */
178144      int nByte;                            /* Bytes of data */
178145      int iEnd;
178146
178147      iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
178148      iPgidxPrev += nByte;
178149      iOff = iPgidxPrev;
178150
178151      if( iPgidxOff<n ){
178152        fts5GetVarint32(&a[iPgidxOff], nByte);
178153        iEnd = iPgidxPrev + nByte;
178154      }else{
178155        iEnd = szLeaf;
178156      }
178157
178158      if( bFirst==0 ){
178159        iOff += fts5GetVarint32(&a[iOff], nByte);
178160        term.n = nByte;
178161      }
178162      iOff += fts5GetVarint32(&a[iOff], nByte);
178163      fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
178164      iOff += nByte;
178165
178166      sqlite3Fts5BufferAppendPrintf(
178167          &rc, &s, " term=%.*s", term.n, (const char*)term.p
178168      );
178169      iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
178170    }
178171
178172    fts5BufferFree(&term);
178173  }
178174
178175 decode_out:
178176  sqlite3_free(a);
178177  if( rc==SQLITE_OK ){
178178    sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
178179  }else{
178180    sqlite3_result_error_code(pCtx, rc);
178181  }
178182  fts5BufferFree(&s);
178183}
178184
178185/*
178186** The implementation of user-defined scalar function fts5_rowid().
178187*/
178188static void fts5RowidFunction(
178189  sqlite3_context *pCtx,          /* Function call context */
178190  int nArg,                       /* Number of args (always 2) */
178191  sqlite3_value **apVal           /* Function arguments */
178192){
178193  const char *zArg;
178194  if( nArg==0 ){
178195    sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
178196  }else{
178197    zArg = (const char*)sqlite3_value_text(apVal[0]);
178198    if( 0==sqlite3_stricmp(zArg, "segment") ){
178199      i64 iRowid;
178200      int segid, pgno;
178201      if( nArg!=3 ){
178202        sqlite3_result_error(pCtx,
178203            "should be: fts5_rowid('segment', segid, pgno))", -1
178204        );
178205      }else{
178206        segid = sqlite3_value_int(apVal[1]);
178207        pgno = sqlite3_value_int(apVal[2]);
178208        iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
178209        sqlite3_result_int64(pCtx, iRowid);
178210      }
178211    }else{
178212      sqlite3_result_error(pCtx,
178213        "first arg to fts5_rowid() must be 'segment'" , -1
178214      );
178215    }
178216  }
178217}
178218
178219/*
178220** This is called as part of registering the FTS5 module with database
178221** connection db. It registers several user-defined scalar functions useful
178222** with FTS5.
178223**
178224** If successful, SQLITE_OK is returned. If an error occurs, some other
178225** SQLite error code is returned instead.
178226*/
178227static int sqlite3Fts5IndexInit(sqlite3 *db){
178228  int rc = sqlite3_create_function(
178229      db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
178230  );
178231  if( rc==SQLITE_OK ){
178232    rc = sqlite3_create_function(
178233        db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
178234    );
178235  }
178236  return rc;
178237}
178238
178239
178240/*
178241** 2014 Jun 09
178242**
178243** The author disclaims copyright to this source code.  In place of
178244** a legal notice, here is a blessing:
178245**
178246**    May you do good and not evil.
178247**    May you find forgiveness for yourself and forgive others.
178248**    May you share freely, never taking more than you give.
178249**
178250******************************************************************************
178251**
178252** This is an SQLite module implementing full-text search.
178253*/
178254
178255
178256
178257/*
178258** This variable is set to false when running tests for which the on disk
178259** structures should not be corrupt. Otherwise, true. If it is false, extra
178260** assert() conditions in the fts5 code are activated - conditions that are
178261** only true if it is guaranteed that the fts5 database is not corrupt.
178262*/
178263SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
178264
178265
178266typedef struct Fts5Auxdata Fts5Auxdata;
178267typedef struct Fts5Auxiliary Fts5Auxiliary;
178268typedef struct Fts5Cursor Fts5Cursor;
178269typedef struct Fts5Sorter Fts5Sorter;
178270typedef struct Fts5Table Fts5Table;
178271typedef struct Fts5TokenizerModule Fts5TokenizerModule;
178272
178273/*
178274** NOTES ON TRANSACTIONS:
178275**
178276** SQLite invokes the following virtual table methods as transactions are
178277** opened and closed by the user:
178278**
178279**     xBegin():    Start of a new transaction.
178280**     xSync():     Initial part of two-phase commit.
178281**     xCommit():   Final part of two-phase commit.
178282**     xRollback(): Rollback the transaction.
178283**
178284** Anything that is required as part of a commit that may fail is performed
178285** in the xSync() callback. Current versions of SQLite ignore any errors
178286** returned by xCommit().
178287**
178288** And as sub-transactions are opened/closed:
178289**
178290**     xSavepoint(int S):  Open savepoint S.
178291**     xRelease(int S):    Commit and close savepoint S.
178292**     xRollbackTo(int S): Rollback to start of savepoint S.
178293**
178294** During a write-transaction the fts5_index.c module may cache some data
178295** in-memory. It is flushed to disk whenever xSync(), xRelease() or
178296** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
178297** is called.
178298**
178299** Additionally, if SQLITE_DEBUG is defined, an instance of the following
178300** structure is used to record the current transaction state. This information
178301** is not required, but it is used in the assert() statements executed by
178302** function fts5CheckTransactionState() (see below).
178303*/
178304struct Fts5TransactionState {
178305  int eState;                     /* 0==closed, 1==open, 2==synced */
178306  int iSavepoint;                 /* Number of open savepoints (0 -> none) */
178307};
178308
178309/*
178310** A single object of this type is allocated when the FTS5 module is
178311** registered with a database handle. It is used to store pointers to
178312** all registered FTS5 extensions - tokenizers and auxiliary functions.
178313*/
178314struct Fts5Global {
178315  fts5_api api;                   /* User visible part of object (see fts5.h) */
178316  sqlite3 *db;                    /* Associated database connection */
178317  i64 iNextId;                    /* Used to allocate unique cursor ids */
178318  Fts5Auxiliary *pAux;            /* First in list of all aux. functions */
178319  Fts5TokenizerModule *pTok;      /* First in list of all tokenizer modules */
178320  Fts5TokenizerModule *pDfltTok;  /* Default tokenizer module */
178321  Fts5Cursor *pCsr;               /* First in list of all open cursors */
178322};
178323
178324/*
178325** Each auxiliary function registered with the FTS5 module is represented
178326** by an object of the following type. All such objects are stored as part
178327** of the Fts5Global.pAux list.
178328*/
178329struct Fts5Auxiliary {
178330  Fts5Global *pGlobal;            /* Global context for this function */
178331  char *zFunc;                    /* Function name (nul-terminated) */
178332  void *pUserData;                /* User-data pointer */
178333  fts5_extension_function xFunc;  /* Callback function */
178334  void (*xDestroy)(void*);        /* Destructor function */
178335  Fts5Auxiliary *pNext;           /* Next registered auxiliary function */
178336};
178337
178338/*
178339** Each tokenizer module registered with the FTS5 module is represented
178340** by an object of the following type. All such objects are stored as part
178341** of the Fts5Global.pTok list.
178342*/
178343struct Fts5TokenizerModule {
178344  char *zName;                    /* Name of tokenizer */
178345  void *pUserData;                /* User pointer passed to xCreate() */
178346  fts5_tokenizer x;               /* Tokenizer functions */
178347  void (*xDestroy)(void*);        /* Destructor function */
178348  Fts5TokenizerModule *pNext;     /* Next registered tokenizer module */
178349};
178350
178351/*
178352** Virtual-table object.
178353*/
178354struct Fts5Table {
178355  sqlite3_vtab base;              /* Base class used by SQLite core */
178356  Fts5Config *pConfig;            /* Virtual table configuration */
178357  Fts5Index *pIndex;              /* Full-text index */
178358  Fts5Storage *pStorage;          /* Document store */
178359  Fts5Global *pGlobal;            /* Global (connection wide) data */
178360  Fts5Cursor *pSortCsr;           /* Sort data from this cursor */
178361#ifdef SQLITE_DEBUG
178362  struct Fts5TransactionState ts;
178363#endif
178364};
178365
178366struct Fts5MatchPhrase {
178367  Fts5Buffer *pPoslist;           /* Pointer to current poslist */
178368  int nTerm;                      /* Size of phrase in terms */
178369};
178370
178371/*
178372** pStmt:
178373**   SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
178374**
178375** aIdx[]:
178376**   There is one entry in the aIdx[] array for each phrase in the query,
178377**   the value of which is the offset within aPoslist[] following the last
178378**   byte of the position list for the corresponding phrase.
178379*/
178380struct Fts5Sorter {
178381  sqlite3_stmt *pStmt;
178382  i64 iRowid;                     /* Current rowid */
178383  const u8 *aPoslist;             /* Position lists for current row */
178384  int nIdx;                       /* Number of entries in aIdx[] */
178385  int aIdx[1];                    /* Offsets into aPoslist for current row */
178386};
178387
178388
178389/*
178390** Virtual-table cursor object.
178391**
178392** iSpecial:
178393**   If this is a 'special' query (refer to function fts5SpecialMatch()),
178394**   then this variable contains the result of the query.
178395**
178396** iFirstRowid, iLastRowid:
178397**   These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
178398**   cursor iterates in ascending order of rowids, iFirstRowid is the lower
178399**   limit of rowids to return, and iLastRowid the upper. In other words, the
178400**   WHERE clause in the user's query might have been:
178401**
178402**       <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
178403**
178404**   If the cursor iterates in descending order of rowid, iFirstRowid
178405**   is the upper limit (i.e. the "first" rowid visited) and iLastRowid
178406**   the lower.
178407*/
178408struct Fts5Cursor {
178409  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
178410  Fts5Cursor *pNext;              /* Next cursor in Fts5Cursor.pCsr list */
178411  int *aColumnSize;               /* Values for xColumnSize() */
178412  i64 iCsrId;                     /* Cursor id */
178413
178414  /* Zero from this point onwards on cursor reset */
178415  int ePlan;                      /* FTS5_PLAN_XXX value */
178416  int bDesc;                      /* True for "ORDER BY rowid DESC" queries */
178417  i64 iFirstRowid;                /* Return no rowids earlier than this */
178418  i64 iLastRowid;                 /* Return no rowids later than this */
178419  sqlite3_stmt *pStmt;            /* Statement used to read %_content */
178420  Fts5Expr *pExpr;                /* Expression for MATCH queries */
178421  Fts5Sorter *pSorter;            /* Sorter for "ORDER BY rank" queries */
178422  int csrflags;                   /* Mask of cursor flags (see below) */
178423  i64 iSpecial;                   /* Result of special query */
178424
178425  /* "rank" function. Populated on demand from vtab.xColumn(). */
178426  char *zRank;                    /* Custom rank function */
178427  char *zRankArgs;                /* Custom rank function args */
178428  Fts5Auxiliary *pRank;           /* Rank callback (or NULL) */
178429  int nRankArg;                   /* Number of trailing arguments for rank() */
178430  sqlite3_value **apRankArg;      /* Array of trailing arguments */
178431  sqlite3_stmt *pRankArgStmt;     /* Origin of objects in apRankArg[] */
178432
178433  /* Auxiliary data storage */
178434  Fts5Auxiliary *pAux;            /* Currently executing extension function */
178435  Fts5Auxdata *pAuxdata;          /* First in linked list of saved aux-data */
178436
178437  /* Cache used by auxiliary functions xInst() and xInstCount() */
178438  Fts5PoslistReader *aInstIter;   /* One for each phrase */
178439  int nInstAlloc;                 /* Size of aInst[] array (entries / 3) */
178440  int nInstCount;                 /* Number of phrase instances */
178441  int *aInst;                     /* 3 integers per phrase instance */
178442};
178443
178444/*
178445** Bits that make up the "idxNum" parameter passed indirectly by
178446** xBestIndex() to xFilter().
178447*/
178448#define FTS5_BI_MATCH        0x0001         /* <tbl> MATCH ? */
178449#define FTS5_BI_RANK         0x0002         /* rank MATCH ? */
178450#define FTS5_BI_ROWID_EQ     0x0004         /* rowid == ? */
178451#define FTS5_BI_ROWID_LE     0x0008         /* rowid <= ? */
178452#define FTS5_BI_ROWID_GE     0x0010         /* rowid >= ? */
178453
178454#define FTS5_BI_ORDER_RANK   0x0020
178455#define FTS5_BI_ORDER_ROWID  0x0040
178456#define FTS5_BI_ORDER_DESC   0x0080
178457
178458/*
178459** Values for Fts5Cursor.csrflags
178460*/
178461#define FTS5CSR_REQUIRE_CONTENT   0x01
178462#define FTS5CSR_REQUIRE_DOCSIZE   0x02
178463#define FTS5CSR_REQUIRE_INST      0x04
178464#define FTS5CSR_EOF               0x08
178465#define FTS5CSR_FREE_ZRANK        0x10
178466#define FTS5CSR_REQUIRE_RESEEK    0x20
178467
178468#define BitFlagAllTest(x,y) (((x) & (y))==(y))
178469#define BitFlagTest(x,y)    (((x) & (y))!=0)
178470
178471
178472/*
178473** Macros to Set(), Clear() and Test() cursor flags.
178474*/
178475#define CsrFlagSet(pCsr, flag)   ((pCsr)->csrflags |= (flag))
178476#define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
178477#define CsrFlagTest(pCsr, flag)  ((pCsr)->csrflags & (flag))
178478
178479struct Fts5Auxdata {
178480  Fts5Auxiliary *pAux;            /* Extension to which this belongs */
178481  void *pPtr;                     /* Pointer value */
178482  void(*xDelete)(void*);          /* Destructor */
178483  Fts5Auxdata *pNext;             /* Next object in linked list */
178484};
178485
178486#ifdef SQLITE_DEBUG
178487#define FTS5_BEGIN      1
178488#define FTS5_SYNC       2
178489#define FTS5_COMMIT     3
178490#define FTS5_ROLLBACK   4
178491#define FTS5_SAVEPOINT  5
178492#define FTS5_RELEASE    6
178493#define FTS5_ROLLBACKTO 7
178494static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
178495  switch( op ){
178496    case FTS5_BEGIN:
178497      assert( p->ts.eState==0 );
178498      p->ts.eState = 1;
178499      p->ts.iSavepoint = -1;
178500      break;
178501
178502    case FTS5_SYNC:
178503      assert( p->ts.eState==1 );
178504      p->ts.eState = 2;
178505      break;
178506
178507    case FTS5_COMMIT:
178508      assert( p->ts.eState==2 );
178509      p->ts.eState = 0;
178510      break;
178511
178512    case FTS5_ROLLBACK:
178513      assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
178514      p->ts.eState = 0;
178515      break;
178516
178517    case FTS5_SAVEPOINT:
178518      assert( p->ts.eState==1 );
178519      assert( iSavepoint>=0 );
178520      assert( iSavepoint>p->ts.iSavepoint );
178521      p->ts.iSavepoint = iSavepoint;
178522      break;
178523
178524    case FTS5_RELEASE:
178525      assert( p->ts.eState==1 );
178526      assert( iSavepoint>=0 );
178527      assert( iSavepoint<=p->ts.iSavepoint );
178528      p->ts.iSavepoint = iSavepoint-1;
178529      break;
178530
178531    case FTS5_ROLLBACKTO:
178532      assert( p->ts.eState==1 );
178533      assert( iSavepoint>=0 );
178534      assert( iSavepoint<=p->ts.iSavepoint );
178535      p->ts.iSavepoint = iSavepoint;
178536      break;
178537  }
178538}
178539#else
178540# define fts5CheckTransactionState(x,y,z)
178541#endif
178542
178543/*
178544** Return true if pTab is a contentless table.
178545*/
178546static int fts5IsContentless(Fts5Table *pTab){
178547  return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
178548}
178549
178550/*
178551** Delete a virtual table handle allocated by fts5InitVtab().
178552*/
178553static void fts5FreeVtab(Fts5Table *pTab){
178554  if( pTab ){
178555    sqlite3Fts5IndexClose(pTab->pIndex);
178556    sqlite3Fts5StorageClose(pTab->pStorage);
178557    sqlite3Fts5ConfigFree(pTab->pConfig);
178558    sqlite3_free(pTab);
178559  }
178560}
178561
178562/*
178563** The xDisconnect() virtual table method.
178564*/
178565static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
178566  fts5FreeVtab((Fts5Table*)pVtab);
178567  return SQLITE_OK;
178568}
178569
178570/*
178571** The xDestroy() virtual table method.
178572*/
178573static int fts5DestroyMethod(sqlite3_vtab *pVtab){
178574  Fts5Table *pTab = (Fts5Table*)pVtab;
178575  int rc = sqlite3Fts5DropAll(pTab->pConfig);
178576  if( rc==SQLITE_OK ){
178577    fts5FreeVtab((Fts5Table*)pVtab);
178578  }
178579  return rc;
178580}
178581
178582/*
178583** This function is the implementation of both the xConnect and xCreate
178584** methods of the FTS3 virtual table.
178585**
178586** The argv[] array contains the following:
178587**
178588**   argv[0]   -> module name  ("fts5")
178589**   argv[1]   -> database name
178590**   argv[2]   -> table name
178591**   argv[...] -> "column name" and other module argument fields.
178592*/
178593static int fts5InitVtab(
178594  int bCreate,                    /* True for xCreate, false for xConnect */
178595  sqlite3 *db,                    /* The SQLite database connection */
178596  void *pAux,                     /* Hash table containing tokenizers */
178597  int argc,                       /* Number of elements in argv array */
178598  const char * const *argv,       /* xCreate/xConnect argument array */
178599  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
178600  char **pzErr                    /* Write any error message here */
178601){
178602  Fts5Global *pGlobal = (Fts5Global*)pAux;
178603  const char **azConfig = (const char**)argv;
178604  int rc = SQLITE_OK;             /* Return code */
178605  Fts5Config *pConfig = 0;        /* Results of parsing argc/argv */
178606  Fts5Table *pTab = 0;            /* New virtual table object */
178607
178608  /* Allocate the new vtab object and parse the configuration */
178609  pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
178610  if( rc==SQLITE_OK ){
178611    rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
178612    assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
178613  }
178614  if( rc==SQLITE_OK ){
178615    pTab->pConfig = pConfig;
178616    pTab->pGlobal = pGlobal;
178617  }
178618
178619  /* Open the index sub-system */
178620  if( rc==SQLITE_OK ){
178621    rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
178622  }
178623
178624  /* Open the storage sub-system */
178625  if( rc==SQLITE_OK ){
178626    rc = sqlite3Fts5StorageOpen(
178627        pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
178628    );
178629  }
178630
178631  /* Call sqlite3_declare_vtab() */
178632  if( rc==SQLITE_OK ){
178633    rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
178634  }
178635
178636  if( rc!=SQLITE_OK ){
178637    fts5FreeVtab(pTab);
178638    pTab = 0;
178639  }else if( bCreate ){
178640    fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
178641  }
178642  *ppVTab = (sqlite3_vtab*)pTab;
178643  return rc;
178644}
178645
178646/*
178647** The xConnect() and xCreate() methods for the virtual table. All the
178648** work is done in function fts5InitVtab().
178649*/
178650static int fts5ConnectMethod(
178651  sqlite3 *db,                    /* Database connection */
178652  void *pAux,                     /* Pointer to tokenizer hash table */
178653  int argc,                       /* Number of elements in argv array */
178654  const char * const *argv,       /* xCreate/xConnect argument array */
178655  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
178656  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
178657){
178658  return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
178659}
178660static int fts5CreateMethod(
178661  sqlite3 *db,                    /* Database connection */
178662  void *pAux,                     /* Pointer to tokenizer hash table */
178663  int argc,                       /* Number of elements in argv array */
178664  const char * const *argv,       /* xCreate/xConnect argument array */
178665  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
178666  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
178667){
178668  return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
178669}
178670
178671/*
178672** The different query plans.
178673*/
178674#define FTS5_PLAN_MATCH          1       /* (<tbl> MATCH ?) */
178675#define FTS5_PLAN_SOURCE         2       /* A source cursor for SORTED_MATCH */
178676#define FTS5_PLAN_SPECIAL        3       /* An internal query */
178677#define FTS5_PLAN_SORTED_MATCH   4       /* (<tbl> MATCH ? ORDER BY rank) */
178678#define FTS5_PLAN_SCAN           5       /* No usable constraint */
178679#define FTS5_PLAN_ROWID          6       /* (rowid = ?) */
178680
178681/*
178682** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
178683** extension is currently being used by a version of SQLite too old to
178684** support index-info flags. In that case this function is a no-op.
178685*/
178686static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
178687#if SQLITE_VERSION_NUMBER>=3008012
178688  if( sqlite3_libversion_number()>=3008012 ){
178689    pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
178690  }
178691#endif
178692}
178693
178694/*
178695** Implementation of the xBestIndex method for FTS5 tables. Within the
178696** WHERE constraint, it searches for the following:
178697**
178698**   1. A MATCH constraint against the special column.
178699**   2. A MATCH constraint against the "rank" column.
178700**   3. An == constraint against the rowid column.
178701**   4. A < or <= constraint against the rowid column.
178702**   5. A > or >= constraint against the rowid column.
178703**
178704** Within the ORDER BY, either:
178705**
178706**   5. ORDER BY rank [ASC|DESC]
178707**   6. ORDER BY rowid [ASC|DESC]
178708**
178709** Costs are assigned as follows:
178710**
178711**  a) If an unusable MATCH operator is present in the WHERE clause, the
178712**     cost is unconditionally set to 1e50 (a really big number).
178713**
178714**  a) If a MATCH operator is present, the cost depends on the other
178715**     constraints also present. As follows:
178716**
178717**       * No other constraints:         cost=1000.0
178718**       * One rowid range constraint:   cost=750.0
178719**       * Both rowid range constraints: cost=500.0
178720**       * An == rowid constraint:       cost=100.0
178721**
178722**  b) Otherwise, if there is no MATCH:
178723**
178724**       * No other constraints:         cost=1000000.0
178725**       * One rowid range constraint:   cost=750000.0
178726**       * Both rowid range constraints: cost=250000.0
178727**       * An == rowid constraint:       cost=10.0
178728**
178729** Costs are not modified by the ORDER BY clause.
178730*/
178731static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
178732  Fts5Table *pTab = (Fts5Table*)pVTab;
178733  Fts5Config *pConfig = pTab->pConfig;
178734  int idxFlags = 0;               /* Parameter passed through to xFilter() */
178735  int bHasMatch;
178736  int iNext;
178737  int i;
178738
178739  struct Constraint {
178740    int op;                       /* Mask against sqlite3_index_constraint.op */
178741    int fts5op;                   /* FTS5 mask for idxFlags */
178742    int iCol;                     /* 0==rowid, 1==tbl, 2==rank */
178743    int omit;                     /* True to omit this if found */
178744    int iConsIndex;               /* Index in pInfo->aConstraint[] */
178745  } aConstraint[] = {
178746    {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
178747                                    FTS5_BI_MATCH,    1, 1, -1},
178748    {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
178749                                    FTS5_BI_RANK,     2, 1, -1},
178750    {SQLITE_INDEX_CONSTRAINT_EQ,    FTS5_BI_ROWID_EQ, 0, 0, -1},
178751    {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE,
178752                                    FTS5_BI_ROWID_LE, 0, 0, -1},
178753    {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE,
178754                                    FTS5_BI_ROWID_GE, 0, 0, -1},
178755  };
178756
178757  int aColMap[3];
178758  aColMap[0] = -1;
178759  aColMap[1] = pConfig->nCol;
178760  aColMap[2] = pConfig->nCol+1;
178761
178762  /* Set idxFlags flags for all WHERE clause terms that will be used. */
178763  for(i=0; i<pInfo->nConstraint; i++){
178764    struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
178765    int j;
178766    for(j=0; j<sizeof(aConstraint)/sizeof(aConstraint[0]); j++){
178767      struct Constraint *pC = &aConstraint[j];
178768      if( p->iColumn==aColMap[pC->iCol] && p->op & pC->op ){
178769        if( p->usable ){
178770          pC->iConsIndex = i;
178771          idxFlags |= pC->fts5op;
178772        }else if( j==0 ){
178773          /* As there exists an unusable MATCH constraint this is an
178774          ** unusable plan. Set a prohibitively high cost. */
178775          pInfo->estimatedCost = 1e50;
178776          return SQLITE_OK;
178777        }
178778      }
178779    }
178780  }
178781
178782  /* Set idxFlags flags for the ORDER BY clause */
178783  if( pInfo->nOrderBy==1 ){
178784    int iSort = pInfo->aOrderBy[0].iColumn;
178785    if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
178786      idxFlags |= FTS5_BI_ORDER_RANK;
178787    }else if( iSort==-1 ){
178788      idxFlags |= FTS5_BI_ORDER_ROWID;
178789    }
178790    if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
178791      pInfo->orderByConsumed = 1;
178792      if( pInfo->aOrderBy[0].desc ){
178793        idxFlags |= FTS5_BI_ORDER_DESC;
178794      }
178795    }
178796  }
178797
178798  /* Calculate the estimated cost based on the flags set in idxFlags. */
178799  bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
178800  if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
178801    pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
178802    if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
178803  }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
178804    pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
178805  }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
178806    pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
178807  }else{
178808    pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
178809  }
178810
178811  /* Assign argvIndex values to each constraint in use. */
178812  iNext = 1;
178813  for(i=0; i<sizeof(aConstraint)/sizeof(aConstraint[0]); i++){
178814    struct Constraint *pC = &aConstraint[i];
178815    if( pC->iConsIndex>=0 ){
178816      pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
178817      pInfo->aConstraintUsage[pC->iConsIndex].omit = pC->omit;
178818    }
178819  }
178820
178821  pInfo->idxNum = idxFlags;
178822  return SQLITE_OK;
178823}
178824
178825/*
178826** Implementation of xOpen method.
178827*/
178828static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
178829  Fts5Table *pTab = (Fts5Table*)pVTab;
178830  Fts5Config *pConfig = pTab->pConfig;
178831  Fts5Cursor *pCsr;               /* New cursor object */
178832  int nByte;                      /* Bytes of space to allocate */
178833  int rc = SQLITE_OK;             /* Return code */
178834
178835  nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
178836  pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
178837  if( pCsr ){
178838    Fts5Global *pGlobal = pTab->pGlobal;
178839    memset(pCsr, 0, nByte);
178840    pCsr->aColumnSize = (int*)&pCsr[1];
178841    pCsr->pNext = pGlobal->pCsr;
178842    pGlobal->pCsr = pCsr;
178843    pCsr->iCsrId = ++pGlobal->iNextId;
178844  }else{
178845    rc = SQLITE_NOMEM;
178846  }
178847  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
178848  return rc;
178849}
178850
178851static int fts5StmtType(Fts5Cursor *pCsr){
178852  if( pCsr->ePlan==FTS5_PLAN_SCAN ){
178853    return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
178854  }
178855  return FTS5_STMT_LOOKUP;
178856}
178857
178858/*
178859** This function is called after the cursor passed as the only argument
178860** is moved to point at a different row. It clears all cached data
178861** specific to the previous row stored by the cursor object.
178862*/
178863static void fts5CsrNewrow(Fts5Cursor *pCsr){
178864  CsrFlagSet(pCsr,
178865      FTS5CSR_REQUIRE_CONTENT
178866    | FTS5CSR_REQUIRE_DOCSIZE
178867    | FTS5CSR_REQUIRE_INST
178868  );
178869}
178870
178871static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
178872  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
178873  Fts5Auxdata *pData;
178874  Fts5Auxdata *pNext;
178875
178876  sqlite3_free(pCsr->aInstIter);
178877  sqlite3_free(pCsr->aInst);
178878  if( pCsr->pStmt ){
178879    int eStmt = fts5StmtType(pCsr);
178880    sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
178881  }
178882  if( pCsr->pSorter ){
178883    Fts5Sorter *pSorter = pCsr->pSorter;
178884    sqlite3_finalize(pSorter->pStmt);
178885    sqlite3_free(pSorter);
178886  }
178887
178888  if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
178889    sqlite3Fts5ExprFree(pCsr->pExpr);
178890  }
178891
178892  for(pData=pCsr->pAuxdata; pData; pData=pNext){
178893    pNext = pData->pNext;
178894    if( pData->xDelete ) pData->xDelete(pData->pPtr);
178895    sqlite3_free(pData);
178896  }
178897
178898  sqlite3_finalize(pCsr->pRankArgStmt);
178899  sqlite3_free(pCsr->apRankArg);
178900
178901  if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
178902    sqlite3_free(pCsr->zRank);
178903    sqlite3_free(pCsr->zRankArgs);
178904  }
178905
178906  memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
178907}
178908
178909
178910/*
178911** Close the cursor.  For additional information see the documentation
178912** on the xClose method of the virtual table interface.
178913*/
178914static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
178915  if( pCursor ){
178916    Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
178917    Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
178918    Fts5Cursor **pp;
178919
178920    fts5FreeCursorComponents(pCsr);
178921    /* Remove the cursor from the Fts5Global.pCsr list */
178922    for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
178923    *pp = pCsr->pNext;
178924
178925    sqlite3_free(pCsr);
178926  }
178927  return SQLITE_OK;
178928}
178929
178930static int fts5SorterNext(Fts5Cursor *pCsr){
178931  Fts5Sorter *pSorter = pCsr->pSorter;
178932  int rc;
178933
178934  rc = sqlite3_step(pSorter->pStmt);
178935  if( rc==SQLITE_DONE ){
178936    rc = SQLITE_OK;
178937    CsrFlagSet(pCsr, FTS5CSR_EOF);
178938  }else if( rc==SQLITE_ROW ){
178939    const u8 *a;
178940    const u8 *aBlob;
178941    int nBlob;
178942    int i;
178943    int iOff = 0;
178944    rc = SQLITE_OK;
178945
178946    pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
178947    nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
178948    aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
178949
178950    for(i=0; i<(pSorter->nIdx-1); i++){
178951      int iVal;
178952      a += fts5GetVarint32(a, iVal);
178953      iOff += iVal;
178954      pSorter->aIdx[i] = iOff;
178955    }
178956    pSorter->aIdx[i] = &aBlob[nBlob] - a;
178957
178958    pSorter->aPoslist = a;
178959    fts5CsrNewrow(pCsr);
178960  }
178961
178962  return rc;
178963}
178964
178965
178966/*
178967** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
178968** open on table pTab.
178969*/
178970static void fts5TripCursors(Fts5Table *pTab){
178971  Fts5Cursor *pCsr;
178972  for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
178973    if( pCsr->ePlan==FTS5_PLAN_MATCH
178974     && pCsr->base.pVtab==(sqlite3_vtab*)pTab
178975    ){
178976      CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
178977    }
178978  }
178979}
178980
178981/*
178982** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
178983** argument, close and reopen all Fts5IndexIter iterators that the cursor
178984** is using. Then attempt to move the cursor to a rowid equal to or laster
178985** (in the cursors sort order - ASC or DESC) than the current rowid.
178986**
178987** If the new rowid is not equal to the old, set output parameter *pbSkip
178988** to 1 before returning. Otherwise, leave it unchanged.
178989**
178990** Return SQLITE_OK if successful or if no reseek was required, or an
178991** error code if an error occurred.
178992*/
178993static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
178994  int rc = SQLITE_OK;
178995  assert( *pbSkip==0 );
178996  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
178997    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
178998    int bDesc = pCsr->bDesc;
178999    i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
179000
179001    rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
179002    if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
179003      *pbSkip = 1;
179004    }
179005
179006    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
179007    fts5CsrNewrow(pCsr);
179008    if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
179009      CsrFlagSet(pCsr, FTS5CSR_EOF);
179010    }
179011  }
179012  return rc;
179013}
179014
179015
179016/*
179017** Advance the cursor to the next row in the table that matches the
179018** search criteria.
179019**
179020** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
179021** even if we reach end-of-file.  The fts5EofMethod() will be called
179022** subsequently to determine whether or not an EOF was hit.
179023*/
179024static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
179025  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
179026  int rc = SQLITE_OK;
179027
179028  assert( (pCsr->ePlan<3)==
179029          (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
179030  );
179031
179032  if( pCsr->ePlan<3 ){
179033    int bSkip = 0;
179034    if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
179035    rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
179036    if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
179037      CsrFlagSet(pCsr, FTS5CSR_EOF);
179038    }
179039    fts5CsrNewrow(pCsr);
179040  }else{
179041    switch( pCsr->ePlan ){
179042      case FTS5_PLAN_SPECIAL: {
179043        CsrFlagSet(pCsr, FTS5CSR_EOF);
179044        break;
179045      }
179046
179047      case FTS5_PLAN_SORTED_MATCH: {
179048        rc = fts5SorterNext(pCsr);
179049        break;
179050      }
179051
179052      default:
179053        rc = sqlite3_step(pCsr->pStmt);
179054        if( rc!=SQLITE_ROW ){
179055          CsrFlagSet(pCsr, FTS5CSR_EOF);
179056          rc = sqlite3_reset(pCsr->pStmt);
179057        }else{
179058          rc = SQLITE_OK;
179059        }
179060        break;
179061    }
179062  }
179063
179064  return rc;
179065}
179066
179067static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
179068  Fts5Config *pConfig = pTab->pConfig;
179069  Fts5Sorter *pSorter;
179070  int nPhrase;
179071  int nByte;
179072  int rc = SQLITE_OK;
179073  char *zSql;
179074  const char *zRank = pCsr->zRank;
179075  const char *zRankArgs = pCsr->zRankArgs;
179076
179077  nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
179078  nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
179079  pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
179080  if( pSorter==0 ) return SQLITE_NOMEM;
179081  memset(pSorter, 0, nByte);
179082  pSorter->nIdx = nPhrase;
179083
179084  /* TODO: It would be better to have some system for reusing statement
179085  ** handles here, rather than preparing a new one for each query. But that
179086  ** is not possible as SQLite reference counts the virtual table objects.
179087  ** And since the statement required here reads from this very virtual
179088  ** table, saving it creates a circular reference.
179089  **
179090  ** If SQLite a built-in statement cache, this wouldn't be a problem. */
179091  zSql = sqlite3Fts5Mprintf(&rc,
179092      "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
179093      pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
179094      (zRankArgs ? ", " : ""),
179095      (zRankArgs ? zRankArgs : ""),
179096      bDesc ? "DESC" : "ASC"
179097  );
179098  if( zSql ){
179099    rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pSorter->pStmt, 0);
179100    sqlite3_free(zSql);
179101  }
179102
179103  pCsr->pSorter = pSorter;
179104  if( rc==SQLITE_OK ){
179105    assert( pTab->pSortCsr==0 );
179106    pTab->pSortCsr = pCsr;
179107    rc = fts5SorterNext(pCsr);
179108    pTab->pSortCsr = 0;
179109  }
179110
179111  if( rc!=SQLITE_OK ){
179112    sqlite3_finalize(pSorter->pStmt);
179113    sqlite3_free(pSorter);
179114    pCsr->pSorter = 0;
179115  }
179116
179117  return rc;
179118}
179119
179120static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
179121  int rc;
179122  Fts5Expr *pExpr = pCsr->pExpr;
179123  rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
179124  if( sqlite3Fts5ExprEof(pExpr) ){
179125    CsrFlagSet(pCsr, FTS5CSR_EOF);
179126  }
179127  fts5CsrNewrow(pCsr);
179128  return rc;
179129}
179130
179131/*
179132** Process a "special" query. A special query is identified as one with a
179133** MATCH expression that begins with a '*' character. The remainder of
179134** the text passed to the MATCH operator are used as  the special query
179135** parameters.
179136*/
179137static int fts5SpecialMatch(
179138  Fts5Table *pTab,
179139  Fts5Cursor *pCsr,
179140  const char *zQuery
179141){
179142  int rc = SQLITE_OK;             /* Return code */
179143  const char *z = zQuery;         /* Special query text */
179144  int n;                          /* Number of bytes in text at z */
179145
179146  while( z[0]==' ' ) z++;
179147  for(n=0; z[n] && z[n]!=' '; n++);
179148
179149  assert( pTab->base.zErrMsg==0 );
179150  pCsr->ePlan = FTS5_PLAN_SPECIAL;
179151
179152  if( 0==sqlite3_strnicmp("reads", z, n) ){
179153    pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
179154  }
179155  else if( 0==sqlite3_strnicmp("id", z, n) ){
179156    pCsr->iSpecial = pCsr->iCsrId;
179157  }
179158  else{
179159    /* An unrecognized directive. Return an error message. */
179160    pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
179161    rc = SQLITE_ERROR;
179162  }
179163
179164  return rc;
179165}
179166
179167/*
179168** Search for an auxiliary function named zName that can be used with table
179169** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
179170** structure. Otherwise, if no such function exists, return NULL.
179171*/
179172static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
179173  Fts5Auxiliary *pAux;
179174
179175  for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
179176    if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
179177  }
179178
179179  /* No function of the specified name was found. Return 0. */
179180  return 0;
179181}
179182
179183
179184static int fts5FindRankFunction(Fts5Cursor *pCsr){
179185  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
179186  Fts5Config *pConfig = pTab->pConfig;
179187  int rc = SQLITE_OK;
179188  Fts5Auxiliary *pAux = 0;
179189  const char *zRank = pCsr->zRank;
179190  const char *zRankArgs = pCsr->zRankArgs;
179191
179192  if( zRankArgs ){
179193    char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
179194    if( zSql ){
179195      sqlite3_stmt *pStmt = 0;
179196      rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pStmt, 0);
179197      sqlite3_free(zSql);
179198      assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
179199      if( rc==SQLITE_OK ){
179200        if( SQLITE_ROW==sqlite3_step(pStmt) ){
179201          int nByte;
179202          pCsr->nRankArg = sqlite3_column_count(pStmt);
179203          nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
179204          pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
179205          if( rc==SQLITE_OK ){
179206            int i;
179207            for(i=0; i<pCsr->nRankArg; i++){
179208              pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
179209            }
179210          }
179211          pCsr->pRankArgStmt = pStmt;
179212        }else{
179213          rc = sqlite3_finalize(pStmt);
179214          assert( rc!=SQLITE_OK );
179215        }
179216      }
179217    }
179218  }
179219
179220  if( rc==SQLITE_OK ){
179221    pAux = fts5FindAuxiliary(pTab, zRank);
179222    if( pAux==0 ){
179223      assert( pTab->base.zErrMsg==0 );
179224      pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
179225      rc = SQLITE_ERROR;
179226    }
179227  }
179228
179229  pCsr->pRank = pAux;
179230  return rc;
179231}
179232
179233
179234static int fts5CursorParseRank(
179235  Fts5Config *pConfig,
179236  Fts5Cursor *pCsr,
179237  sqlite3_value *pRank
179238){
179239  int rc = SQLITE_OK;
179240  if( pRank ){
179241    const char *z = (const char*)sqlite3_value_text(pRank);
179242    char *zRank = 0;
179243    char *zRankArgs = 0;
179244
179245    if( z==0 ){
179246      if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
179247    }else{
179248      rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
179249    }
179250    if( rc==SQLITE_OK ){
179251      pCsr->zRank = zRank;
179252      pCsr->zRankArgs = zRankArgs;
179253      CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
179254    }else if( rc==SQLITE_ERROR ){
179255      pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
179256          "parse error in rank function: %s", z
179257      );
179258    }
179259  }else{
179260    if( pConfig->zRank ){
179261      pCsr->zRank = (char*)pConfig->zRank;
179262      pCsr->zRankArgs = (char*)pConfig->zRankArgs;
179263    }else{
179264      pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
179265      pCsr->zRankArgs = 0;
179266    }
179267  }
179268  return rc;
179269}
179270
179271static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
179272  if( pVal ){
179273    int eType = sqlite3_value_numeric_type(pVal);
179274    if( eType==SQLITE_INTEGER ){
179275      return sqlite3_value_int64(pVal);
179276    }
179277  }
179278  return iDefault;
179279}
179280
179281/*
179282** This is the xFilter interface for the virtual table.  See
179283** the virtual table xFilter method documentation for additional
179284** information.
179285**
179286** There are three possible query strategies:
179287**
179288**   1. Full-text search using a MATCH operator.
179289**   2. A by-rowid lookup.
179290**   3. A full-table scan.
179291*/
179292static int fts5FilterMethod(
179293  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
179294  int idxNum,                     /* Strategy index */
179295  const char *idxStr,             /* Unused */
179296  int nVal,                       /* Number of elements in apVal */
179297  sqlite3_value **apVal           /* Arguments for the indexing scheme */
179298){
179299  Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
179300  Fts5Config *pConfig = pTab->pConfig;
179301  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
179302  int rc = SQLITE_OK;             /* Error code */
179303  int iVal = 0;                   /* Counter for apVal[] */
179304  int bDesc;                      /* True if ORDER BY [rank|rowid] DESC */
179305  int bOrderByRank;               /* True if ORDER BY rank */
179306  sqlite3_value *pMatch = 0;      /* <tbl> MATCH ? expression (or NULL) */
179307  sqlite3_value *pRank = 0;       /* rank MATCH ? expression (or NULL) */
179308  sqlite3_value *pRowidEq = 0;    /* rowid = ? expression (or NULL) */
179309  sqlite3_value *pRowidLe = 0;    /* rowid <= ? expression (or NULL) */
179310  sqlite3_value *pRowidGe = 0;    /* rowid >= ? expression (or NULL) */
179311  char **pzErrmsg = pConfig->pzErrmsg;
179312
179313  if( pCsr->ePlan ){
179314    fts5FreeCursorComponents(pCsr);
179315    memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
179316  }
179317
179318  assert( pCsr->pStmt==0 );
179319  assert( pCsr->pExpr==0 );
179320  assert( pCsr->csrflags==0 );
179321  assert( pCsr->pRank==0 );
179322  assert( pCsr->zRank==0 );
179323  assert( pCsr->zRankArgs==0 );
179324
179325  assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
179326  pConfig->pzErrmsg = &pTab->base.zErrMsg;
179327
179328  /* Decode the arguments passed through to this function.
179329  **
179330  ** Note: The following set of if(...) statements must be in the same
179331  ** order as the corresponding entries in the struct at the top of
179332  ** fts5BestIndexMethod().  */
179333  if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
179334  if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
179335  if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
179336  if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
179337  if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
179338  assert( iVal==nVal );
179339  bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
179340  pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
179341
179342  /* Set the cursor upper and lower rowid limits. Only some strategies
179343  ** actually use them. This is ok, as the xBestIndex() method leaves the
179344  ** sqlite3_index_constraint.omit flag clear for range constraints
179345  ** on the rowid field.  */
179346  if( pRowidEq ){
179347    pRowidLe = pRowidGe = pRowidEq;
179348  }
179349  if( bDesc ){
179350    pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
179351    pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
179352  }else{
179353    pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
179354    pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
179355  }
179356
179357  if( pTab->pSortCsr ){
179358    /* If pSortCsr is non-NULL, then this call is being made as part of
179359    ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
179360    ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
179361    ** return results to the user for this query. The current cursor
179362    ** (pCursor) is used to execute the query issued by function
179363    ** fts5CursorFirstSorted() above.  */
179364    assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
179365    assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
179366    assert( pCsr->iLastRowid==LARGEST_INT64 );
179367    assert( pCsr->iFirstRowid==SMALLEST_INT64 );
179368    pCsr->ePlan = FTS5_PLAN_SOURCE;
179369    pCsr->pExpr = pTab->pSortCsr->pExpr;
179370    rc = fts5CursorFirst(pTab, pCsr, bDesc);
179371  }else if( pMatch ){
179372    const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
179373    if( zExpr==0 ) zExpr = "";
179374
179375    rc = fts5CursorParseRank(pConfig, pCsr, pRank);
179376    if( rc==SQLITE_OK ){
179377      if( zExpr[0]=='*' ){
179378        /* The user has issued a query of the form "MATCH '*...'". This
179379        ** indicates that the MATCH expression is not a full text query,
179380        ** but a request for an internal parameter.  */
179381        rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
179382      }else{
179383        char **pzErr = &pTab->base.zErrMsg;
179384        rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pCsr->pExpr, pzErr);
179385        if( rc==SQLITE_OK ){
179386          if( bOrderByRank ){
179387            pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
179388            rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
179389          }else{
179390            pCsr->ePlan = FTS5_PLAN_MATCH;
179391            rc = fts5CursorFirst(pTab, pCsr, bDesc);
179392          }
179393        }
179394      }
179395    }
179396  }else if( pConfig->zContent==0 ){
179397    *pConfig->pzErrmsg = sqlite3_mprintf(
179398        "%s: table does not support scanning", pConfig->zName
179399    );
179400    rc = SQLITE_ERROR;
179401  }else{
179402    /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
179403    ** by rowid (ePlan==FTS5_PLAN_ROWID).  */
179404    pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
179405    rc = sqlite3Fts5StorageStmt(
179406        pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
179407    );
179408    if( rc==SQLITE_OK ){
179409      if( pCsr->ePlan==FTS5_PLAN_ROWID ){
179410        sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
179411      }else{
179412        sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
179413        sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
179414      }
179415      rc = fts5NextMethod(pCursor);
179416    }
179417  }
179418
179419  pConfig->pzErrmsg = pzErrmsg;
179420  return rc;
179421}
179422
179423/*
179424** This is the xEof method of the virtual table. SQLite calls this
179425** routine to find out if it has reached the end of a result set.
179426*/
179427static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
179428  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
179429  return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
179430}
179431
179432/*
179433** Return the rowid that the cursor currently points to.
179434*/
179435static i64 fts5CursorRowid(Fts5Cursor *pCsr){
179436  assert( pCsr->ePlan==FTS5_PLAN_MATCH
179437       || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
179438       || pCsr->ePlan==FTS5_PLAN_SOURCE
179439  );
179440  if( pCsr->pSorter ){
179441    return pCsr->pSorter->iRowid;
179442  }else{
179443    return sqlite3Fts5ExprRowid(pCsr->pExpr);
179444  }
179445}
179446
179447/*
179448** This is the xRowid method. The SQLite core calls this routine to
179449** retrieve the rowid for the current row of the result set. fts5
179450** exposes %_content.rowid as the rowid for the virtual table. The
179451** rowid should be written to *pRowid.
179452*/
179453static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
179454  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
179455  int ePlan = pCsr->ePlan;
179456
179457  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
179458  switch( ePlan ){
179459    case FTS5_PLAN_SPECIAL:
179460      *pRowid = 0;
179461      break;
179462
179463    case FTS5_PLAN_SOURCE:
179464    case FTS5_PLAN_MATCH:
179465    case FTS5_PLAN_SORTED_MATCH:
179466      *pRowid = fts5CursorRowid(pCsr);
179467      break;
179468
179469    default:
179470      *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
179471      break;
179472  }
179473
179474  return SQLITE_OK;
179475}
179476
179477/*
179478** If the cursor requires seeking (bSeekRequired flag is set), seek it.
179479** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
179480**
179481** If argument bErrormsg is true and an error occurs, an error message may
179482** be left in sqlite3_vtab.zErrMsg.
179483*/
179484static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
179485  int rc = SQLITE_OK;
179486
179487  /* If the cursor does not yet have a statement handle, obtain one now. */
179488  if( pCsr->pStmt==0 ){
179489    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
179490    int eStmt = fts5StmtType(pCsr);
179491    rc = sqlite3Fts5StorageStmt(
179492        pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
179493    );
179494    assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
179495    assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
179496  }
179497
179498  if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
179499    assert( pCsr->pExpr );
179500    sqlite3_reset(pCsr->pStmt);
179501    sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
179502    rc = sqlite3_step(pCsr->pStmt);
179503    if( rc==SQLITE_ROW ){
179504      rc = SQLITE_OK;
179505      CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
179506    }else{
179507      rc = sqlite3_reset(pCsr->pStmt);
179508      if( rc==SQLITE_OK ){
179509        rc = FTS5_CORRUPT;
179510      }
179511    }
179512  }
179513  return rc;
179514}
179515
179516static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
179517  va_list ap;                     /* ... printf arguments */
179518  va_start(ap, zFormat);
179519  assert( p->base.zErrMsg==0 );
179520  p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
179521  va_end(ap);
179522}
179523
179524/*
179525** This function is called to handle an FTS INSERT command. In other words,
179526** an INSERT statement of the form:
179527**
179528**     INSERT INTO fts(fts) VALUES($pCmd)
179529**     INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
179530**
179531** Argument pVal is the value assigned to column "fts" by the INSERT
179532** statement. This function returns SQLITE_OK if successful, or an SQLite
179533** error code if an error occurs.
179534**
179535** The commands implemented by this function are documented in the "Special
179536** INSERT Directives" section of the documentation. It should be updated if
179537** more commands are added to this function.
179538*/
179539static int fts5SpecialInsert(
179540  Fts5Table *pTab,                /* Fts5 table object */
179541  const char *zCmd,               /* Text inserted into table-name column */
179542  sqlite3_value *pVal             /* Value inserted into rank column */
179543){
179544  Fts5Config *pConfig = pTab->pConfig;
179545  int rc = SQLITE_OK;
179546  int bError = 0;
179547
179548  if( 0==sqlite3_stricmp("delete-all", zCmd) ){
179549    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
179550      fts5SetVtabError(pTab,
179551          "'delete-all' may only be used with a "
179552          "contentless or external content fts5 table"
179553      );
179554      rc = SQLITE_ERROR;
179555    }else{
179556      rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
179557    }
179558  }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
179559    if( pConfig->eContent==FTS5_CONTENT_NONE ){
179560      fts5SetVtabError(pTab,
179561          "'rebuild' may not be used with a contentless fts5 table"
179562      );
179563      rc = SQLITE_ERROR;
179564    }else{
179565      rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
179566    }
179567  }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
179568    rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
179569  }else if( 0==sqlite3_stricmp("merge", zCmd) ){
179570    int nMerge = sqlite3_value_int(pVal);
179571    rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
179572  }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
179573    rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
179574#ifdef SQLITE_DEBUG
179575  }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
179576    pConfig->bPrefixIndex = sqlite3_value_int(pVal);
179577#endif
179578  }else{
179579    rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
179580    if( rc==SQLITE_OK ){
179581      rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
179582    }
179583    if( rc==SQLITE_OK ){
179584      if( bError ){
179585        rc = SQLITE_ERROR;
179586      }else{
179587        rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
179588      }
179589    }
179590  }
179591  return rc;
179592}
179593
179594static int fts5SpecialDelete(
179595  Fts5Table *pTab,
179596  sqlite3_value **apVal,
179597  sqlite3_int64 *piRowid
179598){
179599  int rc = SQLITE_OK;
179600  int eType1 = sqlite3_value_type(apVal[1]);
179601  if( eType1==SQLITE_INTEGER ){
179602    sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
179603    rc = sqlite3Fts5StorageSpecialDelete(pTab->pStorage, iDel, &apVal[2]);
179604  }
179605  return rc;
179606}
179607
179608static void fts5StorageInsert(
179609  int *pRc,
179610  Fts5Table *pTab,
179611  sqlite3_value **apVal,
179612  i64 *piRowid
179613){
179614  int rc = *pRc;
179615  if( rc==SQLITE_OK ){
179616    rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
179617  }
179618  if( rc==SQLITE_OK ){
179619    rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
179620  }
179621  *pRc = rc;
179622}
179623
179624/*
179625** This function is the implementation of the xUpdate callback used by
179626** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
179627** inserted, updated or deleted.
179628**
179629** A delete specifies a single argument - the rowid of the row to remove.
179630**
179631** Update and insert operations pass:
179632**
179633**   1. The "old" rowid, or NULL.
179634**   2. The "new" rowid.
179635**   3. Values for each of the nCol matchable columns.
179636**   4. Values for the two hidden columns (<tablename> and "rank").
179637*/
179638static int fts5UpdateMethod(
179639  sqlite3_vtab *pVtab,            /* Virtual table handle */
179640  int nArg,                       /* Size of argument array */
179641  sqlite3_value **apVal,          /* Array of arguments */
179642  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
179643){
179644  Fts5Table *pTab = (Fts5Table*)pVtab;
179645  Fts5Config *pConfig = pTab->pConfig;
179646  int eType0;                     /* value_type() of apVal[0] */
179647  int rc = SQLITE_OK;             /* Return code */
179648
179649  /* A transaction must be open when this is called. */
179650  assert( pTab->ts.eState==1 );
179651
179652  assert( pVtab->zErrMsg==0 );
179653  assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
179654  assert( nArg==1
179655      || sqlite3_value_type(apVal[1])==SQLITE_INTEGER
179656      || sqlite3_value_type(apVal[1])==SQLITE_NULL
179657  );
179658  assert( pTab->pConfig->pzErrmsg==0 );
179659  pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
179660
179661  /* Put any active cursors into REQUIRE_SEEK state. */
179662  fts5TripCursors(pTab);
179663
179664  eType0 = sqlite3_value_type(apVal[0]);
179665  if( eType0==SQLITE_NULL
179666   && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
179667  ){
179668    /* A "special" INSERT op. These are handled separately. */
179669    const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
179670    if( pConfig->eContent!=FTS5_CONTENT_NORMAL
179671      && 0==sqlite3_stricmp("delete", z)
179672    ){
179673      rc = fts5SpecialDelete(pTab, apVal, pRowid);
179674    }else{
179675      rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
179676    }
179677  }else{
179678    /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
179679    ** any conflict on the rowid value must be detected before any
179680    ** modifications are made to the database file. There are 4 cases:
179681    **
179682    **   1) DELETE
179683    **   2) UPDATE (rowid not modified)
179684    **   3) UPDATE (rowid modified)
179685    **   4) INSERT
179686    **
179687    ** Cases 3 and 4 may violate the rowid constraint.
179688    */
179689    int eConflict = sqlite3_vtab_on_conflict(pConfig->db);
179690
179691    assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
179692    assert( nArg!=1 || eType0==SQLITE_INTEGER );
179693
179694    /* Filter out attempts to run UPDATE or DELETE on contentless tables.
179695    ** This is not suported.  */
179696    if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
179697      pTab->base.zErrMsg = sqlite3_mprintf(
179698          "cannot %s contentless fts5 table: %s",
179699          (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
179700      );
179701      rc = SQLITE_ERROR;
179702    }
179703
179704    /* Case 1: DELETE */
179705    else if( nArg==1 ){
179706      i64 iDel = sqlite3_value_int64(apVal[0]);  /* Rowid to delete */
179707      rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel);
179708    }
179709
179710    /* Case 2: INSERT */
179711    else if( eType0!=SQLITE_INTEGER ){
179712      /* If this is a REPLACE, first remove the current entry (if any) */
179713      if( eConflict==SQLITE_REPLACE
179714       && sqlite3_value_type(apVal[1])==SQLITE_INTEGER
179715      ){
179716        i64 iNew = sqlite3_value_int64(apVal[1]);  /* Rowid to delete */
179717        rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew);
179718      }
179719      fts5StorageInsert(&rc, pTab, apVal, pRowid);
179720    }
179721
179722    /* Case 2: UPDATE */
179723    else{
179724      i64 iOld = sqlite3_value_int64(apVal[0]);  /* Old rowid */
179725      i64 iNew = sqlite3_value_int64(apVal[1]);  /* New rowid */
179726      if( iOld!=iNew ){
179727        if( eConflict==SQLITE_REPLACE ){
179728          rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld);
179729          if( rc==SQLITE_OK ){
179730            rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew);
179731          }
179732          fts5StorageInsert(&rc, pTab, apVal, pRowid);
179733        }else{
179734          rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
179735          if( rc==SQLITE_OK ){
179736            rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld);
179737          }
179738          if( rc==SQLITE_OK ){
179739            rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
179740          }
179741        }
179742      }else{
179743        rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld);
179744        fts5StorageInsert(&rc, pTab, apVal, pRowid);
179745      }
179746    }
179747  }
179748
179749  pTab->pConfig->pzErrmsg = 0;
179750  return rc;
179751}
179752
179753/*
179754** Implementation of xSync() method.
179755*/
179756static int fts5SyncMethod(sqlite3_vtab *pVtab){
179757  int rc;
179758  Fts5Table *pTab = (Fts5Table*)pVtab;
179759  fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
179760  pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
179761  fts5TripCursors(pTab);
179762  rc = sqlite3Fts5StorageSync(pTab->pStorage, 1);
179763  pTab->pConfig->pzErrmsg = 0;
179764  return rc;
179765}
179766
179767/*
179768** Implementation of xBegin() method.
179769*/
179770static int fts5BeginMethod(sqlite3_vtab *pVtab){
179771  fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
179772  return SQLITE_OK;
179773}
179774
179775/*
179776** Implementation of xCommit() method. This is a no-op. The contents of
179777** the pending-terms hash-table have already been flushed into the database
179778** by fts5SyncMethod().
179779*/
179780static int fts5CommitMethod(sqlite3_vtab *pVtab){
179781  fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
179782  return SQLITE_OK;
179783}
179784
179785/*
179786** Implementation of xRollback(). Discard the contents of the pending-terms
179787** hash-table. Any changes made to the database are reverted by SQLite.
179788*/
179789static int fts5RollbackMethod(sqlite3_vtab *pVtab){
179790  int rc;
179791  Fts5Table *pTab = (Fts5Table*)pVtab;
179792  fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
179793  rc = sqlite3Fts5StorageRollback(pTab->pStorage);
179794  return rc;
179795}
179796
179797static void *fts5ApiUserData(Fts5Context *pCtx){
179798  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
179799  return pCsr->pAux->pUserData;
179800}
179801
179802static int fts5ApiColumnCount(Fts5Context *pCtx){
179803  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
179804  return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
179805}
179806
179807static int fts5ApiColumnTotalSize(
179808  Fts5Context *pCtx,
179809  int iCol,
179810  sqlite3_int64 *pnToken
179811){
179812  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
179813  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
179814  return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
179815}
179816
179817static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
179818  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
179819  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
179820  return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
179821}
179822
179823static int fts5ApiTokenize(
179824  Fts5Context *pCtx,
179825  const char *pText, int nText,
179826  void *pUserData,
179827  int (*xToken)(void*, int, const char*, int, int, int)
179828){
179829  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
179830  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
179831  return sqlite3Fts5Tokenize(
179832      pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
179833  );
179834}
179835
179836static int fts5ApiPhraseCount(Fts5Context *pCtx){
179837  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
179838  return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
179839}
179840
179841static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
179842  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
179843  return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
179844}
179845
179846static int fts5CsrPoslist(Fts5Cursor *pCsr, int iPhrase, const u8 **pa){
179847  int n;
179848  if( pCsr->pSorter ){
179849    Fts5Sorter *pSorter = pCsr->pSorter;
179850    int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
179851    n = pSorter->aIdx[iPhrase] - i1;
179852    *pa = &pSorter->aPoslist[i1];
179853  }else{
179854    n = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
179855  }
179856  return n;
179857}
179858
179859/*
179860** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
179861** correctly for the current view. Return SQLITE_OK if successful, or an
179862** SQLite error code otherwise.
179863*/
179864static int fts5CacheInstArray(Fts5Cursor *pCsr){
179865  int rc = SQLITE_OK;
179866  Fts5PoslistReader *aIter;       /* One iterator for each phrase */
179867  int nIter;                      /* Number of iterators/phrases */
179868
179869  nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
179870  if( pCsr->aInstIter==0 ){
179871    int nByte = sizeof(Fts5PoslistReader) * nIter;
179872    pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
179873  }
179874  aIter = pCsr->aInstIter;
179875
179876  if( aIter ){
179877    int nInst = 0;                /* Number instances seen so far */
179878    int i;
179879
179880    /* Initialize all iterators */
179881    for(i=0; i<nIter; i++){
179882      const u8 *a;
179883      int n = fts5CsrPoslist(pCsr, i, &a);
179884      sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
179885    }
179886
179887    while( 1 ){
179888      int *aInst;
179889      int iBest = -1;
179890      for(i=0; i<nIter; i++){
179891        if( (aIter[i].bEof==0)
179892         && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
179893        ){
179894          iBest = i;
179895        }
179896      }
179897      if( iBest<0 ) break;
179898
179899      nInst++;
179900      if( nInst>=pCsr->nInstAlloc ){
179901        pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
179902        aInst = (int*)sqlite3_realloc(
179903            pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
179904        );
179905        if( aInst ){
179906          pCsr->aInst = aInst;
179907        }else{
179908          rc = SQLITE_NOMEM;
179909          break;
179910        }
179911      }
179912
179913      aInst = &pCsr->aInst[3 * (nInst-1)];
179914      aInst[0] = iBest;
179915      aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
179916      aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
179917      sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
179918    }
179919
179920    pCsr->nInstCount = nInst;
179921    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
179922  }
179923  return rc;
179924}
179925
179926static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
179927  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
179928  int rc = SQLITE_OK;
179929  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
179930   || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
179931    *pnInst = pCsr->nInstCount;
179932  }
179933  return rc;
179934}
179935
179936static int fts5ApiInst(
179937  Fts5Context *pCtx,
179938  int iIdx,
179939  int *piPhrase,
179940  int *piCol,
179941  int *piOff
179942){
179943  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
179944  int rc = SQLITE_OK;
179945  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
179946   || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
179947  ){
179948    if( iIdx<0 || iIdx>=pCsr->nInstCount ){
179949      rc = SQLITE_RANGE;
179950    }else{
179951      *piPhrase = pCsr->aInst[iIdx*3];
179952      *piCol = pCsr->aInst[iIdx*3 + 1];
179953      *piOff = pCsr->aInst[iIdx*3 + 2];
179954    }
179955  }
179956  return rc;
179957}
179958
179959static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
179960  return fts5CursorRowid((Fts5Cursor*)pCtx);
179961}
179962
179963static int fts5ApiColumnText(
179964  Fts5Context *pCtx,
179965  int iCol,
179966  const char **pz,
179967  int *pn
179968){
179969  int rc = SQLITE_OK;
179970  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
179971  if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
179972    *pz = 0;
179973    *pn = 0;
179974  }else{
179975    rc = fts5SeekCursor(pCsr, 0);
179976    if( rc==SQLITE_OK ){
179977      *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
179978      *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
179979    }
179980  }
179981  return rc;
179982}
179983
179984static int fts5ColumnSizeCb(
179985  void *pContext,                 /* Pointer to int */
179986  int tflags,
179987  const char *pToken,             /* Buffer containing token */
179988  int nToken,                     /* Size of token in bytes */
179989  int iStart,                     /* Start offset of token */
179990  int iEnd                        /* End offset of token */
179991){
179992  int *pCnt = (int*)pContext;
179993  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
179994    (*pCnt)++;
179995  }
179996  return SQLITE_OK;
179997}
179998
179999static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
180000  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
180001  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
180002  Fts5Config *pConfig = pTab->pConfig;
180003  int rc = SQLITE_OK;
180004
180005  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
180006    if( pConfig->bColumnsize ){
180007      i64 iRowid = fts5CursorRowid(pCsr);
180008      rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
180009    }else if( pConfig->zContent==0 ){
180010      int i;
180011      for(i=0; i<pConfig->nCol; i++){
180012        if( pConfig->abUnindexed[i]==0 ){
180013          pCsr->aColumnSize[i] = -1;
180014        }
180015      }
180016    }else{
180017      int i;
180018      for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
180019        if( pConfig->abUnindexed[i]==0 ){
180020          const char *z; int n;
180021          void *p = (void*)(&pCsr->aColumnSize[i]);
180022          pCsr->aColumnSize[i] = 0;
180023          rc = fts5ApiColumnText(pCtx, i, &z, &n);
180024          if( rc==SQLITE_OK ){
180025            rc = sqlite3Fts5Tokenize(
180026                pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
180027            );
180028          }
180029        }
180030      }
180031    }
180032    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
180033  }
180034  if( iCol<0 ){
180035    int i;
180036    *pnToken = 0;
180037    for(i=0; i<pConfig->nCol; i++){
180038      *pnToken += pCsr->aColumnSize[i];
180039    }
180040  }else if( iCol<pConfig->nCol ){
180041    *pnToken = pCsr->aColumnSize[iCol];
180042  }else{
180043    *pnToken = 0;
180044    rc = SQLITE_RANGE;
180045  }
180046  return rc;
180047}
180048
180049/*
180050** Implementation of the xSetAuxdata() method.
180051*/
180052static int fts5ApiSetAuxdata(
180053  Fts5Context *pCtx,              /* Fts5 context */
180054  void *pPtr,                     /* Pointer to save as auxdata */
180055  void(*xDelete)(void*)           /* Destructor for pPtr (or NULL) */
180056){
180057  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
180058  Fts5Auxdata *pData;
180059
180060  /* Search through the cursors list of Fts5Auxdata objects for one that
180061  ** corresponds to the currently executing auxiliary function.  */
180062  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
180063    if( pData->pAux==pCsr->pAux ) break;
180064  }
180065
180066  if( pData ){
180067    if( pData->xDelete ){
180068      pData->xDelete(pData->pPtr);
180069    }
180070  }else{
180071    int rc = SQLITE_OK;
180072    pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
180073    if( pData==0 ){
180074      if( xDelete ) xDelete(pPtr);
180075      return rc;
180076    }
180077    pData->pAux = pCsr->pAux;
180078    pData->pNext = pCsr->pAuxdata;
180079    pCsr->pAuxdata = pData;
180080  }
180081
180082  pData->xDelete = xDelete;
180083  pData->pPtr = pPtr;
180084  return SQLITE_OK;
180085}
180086
180087static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
180088  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
180089  Fts5Auxdata *pData;
180090  void *pRet = 0;
180091
180092  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
180093    if( pData->pAux==pCsr->pAux ) break;
180094  }
180095
180096  if( pData ){
180097    pRet = pData->pPtr;
180098    if( bClear ){
180099      pData->pPtr = 0;
180100      pData->xDelete = 0;
180101    }
180102  }
180103
180104  return pRet;
180105}
180106
180107static void fts5ApiPhraseNext(
180108  Fts5Context *pCtx,
180109  Fts5PhraseIter *pIter,
180110  int *piCol, int *piOff
180111){
180112  if( pIter->a>=pIter->b ){
180113    *piCol = -1;
180114    *piOff = -1;
180115  }else{
180116    int iVal;
180117    pIter->a += fts5GetVarint32(pIter->a, iVal);
180118    if( iVal==1 ){
180119      pIter->a += fts5GetVarint32(pIter->a, iVal);
180120      *piCol = iVal;
180121      *piOff = 0;
180122      pIter->a += fts5GetVarint32(pIter->a, iVal);
180123    }
180124    *piOff += (iVal-2);
180125  }
180126}
180127
180128static void fts5ApiPhraseFirst(
180129  Fts5Context *pCtx,
180130  int iPhrase,
180131  Fts5PhraseIter *pIter,
180132  int *piCol, int *piOff
180133){
180134  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
180135  int n = fts5CsrPoslist(pCsr, iPhrase, &pIter->a);
180136  pIter->b = &pIter->a[n];
180137  *piCol = 0;
180138  *piOff = 0;
180139  fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
180140}
180141
180142static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
180143    int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
180144);
180145
180146static const Fts5ExtensionApi sFts5Api = {
180147  2,                            /* iVersion */
180148  fts5ApiUserData,
180149  fts5ApiColumnCount,
180150  fts5ApiRowCount,
180151  fts5ApiColumnTotalSize,
180152  fts5ApiTokenize,
180153  fts5ApiPhraseCount,
180154  fts5ApiPhraseSize,
180155  fts5ApiInstCount,
180156  fts5ApiInst,
180157  fts5ApiRowid,
180158  fts5ApiColumnText,
180159  fts5ApiColumnSize,
180160  fts5ApiQueryPhrase,
180161  fts5ApiSetAuxdata,
180162  fts5ApiGetAuxdata,
180163  fts5ApiPhraseFirst,
180164  fts5ApiPhraseNext,
180165};
180166
180167
180168/*
180169** Implementation of API function xQueryPhrase().
180170*/
180171static int fts5ApiQueryPhrase(
180172  Fts5Context *pCtx,
180173  int iPhrase,
180174  void *pUserData,
180175  int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
180176){
180177  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
180178  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
180179  int rc;
180180  Fts5Cursor *pNew = 0;
180181
180182  rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
180183  if( rc==SQLITE_OK ){
180184    Fts5Config *pConf = pTab->pConfig;
180185    pNew->ePlan = FTS5_PLAN_MATCH;
180186    pNew->iFirstRowid = SMALLEST_INT64;
180187    pNew->iLastRowid = LARGEST_INT64;
180188    pNew->base.pVtab = (sqlite3_vtab*)pTab;
180189    rc = sqlite3Fts5ExprClonePhrase(pConf, pCsr->pExpr, iPhrase, &pNew->pExpr);
180190  }
180191
180192  if( rc==SQLITE_OK ){
180193    for(rc = fts5CursorFirst(pTab, pNew, 0);
180194        rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
180195        rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
180196    ){
180197      rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
180198      if( rc!=SQLITE_OK ){
180199        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
180200        break;
180201      }
180202    }
180203  }
180204
180205  fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
180206  return rc;
180207}
180208
180209static void fts5ApiInvoke(
180210  Fts5Auxiliary *pAux,
180211  Fts5Cursor *pCsr,
180212  sqlite3_context *context,
180213  int argc,
180214  sqlite3_value **argv
180215){
180216  assert( pCsr->pAux==0 );
180217  pCsr->pAux = pAux;
180218  pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
180219  pCsr->pAux = 0;
180220}
180221
180222static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
180223  Fts5Cursor *pCsr;
180224  for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
180225    if( pCsr->iCsrId==iCsrId ) break;
180226  }
180227  return pCsr;
180228}
180229
180230static void fts5ApiCallback(
180231  sqlite3_context *context,
180232  int argc,
180233  sqlite3_value **argv
180234){
180235
180236  Fts5Auxiliary *pAux;
180237  Fts5Cursor *pCsr;
180238  i64 iCsrId;
180239
180240  assert( argc>=1 );
180241  pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
180242  iCsrId = sqlite3_value_int64(argv[0]);
180243
180244  pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
180245  if( pCsr==0 ){
180246    char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
180247    sqlite3_result_error(context, zErr, -1);
180248    sqlite3_free(zErr);
180249  }else{
180250    fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
180251  }
180252}
180253
180254
180255/*
180256** Given cursor id iId, return a pointer to the corresponding Fts5Index
180257** object. Or NULL If the cursor id does not exist.
180258**
180259** If successful, set *pnCol to the number of indexed columns in the
180260** table before returning.
180261*/
180262static Fts5Index *sqlite3Fts5IndexFromCsrid(
180263  Fts5Global *pGlobal,
180264  i64 iCsrId,
180265  int *pnCol
180266){
180267  Fts5Cursor *pCsr;
180268  Fts5Table *pTab;
180269
180270  pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
180271  pTab = (Fts5Table*)pCsr->base.pVtab;
180272  *pnCol = pTab->pConfig->nCol;
180273
180274  return pTab->pIndex;
180275}
180276
180277/*
180278** Return a "position-list blob" corresponding to the current position of
180279** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
180280** the current position-list for each phrase in the query associated with
180281** cursor pCsr.
180282**
180283** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
180284** the number of phrases in the query. Following the varints are the
180285** concatenated position lists for each phrase, in order.
180286**
180287** The first varint (if it exists) contains the size of the position list
180288** for phrase 0. The second (same disclaimer) contains the size of position
180289** list 1. And so on. There is no size field for the final position list,
180290** as it can be derived from the total size of the blob.
180291*/
180292static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
180293  int i;
180294  int rc = SQLITE_OK;
180295  int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
180296  Fts5Buffer val;
180297
180298  memset(&val, 0, sizeof(Fts5Buffer));
180299
180300  /* Append the varints */
180301  for(i=0; i<(nPhrase-1); i++){
180302    const u8 *dummy;
180303    int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
180304    sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
180305  }
180306
180307  /* Append the position lists */
180308  for(i=0; i<nPhrase; i++){
180309    const u8 *pPoslist;
180310    int nPoslist;
180311    nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
180312    sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
180313  }
180314
180315  sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
180316  return rc;
180317}
180318
180319/*
180320** This is the xColumn method, called by SQLite to request a value from
180321** the row that the supplied cursor currently points to.
180322*/
180323static int fts5ColumnMethod(
180324  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
180325  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
180326  int iCol                        /* Index of column to read value from */
180327){
180328  Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
180329  Fts5Config *pConfig = pTab->pConfig;
180330  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
180331  int rc = SQLITE_OK;
180332
180333  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
180334
180335  if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
180336    if( iCol==pConfig->nCol ){
180337      sqlite3_result_int64(pCtx, pCsr->iSpecial);
180338    }
180339  }else
180340
180341  if( iCol==pConfig->nCol ){
180342    /* User is requesting the value of the special column with the same name
180343    ** as the table. Return the cursor integer id number. This value is only
180344    ** useful in that it may be passed as the first argument to an FTS5
180345    ** auxiliary function.  */
180346    sqlite3_result_int64(pCtx, pCsr->iCsrId);
180347  }else if( iCol==pConfig->nCol+1 ){
180348
180349    /* The value of the "rank" column. */
180350    if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
180351      fts5PoslistBlob(pCtx, pCsr);
180352    }else if(
180353        pCsr->ePlan==FTS5_PLAN_MATCH
180354     || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
180355    ){
180356      if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
180357        fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
180358      }
180359    }
180360  }else if( !fts5IsContentless(pTab) ){
180361    rc = fts5SeekCursor(pCsr, 1);
180362    if( rc==SQLITE_OK ){
180363      sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
180364    }
180365  }
180366  return rc;
180367}
180368
180369
180370/*
180371** This routine implements the xFindFunction method for the FTS3
180372** virtual table.
180373*/
180374static int fts5FindFunctionMethod(
180375  sqlite3_vtab *pVtab,            /* Virtual table handle */
180376  int nArg,                       /* Number of SQL function arguments */
180377  const char *zName,              /* Name of SQL function */
180378  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
180379  void **ppArg                    /* OUT: User data for *pxFunc */
180380){
180381  Fts5Table *pTab = (Fts5Table*)pVtab;
180382  Fts5Auxiliary *pAux;
180383
180384  pAux = fts5FindAuxiliary(pTab, zName);
180385  if( pAux ){
180386    *pxFunc = fts5ApiCallback;
180387    *ppArg = (void*)pAux;
180388    return 1;
180389  }
180390
180391  /* No function of the specified name was found. Return 0. */
180392  return 0;
180393}
180394
180395/*
180396** Implementation of FTS5 xRename method. Rename an fts5 table.
180397*/
180398static int fts5RenameMethod(
180399  sqlite3_vtab *pVtab,            /* Virtual table handle */
180400  const char *zName               /* New name of table */
180401){
180402  Fts5Table *pTab = (Fts5Table*)pVtab;
180403  return sqlite3Fts5StorageRename(pTab->pStorage, zName);
180404}
180405
180406/*
180407** The xSavepoint() method.
180408**
180409** Flush the contents of the pending-terms table to disk.
180410*/
180411static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
180412  Fts5Table *pTab = (Fts5Table*)pVtab;
180413  fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
180414  fts5TripCursors(pTab);
180415  return sqlite3Fts5StorageSync(pTab->pStorage, 0);
180416}
180417
180418/*
180419** The xRelease() method.
180420**
180421** This is a no-op.
180422*/
180423static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
180424  Fts5Table *pTab = (Fts5Table*)pVtab;
180425  fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
180426  fts5TripCursors(pTab);
180427  return sqlite3Fts5StorageSync(pTab->pStorage, 0);
180428}
180429
180430/*
180431** The xRollbackTo() method.
180432**
180433** Discard the contents of the pending terms table.
180434*/
180435static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
180436  Fts5Table *pTab = (Fts5Table*)pVtab;
180437  fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
180438  fts5TripCursors(pTab);
180439  return sqlite3Fts5StorageRollback(pTab->pStorage);
180440}
180441
180442/*
180443** Register a new auxiliary function with global context pGlobal.
180444*/
180445static int fts5CreateAux(
180446  fts5_api *pApi,                 /* Global context (one per db handle) */
180447  const char *zName,              /* Name of new function */
180448  void *pUserData,                /* User data for aux. function */
180449  fts5_extension_function xFunc,  /* Aux. function implementation */
180450  void(*xDestroy)(void*)          /* Destructor for pUserData */
180451){
180452  Fts5Global *pGlobal = (Fts5Global*)pApi;
180453  int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
180454  if( rc==SQLITE_OK ){
180455    Fts5Auxiliary *pAux;
180456    int nName;                      /* Size of zName in bytes, including \0 */
180457    int nByte;                      /* Bytes of space to allocate */
180458
180459    nName = (int)strlen(zName) + 1;
180460    nByte = sizeof(Fts5Auxiliary) + nName;
180461    pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
180462    if( pAux ){
180463      memset(pAux, 0, nByte);
180464      pAux->zFunc = (char*)&pAux[1];
180465      memcpy(pAux->zFunc, zName, nName);
180466      pAux->pGlobal = pGlobal;
180467      pAux->pUserData = pUserData;
180468      pAux->xFunc = xFunc;
180469      pAux->xDestroy = xDestroy;
180470      pAux->pNext = pGlobal->pAux;
180471      pGlobal->pAux = pAux;
180472    }else{
180473      rc = SQLITE_NOMEM;
180474    }
180475  }
180476
180477  return rc;
180478}
180479
180480/*
180481** Register a new tokenizer. This is the implementation of the
180482** fts5_api.xCreateTokenizer() method.
180483*/
180484static int fts5CreateTokenizer(
180485  fts5_api *pApi,                 /* Global context (one per db handle) */
180486  const char *zName,              /* Name of new function */
180487  void *pUserData,                /* User data for aux. function */
180488  fts5_tokenizer *pTokenizer,     /* Tokenizer implementation */
180489  void(*xDestroy)(void*)          /* Destructor for pUserData */
180490){
180491  Fts5Global *pGlobal = (Fts5Global*)pApi;
180492  Fts5TokenizerModule *pNew;
180493  int nName;                      /* Size of zName and its \0 terminator */
180494  int nByte;                      /* Bytes of space to allocate */
180495  int rc = SQLITE_OK;
180496
180497  nName = (int)strlen(zName) + 1;
180498  nByte = sizeof(Fts5TokenizerModule) + nName;
180499  pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
180500  if( pNew ){
180501    memset(pNew, 0, nByte);
180502    pNew->zName = (char*)&pNew[1];
180503    memcpy(pNew->zName, zName, nName);
180504    pNew->pUserData = pUserData;
180505    pNew->x = *pTokenizer;
180506    pNew->xDestroy = xDestroy;
180507    pNew->pNext = pGlobal->pTok;
180508    pGlobal->pTok = pNew;
180509    if( pNew->pNext==0 ){
180510      pGlobal->pDfltTok = pNew;
180511    }
180512  }else{
180513    rc = SQLITE_NOMEM;
180514  }
180515
180516  return rc;
180517}
180518
180519static Fts5TokenizerModule *fts5LocateTokenizer(
180520  Fts5Global *pGlobal,
180521  const char *zName
180522){
180523  Fts5TokenizerModule *pMod = 0;
180524
180525  if( zName==0 ){
180526    pMod = pGlobal->pDfltTok;
180527  }else{
180528    for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
180529      if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
180530    }
180531  }
180532
180533  return pMod;
180534}
180535
180536/*
180537** Find a tokenizer. This is the implementation of the
180538** fts5_api.xFindTokenizer() method.
180539*/
180540static int fts5FindTokenizer(
180541  fts5_api *pApi,                 /* Global context (one per db handle) */
180542  const char *zName,              /* Name of new function */
180543  void **ppUserData,
180544  fts5_tokenizer *pTokenizer      /* Populate this object */
180545){
180546  int rc = SQLITE_OK;
180547  Fts5TokenizerModule *pMod;
180548
180549  pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
180550  if( pMod ){
180551    *pTokenizer = pMod->x;
180552    *ppUserData = pMod->pUserData;
180553  }else{
180554    memset(pTokenizer, 0, sizeof(fts5_tokenizer));
180555    rc = SQLITE_ERROR;
180556  }
180557
180558  return rc;
180559}
180560
180561static int sqlite3Fts5GetTokenizer(
180562  Fts5Global *pGlobal,
180563  const char **azArg,
180564  int nArg,
180565  Fts5Tokenizer **ppTok,
180566  fts5_tokenizer **ppTokApi,
180567  char **pzErr
180568){
180569  Fts5TokenizerModule *pMod;
180570  int rc = SQLITE_OK;
180571
180572  pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
180573  if( pMod==0 ){
180574    assert( nArg>0 );
180575    rc = SQLITE_ERROR;
180576    *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
180577  }else{
180578    rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
180579    *ppTokApi = &pMod->x;
180580    if( rc!=SQLITE_OK && pzErr ){
180581      *pzErr = sqlite3_mprintf("error in tokenizer constructor");
180582    }
180583  }
180584
180585  if( rc!=SQLITE_OK ){
180586    *ppTokApi = 0;
180587    *ppTok = 0;
180588  }
180589
180590  return rc;
180591}
180592
180593static void fts5ModuleDestroy(void *pCtx){
180594  Fts5TokenizerModule *pTok, *pNextTok;
180595  Fts5Auxiliary *pAux, *pNextAux;
180596  Fts5Global *pGlobal = (Fts5Global*)pCtx;
180597
180598  for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
180599    pNextAux = pAux->pNext;
180600    if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
180601    sqlite3_free(pAux);
180602  }
180603
180604  for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
180605    pNextTok = pTok->pNext;
180606    if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
180607    sqlite3_free(pTok);
180608  }
180609
180610  sqlite3_free(pGlobal);
180611}
180612
180613static void fts5Fts5Func(
180614  sqlite3_context *pCtx,          /* Function call context */
180615  int nArg,                       /* Number of args */
180616  sqlite3_value **apVal           /* Function arguments */
180617){
180618  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
180619  char buf[8];
180620  assert( nArg==0 );
180621  assert( sizeof(buf)>=sizeof(pGlobal) );
180622  memcpy(buf, (void*)&pGlobal, sizeof(pGlobal));
180623  sqlite3_result_blob(pCtx, buf, sizeof(pGlobal), SQLITE_TRANSIENT);
180624}
180625
180626/*
180627** Implementation of fts5_source_id() function.
180628*/
180629static void fts5SourceIdFunc(
180630  sqlite3_context *pCtx,          /* Function call context */
180631  int nArg,                       /* Number of args */
180632  sqlite3_value **apVal           /* Function arguments */
180633){
180634  assert( nArg==0 );
180635  sqlite3_result_text(pCtx, "fts5: 2015-11-02 18:31:45 bda77dda9697c463c3d0704014d51627fceee328", -1, SQLITE_TRANSIENT);
180636}
180637
180638static int fts5Init(sqlite3 *db){
180639  static const sqlite3_module fts5Mod = {
180640    /* iVersion      */ 2,
180641    /* xCreate       */ fts5CreateMethod,
180642    /* xConnect      */ fts5ConnectMethod,
180643    /* xBestIndex    */ fts5BestIndexMethod,
180644    /* xDisconnect   */ fts5DisconnectMethod,
180645    /* xDestroy      */ fts5DestroyMethod,
180646    /* xOpen         */ fts5OpenMethod,
180647    /* xClose        */ fts5CloseMethod,
180648    /* xFilter       */ fts5FilterMethod,
180649    /* xNext         */ fts5NextMethod,
180650    /* xEof          */ fts5EofMethod,
180651    /* xColumn       */ fts5ColumnMethod,
180652    /* xRowid        */ fts5RowidMethod,
180653    /* xUpdate       */ fts5UpdateMethod,
180654    /* xBegin        */ fts5BeginMethod,
180655    /* xSync         */ fts5SyncMethod,
180656    /* xCommit       */ fts5CommitMethod,
180657    /* xRollback     */ fts5RollbackMethod,
180658    /* xFindFunction */ fts5FindFunctionMethod,
180659    /* xRename       */ fts5RenameMethod,
180660    /* xSavepoint    */ fts5SavepointMethod,
180661    /* xRelease      */ fts5ReleaseMethod,
180662    /* xRollbackTo   */ fts5RollbackToMethod,
180663  };
180664
180665  int rc;
180666  Fts5Global *pGlobal = 0;
180667
180668  pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
180669  if( pGlobal==0 ){
180670    rc = SQLITE_NOMEM;
180671  }else{
180672    void *p = (void*)pGlobal;
180673    memset(pGlobal, 0, sizeof(Fts5Global));
180674    pGlobal->db = db;
180675    pGlobal->api.iVersion = 2;
180676    pGlobal->api.xCreateFunction = fts5CreateAux;
180677    pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
180678    pGlobal->api.xFindTokenizer = fts5FindTokenizer;
180679    rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
180680    if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
180681    if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
180682    if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
180683    if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
180684    if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
180685    if( rc==SQLITE_OK ){
180686      rc = sqlite3_create_function(
180687          db, "fts5", 0, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
180688      );
180689    }
180690    if( rc==SQLITE_OK ){
180691      rc = sqlite3_create_function(
180692          db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
180693      );
180694    }
180695  }
180696  return rc;
180697}
180698
180699/*
180700** The following functions are used to register the module with SQLite. If
180701** this module is being built as part of the SQLite core (SQLITE_CORE is
180702** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
180703**
180704** Or, if this module is being built as a loadable extension,
180705** sqlite3Fts5Init() is omitted and the two standard entry points
180706** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
180707*/
180708#ifndef SQLITE_CORE
180709#ifdef _WIN32
180710__declspec(dllexport)
180711#endif
180712SQLITE_API int SQLITE_STDCALL sqlite3_fts_init(
180713  sqlite3 *db,
180714  char **pzErrMsg,
180715  const sqlite3_api_routines *pApi
180716){
180717  SQLITE_EXTENSION_INIT2(pApi);
180718  (void)pzErrMsg;  /* Unused parameter */
180719  return fts5Init(db);
180720}
180721
180722#ifdef _WIN32
180723__declspec(dllexport)
180724#endif
180725SQLITE_API int SQLITE_STDCALL sqlite3_fts5_init(
180726  sqlite3 *db,
180727  char **pzErrMsg,
180728  const sqlite3_api_routines *pApi
180729){
180730  SQLITE_EXTENSION_INIT2(pApi);
180731  (void)pzErrMsg;  /* Unused parameter */
180732  return fts5Init(db);
180733}
180734#else
180735SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
180736  return fts5Init(db);
180737}
180738#endif
180739
180740/*
180741** 2014 May 31
180742**
180743** The author disclaims copyright to this source code.  In place of
180744** a legal notice, here is a blessing:
180745**
180746**    May you do good and not evil.
180747**    May you find forgiveness for yourself and forgive others.
180748**    May you share freely, never taking more than you give.
180749**
180750******************************************************************************
180751**
180752*/
180753
180754
180755
180756
180757struct Fts5Storage {
180758  Fts5Config *pConfig;
180759  Fts5Index *pIndex;
180760  int bTotalsValid;               /* True if nTotalRow/aTotalSize[] are valid */
180761  i64 nTotalRow;                  /* Total number of rows in FTS table */
180762  i64 *aTotalSize;                /* Total sizes of each column */
180763  sqlite3_stmt *aStmt[11];
180764};
180765
180766
180767#if FTS5_STMT_SCAN_ASC!=0
180768# error "FTS5_STMT_SCAN_ASC mismatch"
180769#endif
180770#if FTS5_STMT_SCAN_DESC!=1
180771# error "FTS5_STMT_SCAN_DESC mismatch"
180772#endif
180773#if FTS5_STMT_LOOKUP!=2
180774# error "FTS5_STMT_LOOKUP mismatch"
180775#endif
180776
180777#define FTS5_STMT_INSERT_CONTENT  3
180778#define FTS5_STMT_REPLACE_CONTENT 4
180779#define FTS5_STMT_DELETE_CONTENT  5
180780#define FTS5_STMT_REPLACE_DOCSIZE  6
180781#define FTS5_STMT_DELETE_DOCSIZE  7
180782#define FTS5_STMT_LOOKUP_DOCSIZE  8
180783#define FTS5_STMT_REPLACE_CONFIG 9
180784#define FTS5_STMT_SCAN 10
180785
180786/*
180787** Prepare the two insert statements - Fts5Storage.pInsertContent and
180788** Fts5Storage.pInsertDocsize - if they have not already been prepared.
180789** Return SQLITE_OK if successful, or an SQLite error code if an error
180790** occurs.
180791*/
180792static int fts5StorageGetStmt(
180793  Fts5Storage *p,                 /* Storage handle */
180794  int eStmt,                      /* FTS5_STMT_XXX constant */
180795  sqlite3_stmt **ppStmt,          /* OUT: Prepared statement handle */
180796  char **pzErrMsg                 /* OUT: Error message (if any) */
180797){
180798  int rc = SQLITE_OK;
180799
180800  /* If there is no %_docsize table, there should be no requests for
180801  ** statements to operate on it.  */
180802  assert( p->pConfig->bColumnsize || (
180803        eStmt!=FTS5_STMT_REPLACE_DOCSIZE
180804     && eStmt!=FTS5_STMT_DELETE_DOCSIZE
180805     && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
180806  ));
180807
180808  assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
180809  if( p->aStmt[eStmt]==0 ){
180810    const char *azStmt[] = {
180811      "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
180812      "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
180813      "SELECT %s FROM %s T WHERE T.%Q=?",               /* LOOKUP  */
180814
180815      "INSERT INTO %Q.'%q_content' VALUES(%s)",         /* INSERT_CONTENT  */
180816      "REPLACE INTO %Q.'%q_content' VALUES(%s)",        /* REPLACE_CONTENT */
180817      "DELETE FROM %Q.'%q_content' WHERE id=?",         /* DELETE_CONTENT  */
180818      "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",       /* REPLACE_DOCSIZE  */
180819      "DELETE FROM %Q.'%q_docsize' WHERE id=?",         /* DELETE_DOCSIZE  */
180820
180821      "SELECT sz FROM %Q.'%q_docsize' WHERE id=?",      /* LOOKUP_DOCSIZE  */
180822
180823      "REPLACE INTO %Q.'%q_config' VALUES(?,?)",        /* REPLACE_CONFIG */
180824      "SELECT %s FROM %s AS T",                         /* SCAN */
180825    };
180826    Fts5Config *pC = p->pConfig;
180827    char *zSql = 0;
180828
180829    switch( eStmt ){
180830      case FTS5_STMT_SCAN:
180831        zSql = sqlite3_mprintf(azStmt[eStmt],
180832            pC->zContentExprlist, pC->zContent
180833        );
180834        break;
180835
180836      case FTS5_STMT_SCAN_ASC:
180837      case FTS5_STMT_SCAN_DESC:
180838        zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
180839            pC->zContent, pC->zContentRowid, pC->zContentRowid,
180840            pC->zContentRowid
180841        );
180842        break;
180843
180844      case FTS5_STMT_LOOKUP:
180845        zSql = sqlite3_mprintf(azStmt[eStmt],
180846            pC->zContentExprlist, pC->zContent, pC->zContentRowid
180847        );
180848        break;
180849
180850      case FTS5_STMT_INSERT_CONTENT:
180851      case FTS5_STMT_REPLACE_CONTENT: {
180852        int nCol = pC->nCol + 1;
180853        char *zBind;
180854        int i;
180855
180856        zBind = sqlite3_malloc(1 + nCol*2);
180857        if( zBind ){
180858          for(i=0; i<nCol; i++){
180859            zBind[i*2] = '?';
180860            zBind[i*2 + 1] = ',';
180861          }
180862          zBind[i*2-1] = '\0';
180863          zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
180864          sqlite3_free(zBind);
180865        }
180866        break;
180867      }
180868
180869      default:
180870        zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
180871        break;
180872    }
180873
180874    if( zSql==0 ){
180875      rc = SQLITE_NOMEM;
180876    }else{
180877      rc = sqlite3_prepare_v2(pC->db, zSql, -1, &p->aStmt[eStmt], 0);
180878      sqlite3_free(zSql);
180879      if( rc!=SQLITE_OK && pzErrMsg ){
180880        *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
180881      }
180882    }
180883  }
180884
180885  *ppStmt = p->aStmt[eStmt];
180886  return rc;
180887}
180888
180889
180890static int fts5ExecPrintf(
180891  sqlite3 *db,
180892  char **pzErr,
180893  const char *zFormat,
180894  ...
180895){
180896  int rc;
180897  va_list ap;                     /* ... printf arguments */
180898  char *zSql;
180899
180900  va_start(ap, zFormat);
180901  zSql = sqlite3_vmprintf(zFormat, ap);
180902
180903  if( zSql==0 ){
180904    rc = SQLITE_NOMEM;
180905  }else{
180906    rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
180907    sqlite3_free(zSql);
180908  }
180909
180910  va_end(ap);
180911  return rc;
180912}
180913
180914/*
180915** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
180916** code otherwise.
180917*/
180918static int sqlite3Fts5DropAll(Fts5Config *pConfig){
180919  int rc = fts5ExecPrintf(pConfig->db, 0,
180920      "DROP TABLE IF EXISTS %Q.'%q_data';"
180921      "DROP TABLE IF EXISTS %Q.'%q_idx';"
180922      "DROP TABLE IF EXISTS %Q.'%q_config';",
180923      pConfig->zDb, pConfig->zName,
180924      pConfig->zDb, pConfig->zName,
180925      pConfig->zDb, pConfig->zName
180926  );
180927  if( rc==SQLITE_OK && pConfig->bColumnsize ){
180928    rc = fts5ExecPrintf(pConfig->db, 0,
180929        "DROP TABLE IF EXISTS %Q.'%q_docsize';",
180930        pConfig->zDb, pConfig->zName
180931    );
180932  }
180933  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
180934    rc = fts5ExecPrintf(pConfig->db, 0,
180935        "DROP TABLE IF EXISTS %Q.'%q_content';",
180936        pConfig->zDb, pConfig->zName
180937    );
180938  }
180939  return rc;
180940}
180941
180942static void fts5StorageRenameOne(
180943  Fts5Config *pConfig,            /* Current FTS5 configuration */
180944  int *pRc,                       /* IN/OUT: Error code */
180945  const char *zTail,              /* Tail of table name e.g. "data", "config" */
180946  const char *zName               /* New name of FTS5 table */
180947){
180948  if( *pRc==SQLITE_OK ){
180949    *pRc = fts5ExecPrintf(pConfig->db, 0,
180950        "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
180951        pConfig->zDb, pConfig->zName, zTail, zName, zTail
180952    );
180953  }
180954}
180955
180956static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
180957  Fts5Config *pConfig = pStorage->pConfig;
180958  int rc = sqlite3Fts5StorageSync(pStorage, 1);
180959
180960  fts5StorageRenameOne(pConfig, &rc, "data", zName);
180961  fts5StorageRenameOne(pConfig, &rc, "idx", zName);
180962  fts5StorageRenameOne(pConfig, &rc, "config", zName);
180963  if( pConfig->bColumnsize ){
180964    fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
180965  }
180966  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
180967    fts5StorageRenameOne(pConfig, &rc, "content", zName);
180968  }
180969  return rc;
180970}
180971
180972/*
180973** Create the shadow table named zPost, with definition zDefn. Return
180974** SQLITE_OK if successful, or an SQLite error code otherwise.
180975*/
180976static int sqlite3Fts5CreateTable(
180977  Fts5Config *pConfig,            /* FTS5 configuration */
180978  const char *zPost,              /* Shadow table to create (e.g. "content") */
180979  const char *zDefn,              /* Columns etc. for shadow table */
180980  int bWithout,                   /* True for without rowid */
180981  char **pzErr                    /* OUT: Error message */
180982){
180983  int rc;
180984  char *zErr = 0;
180985
180986  rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
180987      pConfig->zDb, pConfig->zName, zPost, zDefn, bWithout?" WITHOUT ROWID":""
180988  );
180989  if( zErr ){
180990    *pzErr = sqlite3_mprintf(
180991        "fts5: error creating shadow table %q_%s: %s",
180992        pConfig->zName, zPost, zErr
180993    );
180994    sqlite3_free(zErr);
180995  }
180996
180997  return rc;
180998}
180999
181000/*
181001** Open a new Fts5Index handle. If the bCreate argument is true, create
181002** and initialize the underlying tables
181003**
181004** If successful, set *pp to point to the new object and return SQLITE_OK.
181005** Otherwise, set *pp to NULL and return an SQLite error code.
181006*/
181007static int sqlite3Fts5StorageOpen(
181008  Fts5Config *pConfig,
181009  Fts5Index *pIndex,
181010  int bCreate,
181011  Fts5Storage **pp,
181012  char **pzErr                    /* OUT: Error message */
181013){
181014  int rc = SQLITE_OK;
181015  Fts5Storage *p;                 /* New object */
181016  int nByte;                      /* Bytes of space to allocate */
181017
181018  nByte = sizeof(Fts5Storage)               /* Fts5Storage object */
181019        + pConfig->nCol * sizeof(i64);      /* Fts5Storage.aTotalSize[] */
181020  *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
181021  if( !p ) return SQLITE_NOMEM;
181022
181023  memset(p, 0, nByte);
181024  p->aTotalSize = (i64*)&p[1];
181025  p->pConfig = pConfig;
181026  p->pIndex = pIndex;
181027
181028  if( bCreate ){
181029    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
181030      int nDefn = 32 + pConfig->nCol*10;
181031      char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
181032      if( zDefn==0 ){
181033        rc = SQLITE_NOMEM;
181034      }else{
181035        int i;
181036        int iOff;
181037        sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
181038        iOff = strlen(zDefn);
181039        for(i=0; i<pConfig->nCol; i++){
181040          sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
181041          iOff += strlen(&zDefn[iOff]);
181042        }
181043        rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
181044      }
181045      sqlite3_free(zDefn);
181046    }
181047
181048    if( rc==SQLITE_OK && pConfig->bColumnsize ){
181049      rc = sqlite3Fts5CreateTable(
181050          pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
181051      );
181052    }
181053    if( rc==SQLITE_OK ){
181054      rc = sqlite3Fts5CreateTable(
181055          pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
181056      );
181057    }
181058    if( rc==SQLITE_OK ){
181059      rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
181060    }
181061  }
181062
181063  if( rc ){
181064    sqlite3Fts5StorageClose(p);
181065    *pp = 0;
181066  }
181067  return rc;
181068}
181069
181070/*
181071** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
181072*/
181073static int sqlite3Fts5StorageClose(Fts5Storage *p){
181074  int rc = SQLITE_OK;
181075  if( p ){
181076    int i;
181077
181078    /* Finalize all SQL statements */
181079    for(i=0; i<ArraySize(p->aStmt); i++){
181080      sqlite3_finalize(p->aStmt[i]);
181081    }
181082
181083    sqlite3_free(p);
181084  }
181085  return rc;
181086}
181087
181088typedef struct Fts5InsertCtx Fts5InsertCtx;
181089struct Fts5InsertCtx {
181090  Fts5Storage *pStorage;
181091  int iCol;
181092  int szCol;                      /* Size of column value in tokens */
181093};
181094
181095/*
181096** Tokenization callback used when inserting tokens into the FTS index.
181097*/
181098static int fts5StorageInsertCallback(
181099  void *pContext,                 /* Pointer to Fts5InsertCtx object */
181100  int tflags,
181101  const char *pToken,             /* Buffer containing token */
181102  int nToken,                     /* Size of token in bytes */
181103  int iStart,                     /* Start offset of token */
181104  int iEnd                        /* End offset of token */
181105){
181106  Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
181107  Fts5Index *pIdx = pCtx->pStorage->pIndex;
181108  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
181109    pCtx->szCol++;
181110  }
181111  return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
181112}
181113
181114/*
181115** If a row with rowid iDel is present in the %_content table, add the
181116** delete-markers to the FTS index necessary to delete it. Do not actually
181117** remove the %_content row at this time though.
181118*/
181119static int fts5StorageDeleteFromIndex(Fts5Storage *p, i64 iDel){
181120  Fts5Config *pConfig = p->pConfig;
181121  sqlite3_stmt *pSeek;            /* SELECT to read row iDel from %_data */
181122  int rc;                         /* Return code */
181123
181124  rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
181125  if( rc==SQLITE_OK ){
181126    int rc2;
181127    sqlite3_bind_int64(pSeek, 1, iDel);
181128    if( sqlite3_step(pSeek)==SQLITE_ROW ){
181129      int iCol;
181130      Fts5InsertCtx ctx;
181131      ctx.pStorage = p;
181132      ctx.iCol = -1;
181133      rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
181134      for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
181135        if( pConfig->abUnindexed[iCol-1] ) continue;
181136        ctx.szCol = 0;
181137        rc = sqlite3Fts5Tokenize(pConfig,
181138            FTS5_TOKENIZE_DOCUMENT,
181139            (const char*)sqlite3_column_text(pSeek, iCol),
181140            sqlite3_column_bytes(pSeek, iCol),
181141            (void*)&ctx,
181142            fts5StorageInsertCallback
181143        );
181144        p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
181145      }
181146      p->nTotalRow--;
181147    }
181148    rc2 = sqlite3_reset(pSeek);
181149    if( rc==SQLITE_OK ) rc = rc2;
181150  }
181151
181152  return rc;
181153}
181154
181155
181156/*
181157** Insert a record into the %_docsize table. Specifically, do:
181158**
181159**   INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
181160**
181161** If there is no %_docsize table (as happens if the columnsize=0 option
181162** is specified when the FTS5 table is created), this function is a no-op.
181163*/
181164static int fts5StorageInsertDocsize(
181165  Fts5Storage *p,                 /* Storage module to write to */
181166  i64 iRowid,                     /* id value */
181167  Fts5Buffer *pBuf                /* sz value */
181168){
181169  int rc = SQLITE_OK;
181170  if( p->pConfig->bColumnsize ){
181171    sqlite3_stmt *pReplace = 0;
181172    rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
181173    if( rc==SQLITE_OK ){
181174      sqlite3_bind_int64(pReplace, 1, iRowid);
181175      sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
181176      sqlite3_step(pReplace);
181177      rc = sqlite3_reset(pReplace);
181178    }
181179  }
181180  return rc;
181181}
181182
181183/*
181184** Load the contents of the "averages" record from disk into the
181185** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
181186** argument bCache is true, set the p->bTotalsValid flag to indicate
181187** that the contents of aTotalSize[] and nTotalRow are valid until
181188** further notice.
181189**
181190** Return SQLITE_OK if successful, or an SQLite error code if an error
181191** occurs.
181192*/
181193static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
181194  int rc = SQLITE_OK;
181195  if( p->bTotalsValid==0 ){
181196    rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
181197    p->bTotalsValid = bCache;
181198  }
181199  return rc;
181200}
181201
181202/*
181203** Store the current contents of the p->nTotalRow and p->aTotalSize[]
181204** variables in the "averages" record on disk.
181205**
181206** Return SQLITE_OK if successful, or an SQLite error code if an error
181207** occurs.
181208*/
181209static int fts5StorageSaveTotals(Fts5Storage *p){
181210  int nCol = p->pConfig->nCol;
181211  int i;
181212  Fts5Buffer buf;
181213  int rc = SQLITE_OK;
181214  memset(&buf, 0, sizeof(buf));
181215
181216  sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
181217  for(i=0; i<nCol; i++){
181218    sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
181219  }
181220  if( rc==SQLITE_OK ){
181221    rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
181222  }
181223  sqlite3_free(buf.p);
181224
181225  return rc;
181226}
181227
181228/*
181229** Remove a row from the FTS table.
181230*/
181231static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel){
181232  Fts5Config *pConfig = p->pConfig;
181233  int rc;
181234  sqlite3_stmt *pDel = 0;
181235
181236  rc = fts5StorageLoadTotals(p, 1);
181237
181238  /* Delete the index records */
181239  if( rc==SQLITE_OK ){
181240    rc = fts5StorageDeleteFromIndex(p, iDel);
181241  }
181242
181243  /* Delete the %_docsize record */
181244  if( rc==SQLITE_OK && pConfig->bColumnsize ){
181245    rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
181246    if( rc==SQLITE_OK ){
181247      sqlite3_bind_int64(pDel, 1, iDel);
181248      sqlite3_step(pDel);
181249      rc = sqlite3_reset(pDel);
181250    }
181251  }
181252
181253  /* Delete the %_content record */
181254  if( rc==SQLITE_OK ){
181255    rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
181256  }
181257  if( rc==SQLITE_OK ){
181258    sqlite3_bind_int64(pDel, 1, iDel);
181259    sqlite3_step(pDel);
181260    rc = sqlite3_reset(pDel);
181261  }
181262
181263  /* Write the averages record */
181264  if( rc==SQLITE_OK ){
181265    rc = fts5StorageSaveTotals(p);
181266  }
181267
181268  return rc;
181269}
181270
181271static int sqlite3Fts5StorageSpecialDelete(
181272  Fts5Storage *p,
181273  i64 iDel,
181274  sqlite3_value **apVal
181275){
181276  Fts5Config *pConfig = p->pConfig;
181277  int rc;
181278  sqlite3_stmt *pDel = 0;
181279
181280  assert( pConfig->eContent!=FTS5_CONTENT_NORMAL );
181281  rc = fts5StorageLoadTotals(p, 1);
181282
181283  /* Delete the index records */
181284  if( rc==SQLITE_OK ){
181285    int iCol;
181286    Fts5InsertCtx ctx;
181287    ctx.pStorage = p;
181288    ctx.iCol = -1;
181289
181290    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
181291    for(iCol=0; rc==SQLITE_OK && iCol<pConfig->nCol; iCol++){
181292      if( pConfig->abUnindexed[iCol] ) continue;
181293      ctx.szCol = 0;
181294      rc = sqlite3Fts5Tokenize(pConfig,
181295        FTS5_TOKENIZE_DOCUMENT,
181296        (const char*)sqlite3_value_text(apVal[iCol]),
181297        sqlite3_value_bytes(apVal[iCol]),
181298        (void*)&ctx,
181299        fts5StorageInsertCallback
181300      );
181301      p->aTotalSize[iCol] -= (i64)ctx.szCol;
181302    }
181303    p->nTotalRow--;
181304  }
181305
181306  /* Delete the %_docsize record */
181307  if( pConfig->bColumnsize ){
181308    if( rc==SQLITE_OK ){
181309      rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
181310    }
181311    if( rc==SQLITE_OK ){
181312      sqlite3_bind_int64(pDel, 1, iDel);
181313      sqlite3_step(pDel);
181314      rc = sqlite3_reset(pDel);
181315    }
181316  }
181317
181318  /* Write the averages record */
181319  if( rc==SQLITE_OK ){
181320    rc = fts5StorageSaveTotals(p);
181321  }
181322
181323  return rc;
181324}
181325
181326/*
181327** Delete all entries in the FTS5 index.
181328*/
181329static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
181330  Fts5Config *pConfig = p->pConfig;
181331  int rc;
181332
181333  /* Delete the contents of the %_data and %_docsize tables. */
181334  rc = fts5ExecPrintf(pConfig->db, 0,
181335      "DELETE FROM %Q.'%q_data';"
181336      "DELETE FROM %Q.'%q_idx';",
181337      pConfig->zDb, pConfig->zName,
181338      pConfig->zDb, pConfig->zName
181339  );
181340  if( rc==SQLITE_OK && pConfig->bColumnsize ){
181341    rc = fts5ExecPrintf(pConfig->db, 0,
181342        "DELETE FROM %Q.'%q_docsize';",
181343        pConfig->zDb, pConfig->zName
181344    );
181345  }
181346
181347  /* Reinitialize the %_data table. This call creates the initial structure
181348  ** and averages records.  */
181349  if( rc==SQLITE_OK ){
181350    rc = sqlite3Fts5IndexReinit(p->pIndex);
181351  }
181352  if( rc==SQLITE_OK ){
181353    rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
181354  }
181355  return rc;
181356}
181357
181358static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
181359  Fts5Buffer buf = {0,0,0};
181360  Fts5Config *pConfig = p->pConfig;
181361  sqlite3_stmt *pScan = 0;
181362  Fts5InsertCtx ctx;
181363  int rc;
181364
181365  memset(&ctx, 0, sizeof(Fts5InsertCtx));
181366  ctx.pStorage = p;
181367  rc = sqlite3Fts5StorageDeleteAll(p);
181368  if( rc==SQLITE_OK ){
181369    rc = fts5StorageLoadTotals(p, 1);
181370  }
181371
181372  if( rc==SQLITE_OK ){
181373    rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
181374  }
181375
181376  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
181377    i64 iRowid = sqlite3_column_int64(pScan, 0);
181378
181379    sqlite3Fts5BufferZero(&buf);
181380    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
181381    for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
181382      ctx.szCol = 0;
181383      if( pConfig->abUnindexed[ctx.iCol]==0 ){
181384        rc = sqlite3Fts5Tokenize(pConfig,
181385            FTS5_TOKENIZE_DOCUMENT,
181386            (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
181387            sqlite3_column_bytes(pScan, ctx.iCol+1),
181388            (void*)&ctx,
181389            fts5StorageInsertCallback
181390        );
181391      }
181392      sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
181393      p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
181394    }
181395    p->nTotalRow++;
181396
181397    if( rc==SQLITE_OK ){
181398      rc = fts5StorageInsertDocsize(p, iRowid, &buf);
181399    }
181400  }
181401  sqlite3_free(buf.p);
181402
181403  /* Write the averages record */
181404  if( rc==SQLITE_OK ){
181405    rc = fts5StorageSaveTotals(p);
181406  }
181407  return rc;
181408}
181409
181410static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
181411  return sqlite3Fts5IndexOptimize(p->pIndex);
181412}
181413
181414static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
181415  return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
181416}
181417
181418/*
181419** Allocate a new rowid. This is used for "external content" tables when
181420** a NULL value is inserted into the rowid column. The new rowid is allocated
181421** by inserting a dummy row into the %_docsize table. The dummy will be
181422** overwritten later.
181423**
181424** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
181425** this case the user is required to provide a rowid explicitly.
181426*/
181427static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
181428  int rc = SQLITE_MISMATCH;
181429  if( p->pConfig->bColumnsize ){
181430    sqlite3_stmt *pReplace = 0;
181431    rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
181432    if( rc==SQLITE_OK ){
181433      sqlite3_bind_null(pReplace, 1);
181434      sqlite3_bind_null(pReplace, 2);
181435      sqlite3_step(pReplace);
181436      rc = sqlite3_reset(pReplace);
181437    }
181438    if( rc==SQLITE_OK ){
181439      *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
181440    }
181441  }
181442  return rc;
181443}
181444
181445/*
181446** Insert a new row into the FTS content table.
181447*/
181448static int sqlite3Fts5StorageContentInsert(
181449  Fts5Storage *p,
181450  sqlite3_value **apVal,
181451  i64 *piRowid
181452){
181453  Fts5Config *pConfig = p->pConfig;
181454  int rc = SQLITE_OK;
181455
181456  /* Insert the new row into the %_content table. */
181457  if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
181458    if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
181459      *piRowid = sqlite3_value_int64(apVal[1]);
181460    }else{
181461      rc = fts5StorageNewRowid(p, piRowid);
181462    }
181463  }else{
181464    sqlite3_stmt *pInsert = 0;    /* Statement to write %_content table */
181465    int i;                        /* Counter variable */
181466#if 0
181467    if( eConflict==SQLITE_REPLACE ){
181468      eStmt = FTS5_STMT_REPLACE_CONTENT;
181469      rc = fts5StorageDeleteFromIndex(p, sqlite3_value_int64(apVal[1]));
181470    }else{
181471      eStmt = FTS5_STMT_INSERT_CONTENT;
181472    }
181473#endif
181474    if( rc==SQLITE_OK ){
181475      rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
181476    }
181477    for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
181478      rc = sqlite3_bind_value(pInsert, i, apVal[i]);
181479    }
181480    if( rc==SQLITE_OK ){
181481      sqlite3_step(pInsert);
181482      rc = sqlite3_reset(pInsert);
181483    }
181484    *piRowid = sqlite3_last_insert_rowid(pConfig->db);
181485  }
181486
181487  return rc;
181488}
181489
181490/*
181491** Insert new entries into the FTS index and %_docsize table.
181492*/
181493static int sqlite3Fts5StorageIndexInsert(
181494  Fts5Storage *p,
181495  sqlite3_value **apVal,
181496  i64 iRowid
181497){
181498  Fts5Config *pConfig = p->pConfig;
181499  int rc = SQLITE_OK;             /* Return code */
181500  Fts5InsertCtx ctx;              /* Tokenization callback context object */
181501  Fts5Buffer buf;                 /* Buffer used to build up %_docsize blob */
181502
181503  memset(&buf, 0, sizeof(Fts5Buffer));
181504  ctx.pStorage = p;
181505  rc = fts5StorageLoadTotals(p, 1);
181506
181507  if( rc==SQLITE_OK ){
181508    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
181509  }
181510  for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
181511    ctx.szCol = 0;
181512    if( pConfig->abUnindexed[ctx.iCol]==0 ){
181513      rc = sqlite3Fts5Tokenize(pConfig,
181514          FTS5_TOKENIZE_DOCUMENT,
181515          (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
181516          sqlite3_value_bytes(apVal[ctx.iCol+2]),
181517          (void*)&ctx,
181518          fts5StorageInsertCallback
181519      );
181520    }
181521    sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
181522    p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
181523  }
181524  p->nTotalRow++;
181525
181526  /* Write the %_docsize record */
181527  if( rc==SQLITE_OK ){
181528    rc = fts5StorageInsertDocsize(p, iRowid, &buf);
181529  }
181530  sqlite3_free(buf.p);
181531
181532  /* Write the averages record */
181533  if( rc==SQLITE_OK ){
181534    rc = fts5StorageSaveTotals(p);
181535  }
181536
181537  return rc;
181538}
181539
181540static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
181541  Fts5Config *pConfig = p->pConfig;
181542  char *zSql;
181543  int rc;
181544
181545  zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
181546      pConfig->zDb, pConfig->zName, zSuffix
181547  );
181548  if( zSql==0 ){
181549    rc = SQLITE_NOMEM;
181550  }else{
181551    sqlite3_stmt *pCnt = 0;
181552    rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
181553    if( rc==SQLITE_OK ){
181554      if( SQLITE_ROW==sqlite3_step(pCnt) ){
181555        *pnRow = sqlite3_column_int64(pCnt, 0);
181556      }
181557      rc = sqlite3_finalize(pCnt);
181558    }
181559  }
181560
181561  sqlite3_free(zSql);
181562  return rc;
181563}
181564
181565/*
181566** Context object used by sqlite3Fts5StorageIntegrity().
181567*/
181568typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
181569struct Fts5IntegrityCtx {
181570  i64 iRowid;
181571  int iCol;
181572  int szCol;
181573  u64 cksum;
181574  Fts5Config *pConfig;
181575};
181576
181577/*
181578** Tokenization callback used by integrity check.
181579*/
181580static int fts5StorageIntegrityCallback(
181581  void *pContext,                 /* Pointer to Fts5InsertCtx object */
181582  int tflags,
181583  const char *pToken,             /* Buffer containing token */
181584  int nToken,                     /* Size of token in bytes */
181585  int iStart,                     /* Start offset of token */
181586  int iEnd                        /* End offset of token */
181587){
181588  Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
181589  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
181590    pCtx->szCol++;
181591  }
181592  pCtx->cksum ^= sqlite3Fts5IndexCksum(
181593      pCtx->pConfig, pCtx->iRowid, pCtx->iCol, pCtx->szCol-1, pToken, nToken
181594  );
181595  return SQLITE_OK;
181596}
181597
181598/*
181599** Check that the contents of the FTS index match that of the %_content
181600** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
181601** some other SQLite error code if an error occurs while attempting to
181602** determine this.
181603*/
181604static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
181605  Fts5Config *pConfig = p->pConfig;
181606  int rc;                         /* Return code */
181607  int *aColSize;                  /* Array of size pConfig->nCol */
181608  i64 *aTotalSize;                /* Array of size pConfig->nCol */
181609  Fts5IntegrityCtx ctx;
181610  sqlite3_stmt *pScan;
181611
181612  memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
181613  ctx.pConfig = p->pConfig;
181614  aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
181615  if( !aTotalSize ) return SQLITE_NOMEM;
181616  aColSize = (int*)&aTotalSize[pConfig->nCol];
181617  memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
181618
181619  /* Generate the expected index checksum based on the contents of the
181620  ** %_content table. This block stores the checksum in ctx.cksum. */
181621  rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
181622  if( rc==SQLITE_OK ){
181623    int rc2;
181624    while( SQLITE_ROW==sqlite3_step(pScan) ){
181625      int i;
181626      ctx.iRowid = sqlite3_column_int64(pScan, 0);
181627      ctx.szCol = 0;
181628      if( pConfig->bColumnsize ){
181629        rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
181630      }
181631      for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
181632        if( pConfig->abUnindexed[i] ) continue;
181633        ctx.iCol = i;
181634        ctx.szCol = 0;
181635        rc = sqlite3Fts5Tokenize(pConfig,
181636            FTS5_TOKENIZE_DOCUMENT,
181637            (const char*)sqlite3_column_text(pScan, i+1),
181638            sqlite3_column_bytes(pScan, i+1),
181639            (void*)&ctx,
181640            fts5StorageIntegrityCallback
181641        );
181642        if( pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
181643          rc = FTS5_CORRUPT;
181644        }
181645        aTotalSize[i] += ctx.szCol;
181646      }
181647      if( rc!=SQLITE_OK ) break;
181648    }
181649    rc2 = sqlite3_reset(pScan);
181650    if( rc==SQLITE_OK ) rc = rc2;
181651  }
181652
181653  /* Test that the "totals" (sometimes called "averages") record looks Ok */
181654  if( rc==SQLITE_OK ){
181655    int i;
181656    rc = fts5StorageLoadTotals(p, 0);
181657    for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
181658      if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
181659    }
181660  }
181661
181662  /* Check that the %_docsize and %_content tables contain the expected
181663  ** number of rows.  */
181664  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
181665    i64 nRow;
181666    rc = fts5StorageCount(p, "content", &nRow);
181667    if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
181668  }
181669  if( rc==SQLITE_OK && pConfig->bColumnsize ){
181670    i64 nRow;
181671    rc = fts5StorageCount(p, "docsize", &nRow);
181672    if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
181673  }
181674
181675  /* Pass the expected checksum down to the FTS index module. It will
181676  ** verify, amongst other things, that it matches the checksum generated by
181677  ** inspecting the index itself.  */
181678  if( rc==SQLITE_OK ){
181679    rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
181680  }
181681
181682  sqlite3_free(aTotalSize);
181683  return rc;
181684}
181685
181686/*
181687** Obtain an SQLite statement handle that may be used to read data from the
181688** %_content table.
181689*/
181690static int sqlite3Fts5StorageStmt(
181691  Fts5Storage *p,
181692  int eStmt,
181693  sqlite3_stmt **pp,
181694  char **pzErrMsg
181695){
181696  int rc;
181697  assert( eStmt==FTS5_STMT_SCAN_ASC
181698       || eStmt==FTS5_STMT_SCAN_DESC
181699       || eStmt==FTS5_STMT_LOOKUP
181700  );
181701  rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
181702  if( rc==SQLITE_OK ){
181703    assert( p->aStmt[eStmt]==*pp );
181704    p->aStmt[eStmt] = 0;
181705  }
181706  return rc;
181707}
181708
181709/*
181710** Release an SQLite statement handle obtained via an earlier call to
181711** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
181712** must match that passed to the sqlite3Fts5StorageStmt() call.
181713*/
181714static void sqlite3Fts5StorageStmtRelease(
181715  Fts5Storage *p,
181716  int eStmt,
181717  sqlite3_stmt *pStmt
181718){
181719  assert( eStmt==FTS5_STMT_SCAN_ASC
181720       || eStmt==FTS5_STMT_SCAN_DESC
181721       || eStmt==FTS5_STMT_LOOKUP
181722  );
181723  if( p->aStmt[eStmt]==0 ){
181724    sqlite3_reset(pStmt);
181725    p->aStmt[eStmt] = pStmt;
181726  }else{
181727    sqlite3_finalize(pStmt);
181728  }
181729}
181730
181731static int fts5StorageDecodeSizeArray(
181732  int *aCol, int nCol,            /* Array to populate */
181733  const u8 *aBlob, int nBlob      /* Record to read varints from */
181734){
181735  int i;
181736  int iOff = 0;
181737  for(i=0; i<nCol; i++){
181738    if( iOff>=nBlob ) return 1;
181739    iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
181740  }
181741  return (iOff!=nBlob);
181742}
181743
181744/*
181745** Argument aCol points to an array of integers containing one entry for
181746** each table column. This function reads the %_docsize record for the
181747** specified rowid and populates aCol[] with the results.
181748**
181749** An SQLite error code is returned if an error occurs, or SQLITE_OK
181750** otherwise.
181751*/
181752static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
181753  int nCol = p->pConfig->nCol;    /* Number of user columns in table */
181754  sqlite3_stmt *pLookup = 0;      /* Statement to query %_docsize */
181755  int rc;                         /* Return Code */
181756
181757  assert( p->pConfig->bColumnsize );
181758  rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
181759  if( rc==SQLITE_OK ){
181760    int bCorrupt = 1;
181761    sqlite3_bind_int64(pLookup, 1, iRowid);
181762    if( SQLITE_ROW==sqlite3_step(pLookup) ){
181763      const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
181764      int nBlob = sqlite3_column_bytes(pLookup, 0);
181765      if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
181766        bCorrupt = 0;
181767      }
181768    }
181769    rc = sqlite3_reset(pLookup);
181770    if( bCorrupt && rc==SQLITE_OK ){
181771      rc = FTS5_CORRUPT;
181772    }
181773  }
181774
181775  return rc;
181776}
181777
181778static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
181779  int rc = fts5StorageLoadTotals(p, 0);
181780  if( rc==SQLITE_OK ){
181781    *pnToken = 0;
181782    if( iCol<0 ){
181783      int i;
181784      for(i=0; i<p->pConfig->nCol; i++){
181785        *pnToken += p->aTotalSize[i];
181786      }
181787    }else if( iCol<p->pConfig->nCol ){
181788      *pnToken = p->aTotalSize[iCol];
181789    }else{
181790      rc = SQLITE_RANGE;
181791    }
181792  }
181793  return rc;
181794}
181795
181796static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
181797  int rc = fts5StorageLoadTotals(p, 0);
181798  if( rc==SQLITE_OK ){
181799    *pnRow = p->nTotalRow;
181800  }
181801  return rc;
181802}
181803
181804/*
181805** Flush any data currently held in-memory to disk.
181806*/
181807static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit){
181808  if( bCommit && p->bTotalsValid ){
181809    int rc = fts5StorageSaveTotals(p);
181810    p->bTotalsValid = 0;
181811    if( rc!=SQLITE_OK ) return rc;
181812  }
181813  return sqlite3Fts5IndexSync(p->pIndex, bCommit);
181814}
181815
181816static int sqlite3Fts5StorageRollback(Fts5Storage *p){
181817  p->bTotalsValid = 0;
181818  return sqlite3Fts5IndexRollback(p->pIndex);
181819}
181820
181821static int sqlite3Fts5StorageConfigValue(
181822  Fts5Storage *p,
181823  const char *z,
181824  sqlite3_value *pVal,
181825  int iVal
181826){
181827  sqlite3_stmt *pReplace = 0;
181828  int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
181829  if( rc==SQLITE_OK ){
181830    sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
181831    if( pVal ){
181832      sqlite3_bind_value(pReplace, 2, pVal);
181833    }else{
181834      sqlite3_bind_int(pReplace, 2, iVal);
181835    }
181836    sqlite3_step(pReplace);
181837    rc = sqlite3_reset(pReplace);
181838  }
181839  if( rc==SQLITE_OK && pVal ){
181840    int iNew = p->pConfig->iCookie + 1;
181841    rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
181842    if( rc==SQLITE_OK ){
181843      p->pConfig->iCookie = iNew;
181844    }
181845  }
181846  return rc;
181847}
181848
181849
181850
181851/*
181852** 2014 May 31
181853**
181854** The author disclaims copyright to this source code.  In place of
181855** a legal notice, here is a blessing:
181856**
181857**    May you do good and not evil.
181858**    May you find forgiveness for yourself and forgive others.
181859**    May you share freely, never taking more than you give.
181860**
181861******************************************************************************
181862*/
181863
181864
181865
181866/**************************************************************************
181867** Start of ascii tokenizer implementation.
181868*/
181869
181870/*
181871** For tokenizers with no "unicode" modifier, the set of token characters
181872** is the same as the set of ASCII range alphanumeric characters.
181873*/
181874static unsigned char aAsciiTokenChar[128] = {
181875  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00..0x0F */
181876  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x10..0x1F */
181877  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20..0x2F */
181878  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30..0x3F */
181879  0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40..0x4F */
181880  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x50..0x5F */
181881  0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60..0x6F */
181882  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x70..0x7F */
181883};
181884
181885typedef struct AsciiTokenizer AsciiTokenizer;
181886struct AsciiTokenizer {
181887  unsigned char aTokenChar[128];
181888};
181889
181890static void fts5AsciiAddExceptions(
181891  AsciiTokenizer *p,
181892  const char *zArg,
181893  int bTokenChars
181894){
181895  int i;
181896  for(i=0; zArg[i]; i++){
181897    if( (zArg[i] & 0x80)==0 ){
181898      p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
181899    }
181900  }
181901}
181902
181903/*
181904** Delete a "ascii" tokenizer.
181905*/
181906static void fts5AsciiDelete(Fts5Tokenizer *p){
181907  sqlite3_free(p);
181908}
181909
181910/*
181911** Create an "ascii" tokenizer.
181912*/
181913static int fts5AsciiCreate(
181914  void *pCtx,
181915  const char **azArg, int nArg,
181916  Fts5Tokenizer **ppOut
181917){
181918  int rc = SQLITE_OK;
181919  AsciiTokenizer *p = 0;
181920  if( nArg%2 ){
181921    rc = SQLITE_ERROR;
181922  }else{
181923    p = sqlite3_malloc(sizeof(AsciiTokenizer));
181924    if( p==0 ){
181925      rc = SQLITE_NOMEM;
181926    }else{
181927      int i;
181928      memset(p, 0, sizeof(AsciiTokenizer));
181929      memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
181930      for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
181931        const char *zArg = azArg[i+1];
181932        if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
181933          fts5AsciiAddExceptions(p, zArg, 1);
181934        }else
181935        if( 0==sqlite3_stricmp(azArg[i], "separators") ){
181936          fts5AsciiAddExceptions(p, zArg, 0);
181937        }else{
181938          rc = SQLITE_ERROR;
181939        }
181940      }
181941      if( rc!=SQLITE_OK ){
181942        fts5AsciiDelete((Fts5Tokenizer*)p);
181943        p = 0;
181944      }
181945    }
181946  }
181947
181948  *ppOut = (Fts5Tokenizer*)p;
181949  return rc;
181950}
181951
181952
181953static void asciiFold(char *aOut, const char *aIn, int nByte){
181954  int i;
181955  for(i=0; i<nByte; i++){
181956    char c = aIn[i];
181957    if( c>='A' && c<='Z' ) c += 32;
181958    aOut[i] = c;
181959  }
181960}
181961
181962/*
181963** Tokenize some text using the ascii tokenizer.
181964*/
181965static int fts5AsciiTokenize(
181966  Fts5Tokenizer *pTokenizer,
181967  void *pCtx,
181968  int flags,
181969  const char *pText, int nText,
181970  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
181971){
181972  AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
181973  int rc = SQLITE_OK;
181974  int ie;
181975  int is = 0;
181976
181977  char aFold[64];
181978  int nFold = sizeof(aFold);
181979  char *pFold = aFold;
181980  unsigned char *a = p->aTokenChar;
181981
181982  while( is<nText && rc==SQLITE_OK ){
181983    int nByte;
181984
181985    /* Skip any leading divider characters. */
181986    while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
181987      is++;
181988    }
181989    if( is==nText ) break;
181990
181991    /* Count the token characters */
181992    ie = is+1;
181993    while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
181994      ie++;
181995    }
181996
181997    /* Fold to lower case */
181998    nByte = ie-is;
181999    if( nByte>nFold ){
182000      if( pFold!=aFold ) sqlite3_free(pFold);
182001      pFold = sqlite3_malloc(nByte*2);
182002      if( pFold==0 ){
182003        rc = SQLITE_NOMEM;
182004        break;
182005      }
182006      nFold = nByte*2;
182007    }
182008    asciiFold(pFold, &pText[is], nByte);
182009
182010    /* Invoke the token callback */
182011    rc = xToken(pCtx, 0, pFold, nByte, is, ie);
182012    is = ie+1;
182013  }
182014
182015  if( pFold!=aFold ) sqlite3_free(pFold);
182016  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
182017  return rc;
182018}
182019
182020/**************************************************************************
182021** Start of unicode61 tokenizer implementation.
182022*/
182023
182024
182025/*
182026** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
182027** from the sqlite3 source file utf.c. If this file is compiled as part
182028** of the amalgamation, they are not required.
182029*/
182030#ifndef SQLITE_AMALGAMATION
182031
182032static const unsigned char sqlite3Utf8Trans1[] = {
182033  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
182034  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
182035  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
182036  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
182037  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
182038  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
182039  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
182040  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
182041};
182042
182043#define READ_UTF8(zIn, zTerm, c)                           \
182044  c = *(zIn++);                                            \
182045  if( c>=0xc0 ){                                           \
182046    c = sqlite3Utf8Trans1[c-0xc0];                         \
182047    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
182048      c = (c<<6) + (0x3f & *(zIn++));                      \
182049    }                                                      \
182050    if( c<0x80                                             \
182051        || (c&0xFFFFF800)==0xD800                          \
182052        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
182053  }
182054
182055
182056#define WRITE_UTF8(zOut, c) {                          \
182057  if( c<0x00080 ){                                     \
182058    *zOut++ = (unsigned char)(c&0xFF);                 \
182059  }                                                    \
182060  else if( c<0x00800 ){                                \
182061    *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F);     \
182062    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
182063  }                                                    \
182064  else if( c<0x10000 ){                                \
182065    *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F);    \
182066    *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
182067    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
182068  }else{                                               \
182069    *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07);  \
182070    *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F);  \
182071    *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
182072    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
182073  }                                                    \
182074}
182075
182076#endif /* ifndef SQLITE_AMALGAMATION */
182077
182078typedef struct Unicode61Tokenizer Unicode61Tokenizer;
182079struct Unicode61Tokenizer {
182080  unsigned char aTokenChar[128];  /* ASCII range token characters */
182081  char *aFold;                    /* Buffer to fold text into */
182082  int nFold;                      /* Size of aFold[] in bytes */
182083  int bRemoveDiacritic;           /* True if remove_diacritics=1 is set */
182084  int nException;
182085  int *aiException;
182086};
182087
182088static int fts5UnicodeAddExceptions(
182089  Unicode61Tokenizer *p,          /* Tokenizer object */
182090  const char *z,                  /* Characters to treat as exceptions */
182091  int bTokenChars                 /* 1 for 'tokenchars', 0 for 'separators' */
182092){
182093  int rc = SQLITE_OK;
182094  int n = strlen(z);
182095  int *aNew;
182096
182097  if( n>0 ){
182098    aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
182099    if( aNew ){
182100      int nNew = p->nException;
182101      const unsigned char *zCsr = (const unsigned char*)z;
182102      const unsigned char *zTerm = (const unsigned char*)&z[n];
182103      while( zCsr<zTerm ){
182104        int iCode;
182105        int bToken;
182106        READ_UTF8(zCsr, zTerm, iCode);
182107        if( iCode<128 ){
182108          p->aTokenChar[iCode] = bTokenChars;
182109        }else{
182110          bToken = sqlite3Fts5UnicodeIsalnum(iCode);
182111          assert( (bToken==0 || bToken==1) );
182112          assert( (bTokenChars==0 || bTokenChars==1) );
182113          if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
182114            int i;
182115            for(i=0; i<nNew; i++){
182116              if( aNew[i]>iCode ) break;
182117            }
182118            memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
182119            aNew[i] = iCode;
182120            nNew++;
182121          }
182122        }
182123      }
182124      p->aiException = aNew;
182125      p->nException = nNew;
182126    }else{
182127      rc = SQLITE_NOMEM;
182128    }
182129  }
182130
182131  return rc;
182132}
182133
182134/*
182135** Return true if the p->aiException[] array contains the value iCode.
182136*/
182137static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
182138  if( p->nException>0 ){
182139    int *a = p->aiException;
182140    int iLo = 0;
182141    int iHi = p->nException-1;
182142
182143    while( iHi>=iLo ){
182144      int iTest = (iHi + iLo) / 2;
182145      if( iCode==a[iTest] ){
182146        return 1;
182147      }else if( iCode>a[iTest] ){
182148        iLo = iTest+1;
182149      }else{
182150        iHi = iTest-1;
182151      }
182152    }
182153  }
182154
182155  return 0;
182156}
182157
182158/*
182159** Delete a "unicode61" tokenizer.
182160*/
182161static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
182162  if( pTok ){
182163    Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
182164    sqlite3_free(p->aiException);
182165    sqlite3_free(p->aFold);
182166    sqlite3_free(p);
182167  }
182168  return;
182169}
182170
182171/*
182172** Create a "unicode61" tokenizer.
182173*/
182174static int fts5UnicodeCreate(
182175  void *pCtx,
182176  const char **azArg, int nArg,
182177  Fts5Tokenizer **ppOut
182178){
182179  int rc = SQLITE_OK;             /* Return code */
182180  Unicode61Tokenizer *p = 0;      /* New tokenizer object */
182181
182182  if( nArg%2 ){
182183    rc = SQLITE_ERROR;
182184  }else{
182185    p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
182186    if( p ){
182187      int i;
182188      memset(p, 0, sizeof(Unicode61Tokenizer));
182189      memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
182190      p->bRemoveDiacritic = 1;
182191      p->nFold = 64;
182192      p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
182193      if( p->aFold==0 ){
182194        rc = SQLITE_NOMEM;
182195      }
182196      for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
182197        const char *zArg = azArg[i+1];
182198        if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
182199          if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
182200            rc = SQLITE_ERROR;
182201          }
182202          p->bRemoveDiacritic = (zArg[0]=='1');
182203        }else
182204        if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
182205          rc = fts5UnicodeAddExceptions(p, zArg, 1);
182206        }else
182207        if( 0==sqlite3_stricmp(azArg[i], "separators") ){
182208          rc = fts5UnicodeAddExceptions(p, zArg, 0);
182209        }else{
182210          rc = SQLITE_ERROR;
182211        }
182212      }
182213    }else{
182214      rc = SQLITE_NOMEM;
182215    }
182216    if( rc!=SQLITE_OK ){
182217      fts5UnicodeDelete((Fts5Tokenizer*)p);
182218      p = 0;
182219    }
182220    *ppOut = (Fts5Tokenizer*)p;
182221  }
182222  return rc;
182223}
182224
182225/*
182226** Return true if, for the purposes of tokenizing with the tokenizer
182227** passed as the first argument, codepoint iCode is considered a token
182228** character (not a separator).
182229*/
182230static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
182231  assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
182232  return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode);
182233}
182234
182235static int fts5UnicodeTokenize(
182236  Fts5Tokenizer *pTokenizer,
182237  void *pCtx,
182238  int flags,
182239  const char *pText, int nText,
182240  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
182241){
182242  Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
182243  int rc = SQLITE_OK;
182244  unsigned char *a = p->aTokenChar;
182245
182246  unsigned char *zTerm = (unsigned char*)&pText[nText];
182247  unsigned char *zCsr = (unsigned char *)pText;
182248
182249  /* Output buffer */
182250  char *aFold = p->aFold;
182251  int nFold = p->nFold;
182252  const char *pEnd = &aFold[nFold-6];
182253
182254  /* Each iteration of this loop gobbles up a contiguous run of separators,
182255  ** then the next token.  */
182256  while( rc==SQLITE_OK ){
182257    int iCode;                    /* non-ASCII codepoint read from input */
182258    char *zOut = aFold;
182259    int is;
182260    int ie;
182261
182262    /* Skip any separator characters. */
182263    while( 1 ){
182264      if( zCsr>=zTerm ) goto tokenize_done;
182265      if( *zCsr & 0x80 ) {
182266        /* A character outside of the ascii range. Skip past it if it is
182267        ** a separator character. Or break out of the loop if it is not. */
182268        is = zCsr - (unsigned char*)pText;
182269        READ_UTF8(zCsr, zTerm, iCode);
182270        if( fts5UnicodeIsAlnum(p, iCode) ){
182271          goto non_ascii_tokenchar;
182272        }
182273      }else{
182274        if( a[*zCsr] ){
182275          is = zCsr - (unsigned char*)pText;
182276          goto ascii_tokenchar;
182277        }
182278        zCsr++;
182279      }
182280    }
182281
182282    /* Run through the tokenchars. Fold them into the output buffer along
182283    ** the way.  */
182284    while( zCsr<zTerm ){
182285
182286      /* Grow the output buffer so that there is sufficient space to fit the
182287      ** largest possible utf-8 character.  */
182288      if( zOut>pEnd ){
182289        aFold = sqlite3_malloc(nFold*2);
182290        if( aFold==0 ){
182291          rc = SQLITE_NOMEM;
182292          goto tokenize_done;
182293        }
182294        zOut = &aFold[zOut - p->aFold];
182295        memcpy(aFold, p->aFold, nFold);
182296        sqlite3_free(p->aFold);
182297        p->aFold = aFold;
182298        p->nFold = nFold = nFold*2;
182299        pEnd = &aFold[nFold-6];
182300      }
182301
182302      if( *zCsr & 0x80 ){
182303        /* An non-ascii-range character. Fold it into the output buffer if
182304        ** it is a token character, or break out of the loop if it is not. */
182305        READ_UTF8(zCsr, zTerm, iCode);
182306        if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
182307 non_ascii_tokenchar:
182308          iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
182309          if( iCode ) WRITE_UTF8(zOut, iCode);
182310        }else{
182311          break;
182312        }
182313      }else if( a[*zCsr]==0 ){
182314        /* An ascii-range separator character. End of token. */
182315        break;
182316      }else{
182317 ascii_tokenchar:
182318        if( *zCsr>='A' && *zCsr<='Z' ){
182319          *zOut++ = *zCsr + 32;
182320        }else{
182321          *zOut++ = *zCsr;
182322        }
182323        zCsr++;
182324      }
182325      ie = zCsr - (unsigned char*)pText;
182326    }
182327
182328    /* Invoke the token callback */
182329    rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
182330  }
182331
182332 tokenize_done:
182333  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
182334  return rc;
182335}
182336
182337/**************************************************************************
182338** Start of porter stemmer implementation.
182339*/
182340
182341/* Any tokens larger than this (in bytes) are passed through without
182342** stemming. */
182343#define FTS5_PORTER_MAX_TOKEN 64
182344
182345typedef struct PorterTokenizer PorterTokenizer;
182346struct PorterTokenizer {
182347  fts5_tokenizer tokenizer;       /* Parent tokenizer module */
182348  Fts5Tokenizer *pTokenizer;      /* Parent tokenizer instance */
182349  char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
182350};
182351
182352/*
182353** Delete a "porter" tokenizer.
182354*/
182355static void fts5PorterDelete(Fts5Tokenizer *pTok){
182356  if( pTok ){
182357    PorterTokenizer *p = (PorterTokenizer*)pTok;
182358    if( p->pTokenizer ){
182359      p->tokenizer.xDelete(p->pTokenizer);
182360    }
182361    sqlite3_free(p);
182362  }
182363}
182364
182365/*
182366** Create a "porter" tokenizer.
182367*/
182368static int fts5PorterCreate(
182369  void *pCtx,
182370  const char **azArg, int nArg,
182371  Fts5Tokenizer **ppOut
182372){
182373  fts5_api *pApi = (fts5_api*)pCtx;
182374  int rc = SQLITE_OK;
182375  PorterTokenizer *pRet;
182376  void *pUserdata = 0;
182377  const char *zBase = "unicode61";
182378
182379  if( nArg>0 ){
182380    zBase = azArg[0];
182381  }
182382
182383  pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
182384  if( pRet ){
182385    memset(pRet, 0, sizeof(PorterTokenizer));
182386    rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
182387  }else{
182388    rc = SQLITE_NOMEM;
182389  }
182390  if( rc==SQLITE_OK ){
182391    int nArg2 = (nArg>0 ? nArg-1 : 0);
182392    const char **azArg2 = (nArg2 ? &azArg[1] : 0);
182393    rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
182394  }
182395
182396  if( rc!=SQLITE_OK ){
182397    fts5PorterDelete((Fts5Tokenizer*)pRet);
182398    pRet = 0;
182399  }
182400  *ppOut = (Fts5Tokenizer*)pRet;
182401  return rc;
182402}
182403
182404typedef struct PorterContext PorterContext;
182405struct PorterContext {
182406  void *pCtx;
182407  int (*xToken)(void*, int, const char*, int, int, int);
182408  char *aBuf;
182409};
182410
182411typedef struct PorterRule PorterRule;
182412struct PorterRule {
182413  const char *zSuffix;
182414  int nSuffix;
182415  int (*xCond)(char *zStem, int nStem);
182416  const char *zOutput;
182417  int nOutput;
182418};
182419
182420#if 0
182421static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
182422  int ret = -1;
182423  int nBuf = *pnBuf;
182424  PorterRule *p;
182425
182426  for(p=aRule; p->zSuffix; p++){
182427    assert( strlen(p->zSuffix)==p->nSuffix );
182428    assert( strlen(p->zOutput)==p->nOutput );
182429    if( nBuf<p->nSuffix ) continue;
182430    if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
182431  }
182432
182433  if( p->zSuffix ){
182434    int nStem = nBuf - p->nSuffix;
182435    if( p->xCond==0 || p->xCond(aBuf, nStem) ){
182436      memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
182437      *pnBuf = nStem + p->nOutput;
182438      ret = p - aRule;
182439    }
182440  }
182441
182442  return ret;
182443}
182444#endif
182445
182446static int fts5PorterIsVowel(char c, int bYIsVowel){
182447  return (
182448      c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
182449  );
182450}
182451
182452static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
182453  int i;
182454  int bCons = bPrevCons;
182455
182456  /* Scan for a vowel */
182457  for(i=0; i<nStem; i++){
182458    if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
182459  }
182460
182461  /* Scan for a consonent */
182462  for(i++; i<nStem; i++){
182463    if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
182464  }
182465  return 0;
182466}
182467
182468/* porter rule condition: (m > 0) */
182469static int fts5Porter_MGt0(char *zStem, int nStem){
182470  return !!fts5PorterGobbleVC(zStem, nStem, 0);
182471}
182472
182473/* porter rule condition: (m > 1) */
182474static int fts5Porter_MGt1(char *zStem, int nStem){
182475  int n;
182476  n = fts5PorterGobbleVC(zStem, nStem, 0);
182477  if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
182478    return 1;
182479  }
182480  return 0;
182481}
182482
182483/* porter rule condition: (m = 1) */
182484static int fts5Porter_MEq1(char *zStem, int nStem){
182485  int n;
182486  n = fts5PorterGobbleVC(zStem, nStem, 0);
182487  if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
182488    return 1;
182489  }
182490  return 0;
182491}
182492
182493/* porter rule condition: (*o) */
182494static int fts5Porter_Ostar(char *zStem, int nStem){
182495  if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
182496    return 0;
182497  }else{
182498    int i;
182499    int mask = 0;
182500    int bCons = 0;
182501    for(i=0; i<nStem; i++){
182502      bCons = !fts5PorterIsVowel(zStem[i], bCons);
182503      assert( bCons==0 || bCons==1 );
182504      mask = (mask << 1) + bCons;
182505    }
182506    return ((mask & 0x0007)==0x0005);
182507  }
182508}
182509
182510/* porter rule condition: (m > 1 and (*S or *T)) */
182511static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
182512  assert( nStem>0 );
182513  return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
182514      && fts5Porter_MGt1(zStem, nStem);
182515}
182516
182517/* porter rule condition: (*v*) */
182518static int fts5Porter_Vowel(char *zStem, int nStem){
182519  int i;
182520  for(i=0; i<nStem; i++){
182521    if( fts5PorterIsVowel(zStem[i], i>0) ){
182522      return 1;
182523    }
182524  }
182525  return 0;
182526}
182527
182528
182529/**************************************************************************
182530***************************************************************************
182531** GENERATED CODE STARTS HERE (mkportersteps.tcl)
182532*/
182533
182534static int fts5PorterStep4(char *aBuf, int *pnBuf){
182535  int ret = 0;
182536  int nBuf = *pnBuf;
182537  switch( aBuf[nBuf-2] ){
182538
182539    case 'a':
182540      if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
182541        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
182542          *pnBuf = nBuf - 2;
182543        }
182544      }
182545      break;
182546
182547    case 'c':
182548      if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
182549        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
182550          *pnBuf = nBuf - 4;
182551        }
182552      }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
182553        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
182554          *pnBuf = nBuf - 4;
182555        }
182556      }
182557      break;
182558
182559    case 'e':
182560      if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
182561        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
182562          *pnBuf = nBuf - 2;
182563        }
182564      }
182565      break;
182566
182567    case 'i':
182568      if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
182569        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
182570          *pnBuf = nBuf - 2;
182571        }
182572      }
182573      break;
182574
182575    case 'l':
182576      if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
182577        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
182578          *pnBuf = nBuf - 4;
182579        }
182580      }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
182581        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
182582          *pnBuf = nBuf - 4;
182583        }
182584      }
182585      break;
182586
182587    case 'n':
182588      if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
182589        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
182590          *pnBuf = nBuf - 3;
182591        }
182592      }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
182593        if( fts5Porter_MGt1(aBuf, nBuf-5) ){
182594          *pnBuf = nBuf - 5;
182595        }
182596      }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
182597        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
182598          *pnBuf = nBuf - 4;
182599        }
182600      }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
182601        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
182602          *pnBuf = nBuf - 3;
182603        }
182604      }
182605      break;
182606
182607    case 'o':
182608      if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
182609        if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
182610          *pnBuf = nBuf - 3;
182611        }
182612      }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
182613        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
182614          *pnBuf = nBuf - 2;
182615        }
182616      }
182617      break;
182618
182619    case 's':
182620      if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
182621        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
182622          *pnBuf = nBuf - 3;
182623        }
182624      }
182625      break;
182626
182627    case 't':
182628      if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
182629        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
182630          *pnBuf = nBuf - 3;
182631        }
182632      }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
182633        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
182634          *pnBuf = nBuf - 3;
182635        }
182636      }
182637      break;
182638
182639    case 'u':
182640      if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
182641        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
182642          *pnBuf = nBuf - 3;
182643        }
182644      }
182645      break;
182646
182647    case 'v':
182648      if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
182649        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
182650          *pnBuf = nBuf - 3;
182651        }
182652      }
182653      break;
182654
182655    case 'z':
182656      if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
182657        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
182658          *pnBuf = nBuf - 3;
182659        }
182660      }
182661      break;
182662
182663  }
182664  return ret;
182665}
182666
182667
182668static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
182669  int ret = 0;
182670  int nBuf = *pnBuf;
182671  switch( aBuf[nBuf-2] ){
182672
182673    case 'a':
182674      if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
182675        memcpy(&aBuf[nBuf-2], "ate", 3);
182676        *pnBuf = nBuf - 2 + 3;
182677        ret = 1;
182678      }
182679      break;
182680
182681    case 'b':
182682      if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
182683        memcpy(&aBuf[nBuf-2], "ble", 3);
182684        *pnBuf = nBuf - 2 + 3;
182685        ret = 1;
182686      }
182687      break;
182688
182689    case 'i':
182690      if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
182691        memcpy(&aBuf[nBuf-2], "ize", 3);
182692        *pnBuf = nBuf - 2 + 3;
182693        ret = 1;
182694      }
182695      break;
182696
182697  }
182698  return ret;
182699}
182700
182701
182702static int fts5PorterStep2(char *aBuf, int *pnBuf){
182703  int ret = 0;
182704  int nBuf = *pnBuf;
182705  switch( aBuf[nBuf-2] ){
182706
182707    case 'a':
182708      if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
182709        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
182710          memcpy(&aBuf[nBuf-7], "ate", 3);
182711          *pnBuf = nBuf - 7 + 3;
182712        }
182713      }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
182714        if( fts5Porter_MGt0(aBuf, nBuf-6) ){
182715          memcpy(&aBuf[nBuf-6], "tion", 4);
182716          *pnBuf = nBuf - 6 + 4;
182717        }
182718      }
182719      break;
182720
182721    case 'c':
182722      if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
182723        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
182724          memcpy(&aBuf[nBuf-4], "ence", 4);
182725          *pnBuf = nBuf - 4 + 4;
182726        }
182727      }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
182728        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
182729          memcpy(&aBuf[nBuf-4], "ance", 4);
182730          *pnBuf = nBuf - 4 + 4;
182731        }
182732      }
182733      break;
182734
182735    case 'e':
182736      if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
182737        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
182738          memcpy(&aBuf[nBuf-4], "ize", 3);
182739          *pnBuf = nBuf - 4 + 3;
182740        }
182741      }
182742      break;
182743
182744    case 'g':
182745      if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
182746        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
182747          memcpy(&aBuf[nBuf-4], "log", 3);
182748          *pnBuf = nBuf - 4 + 3;
182749        }
182750      }
182751      break;
182752
182753    case 'l':
182754      if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
182755        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
182756          memcpy(&aBuf[nBuf-3], "ble", 3);
182757          *pnBuf = nBuf - 3 + 3;
182758        }
182759      }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
182760        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
182761          memcpy(&aBuf[nBuf-4], "al", 2);
182762          *pnBuf = nBuf - 4 + 2;
182763        }
182764      }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
182765        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
182766          memcpy(&aBuf[nBuf-5], "ent", 3);
182767          *pnBuf = nBuf - 5 + 3;
182768        }
182769      }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
182770        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
182771          memcpy(&aBuf[nBuf-3], "e", 1);
182772          *pnBuf = nBuf - 3 + 1;
182773        }
182774      }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
182775        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
182776          memcpy(&aBuf[nBuf-5], "ous", 3);
182777          *pnBuf = nBuf - 5 + 3;
182778        }
182779      }
182780      break;
182781
182782    case 'o':
182783      if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
182784        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
182785          memcpy(&aBuf[nBuf-7], "ize", 3);
182786          *pnBuf = nBuf - 7 + 3;
182787        }
182788      }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
182789        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
182790          memcpy(&aBuf[nBuf-5], "ate", 3);
182791          *pnBuf = nBuf - 5 + 3;
182792        }
182793      }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
182794        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
182795          memcpy(&aBuf[nBuf-4], "ate", 3);
182796          *pnBuf = nBuf - 4 + 3;
182797        }
182798      }
182799      break;
182800
182801    case 's':
182802      if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
182803        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
182804          memcpy(&aBuf[nBuf-5], "al", 2);
182805          *pnBuf = nBuf - 5 + 2;
182806        }
182807      }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
182808        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
182809          memcpy(&aBuf[nBuf-7], "ive", 3);
182810          *pnBuf = nBuf - 7 + 3;
182811        }
182812      }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
182813        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
182814          memcpy(&aBuf[nBuf-7], "ful", 3);
182815          *pnBuf = nBuf - 7 + 3;
182816        }
182817      }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
182818        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
182819          memcpy(&aBuf[nBuf-7], "ous", 3);
182820          *pnBuf = nBuf - 7 + 3;
182821        }
182822      }
182823      break;
182824
182825    case 't':
182826      if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
182827        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
182828          memcpy(&aBuf[nBuf-5], "al", 2);
182829          *pnBuf = nBuf - 5 + 2;
182830        }
182831      }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
182832        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
182833          memcpy(&aBuf[nBuf-5], "ive", 3);
182834          *pnBuf = nBuf - 5 + 3;
182835        }
182836      }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
182837        if( fts5Porter_MGt0(aBuf, nBuf-6) ){
182838          memcpy(&aBuf[nBuf-6], "ble", 3);
182839          *pnBuf = nBuf - 6 + 3;
182840        }
182841      }
182842      break;
182843
182844  }
182845  return ret;
182846}
182847
182848
182849static int fts5PorterStep3(char *aBuf, int *pnBuf){
182850  int ret = 0;
182851  int nBuf = *pnBuf;
182852  switch( aBuf[nBuf-2] ){
182853
182854    case 'a':
182855      if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
182856        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
182857          memcpy(&aBuf[nBuf-4], "ic", 2);
182858          *pnBuf = nBuf - 4 + 2;
182859        }
182860      }
182861      break;
182862
182863    case 's':
182864      if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
182865        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
182866          *pnBuf = nBuf - 4;
182867        }
182868      }
182869      break;
182870
182871    case 't':
182872      if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
182873        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
182874          memcpy(&aBuf[nBuf-5], "ic", 2);
182875          *pnBuf = nBuf - 5 + 2;
182876        }
182877      }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
182878        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
182879          memcpy(&aBuf[nBuf-5], "ic", 2);
182880          *pnBuf = nBuf - 5 + 2;
182881        }
182882      }
182883      break;
182884
182885    case 'u':
182886      if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
182887        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
182888          *pnBuf = nBuf - 3;
182889        }
182890      }
182891      break;
182892
182893    case 'v':
182894      if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
182895        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
182896          *pnBuf = nBuf - 5;
182897        }
182898      }
182899      break;
182900
182901    case 'z':
182902      if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
182903        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
182904          memcpy(&aBuf[nBuf-5], "al", 2);
182905          *pnBuf = nBuf - 5 + 2;
182906        }
182907      }
182908      break;
182909
182910  }
182911  return ret;
182912}
182913
182914
182915static int fts5PorterStep1B(char *aBuf, int *pnBuf){
182916  int ret = 0;
182917  int nBuf = *pnBuf;
182918  switch( aBuf[nBuf-2] ){
182919
182920    case 'e':
182921      if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
182922        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
182923          memcpy(&aBuf[nBuf-3], "ee", 2);
182924          *pnBuf = nBuf - 3 + 2;
182925        }
182926      }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
182927        if( fts5Porter_Vowel(aBuf, nBuf-2) ){
182928          *pnBuf = nBuf - 2;
182929          ret = 1;
182930        }
182931      }
182932      break;
182933
182934    case 'n':
182935      if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
182936        if( fts5Porter_Vowel(aBuf, nBuf-3) ){
182937          *pnBuf = nBuf - 3;
182938          ret = 1;
182939        }
182940      }
182941      break;
182942
182943  }
182944  return ret;
182945}
182946
182947/*
182948** GENERATED CODE ENDS HERE (mkportersteps.tcl)
182949***************************************************************************
182950**************************************************************************/
182951
182952static void fts5PorterStep1A(char *aBuf, int *pnBuf){
182953  int nBuf = *pnBuf;
182954  if( aBuf[nBuf-1]=='s' ){
182955    if( aBuf[nBuf-2]=='e' ){
182956      if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
182957       || (nBuf>3 && aBuf[nBuf-3]=='i' )
182958      ){
182959        *pnBuf = nBuf-2;
182960      }else{
182961        *pnBuf = nBuf-1;
182962      }
182963    }
182964    else if( aBuf[nBuf-2]!='s' ){
182965      *pnBuf = nBuf-1;
182966    }
182967  }
182968}
182969
182970static int fts5PorterCb(
182971  void *pCtx,
182972  int tflags,
182973  const char *pToken,
182974  int nToken,
182975  int iStart,
182976  int iEnd
182977){
182978  PorterContext *p = (PorterContext*)pCtx;
182979
182980  char *aBuf;
182981  int nBuf;
182982
182983  if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
182984  aBuf = p->aBuf;
182985  nBuf = nToken;
182986  memcpy(aBuf, pToken, nBuf);
182987
182988  /* Step 1. */
182989  fts5PorterStep1A(aBuf, &nBuf);
182990  if( fts5PorterStep1B(aBuf, &nBuf) ){
182991    if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
182992      char c = aBuf[nBuf-1];
182993      if( fts5PorterIsVowel(c, 0)==0
182994       && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
182995      ){
182996        nBuf--;
182997      }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
182998        aBuf[nBuf++] = 'e';
182999      }
183000    }
183001  }
183002
183003  /* Step 1C. */
183004  if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
183005    aBuf[nBuf-1] = 'i';
183006  }
183007
183008  /* Steps 2 through 4. */
183009  fts5PorterStep2(aBuf, &nBuf);
183010  fts5PorterStep3(aBuf, &nBuf);
183011  fts5PorterStep4(aBuf, &nBuf);
183012
183013  /* Step 5a. */
183014  assert( nBuf>0 );
183015  if( aBuf[nBuf-1]=='e' ){
183016    if( fts5Porter_MGt1(aBuf, nBuf-1)
183017     || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
183018    ){
183019      nBuf--;
183020    }
183021  }
183022
183023  /* Step 5b. */
183024  if( nBuf>1 && aBuf[nBuf-1]=='l'
183025   && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
183026  ){
183027    nBuf--;
183028  }
183029
183030  return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
183031
183032 pass_through:
183033  return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
183034}
183035
183036/*
183037** Tokenize using the porter tokenizer.
183038*/
183039static int fts5PorterTokenize(
183040  Fts5Tokenizer *pTokenizer,
183041  void *pCtx,
183042  int flags,
183043  const char *pText, int nText,
183044  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
183045){
183046  PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
183047  PorterContext sCtx;
183048  sCtx.xToken = xToken;
183049  sCtx.pCtx = pCtx;
183050  sCtx.aBuf = p->aBuf;
183051  return p->tokenizer.xTokenize(
183052      p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
183053  );
183054}
183055
183056/*
183057** Register all built-in tokenizers with FTS5.
183058*/
183059static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
183060  struct BuiltinTokenizer {
183061    const char *zName;
183062    fts5_tokenizer x;
183063  } aBuiltin[] = {
183064    { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
183065    { "ascii",     {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
183066    { "porter",    {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
183067  };
183068
183069  int rc = SQLITE_OK;             /* Return code */
183070  int i;                          /* To iterate through builtin functions */
183071
183072  for(i=0; rc==SQLITE_OK && i<sizeof(aBuiltin)/sizeof(aBuiltin[0]); i++){
183073    rc = pApi->xCreateTokenizer(pApi,
183074        aBuiltin[i].zName,
183075        (void*)pApi,
183076        &aBuiltin[i].x,
183077        0
183078    );
183079  }
183080
183081  return rc;
183082}
183083
183084
183085
183086/*
183087** 2012 May 25
183088**
183089** The author disclaims copyright to this source code.  In place of
183090** a legal notice, here is a blessing:
183091**
183092**    May you do good and not evil.
183093**    May you find forgiveness for yourself and forgive others.
183094**    May you share freely, never taking more than you give.
183095**
183096******************************************************************************
183097*/
183098
183099/*
183100** DO NOT EDIT THIS MACHINE GENERATED FILE.
183101*/
183102
183103
183104/* #include <assert.h> */
183105
183106/*
183107** Return true if the argument corresponds to a unicode codepoint
183108** classified as either a letter or a number. Otherwise false.
183109**
183110** The results are undefined if the value passed to this function
183111** is less than zero.
183112*/
183113static int sqlite3Fts5UnicodeIsalnum(int c){
183114  /* Each unsigned integer in the following array corresponds to a contiguous
183115  ** range of unicode codepoints that are not either letters or numbers (i.e.
183116  ** codepoints for which this function should return 0).
183117  **
183118  ** The most significant 22 bits in each 32-bit value contain the first
183119  ** codepoint in the range. The least significant 10 bits are used to store
183120  ** the size of the range (always at least 1). In other words, the value
183121  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
183122  ** C. It is not possible to represent a range larger than 1023 codepoints
183123  ** using this format.
183124  */
183125  static const unsigned int aEntry[] = {
183126    0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
183127    0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
183128    0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
183129    0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
183130    0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
183131    0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
183132    0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
183133    0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
183134    0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
183135    0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
183136    0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
183137    0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
183138    0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
183139    0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
183140    0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
183141    0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
183142    0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
183143    0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
183144    0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
183145    0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
183146    0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
183147    0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
183148    0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
183149    0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
183150    0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
183151    0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
183152    0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
183153    0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
183154    0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
183155    0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
183156    0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
183157    0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
183158    0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
183159    0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
183160    0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
183161    0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
183162    0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
183163    0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
183164    0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
183165    0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
183166    0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
183167    0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
183168    0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
183169    0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
183170    0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
183171    0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
183172    0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
183173    0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
183174    0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
183175    0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
183176    0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
183177    0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
183178    0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
183179    0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
183180    0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
183181    0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
183182    0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
183183    0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
183184    0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
183185    0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
183186    0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
183187    0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
183188    0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
183189    0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
183190    0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
183191    0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
183192    0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
183193    0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
183194    0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
183195    0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
183196    0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
183197    0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
183198    0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
183199    0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
183200    0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
183201    0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
183202    0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
183203    0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
183204    0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
183205    0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
183206    0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
183207    0x380400F0,
183208  };
183209  static const unsigned int aAscii[4] = {
183210    0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
183211  };
183212
183213  if( c<128 ){
183214    return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
183215  }else if( c<(1<<22) ){
183216    unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
183217    int iRes = 0;
183218    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
183219    int iLo = 0;
183220    while( iHi>=iLo ){
183221      int iTest = (iHi + iLo) / 2;
183222      if( key >= aEntry[iTest] ){
183223        iRes = iTest;
183224        iLo = iTest+1;
183225      }else{
183226        iHi = iTest-1;
183227      }
183228    }
183229    assert( aEntry[0]<key );
183230    assert( key>=aEntry[iRes] );
183231    return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
183232  }
183233  return 1;
183234}
183235
183236
183237/*
183238** If the argument is a codepoint corresponding to a lowercase letter
183239** in the ASCII range with a diacritic added, return the codepoint
183240** of the ASCII letter only. For example, if passed 235 - "LATIN
183241** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
183242** E"). The resuls of passing a codepoint that corresponds to an
183243** uppercase letter are undefined.
183244*/
183245static int fts5_remove_diacritic(int c){
183246  unsigned short aDia[] = {
183247        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
183248     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
183249     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
183250     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
183251     3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
183252     3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
183253     4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
183254     6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
183255    61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
183256    61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
183257    62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
183258    62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
183259    62924, 63050, 63082, 63274, 63390,
183260  };
183261  char aChar[] = {
183262    '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
183263    'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
183264    's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
183265    'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
183266    'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
183267    '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
183268    'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
183269    'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
183270    'e',  'i',  'o',  'u',  'y',
183271  };
183272
183273  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
183274  int iRes = 0;
183275  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
183276  int iLo = 0;
183277  while( iHi>=iLo ){
183278    int iTest = (iHi + iLo) / 2;
183279    if( key >= aDia[iTest] ){
183280      iRes = iTest;
183281      iLo = iTest+1;
183282    }else{
183283      iHi = iTest-1;
183284    }
183285  }
183286  assert( key>=aDia[iRes] );
183287  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
183288}
183289
183290
183291/*
183292** Return true if the argument interpreted as a unicode codepoint
183293** is a diacritical modifier character.
183294*/
183295static int sqlite3Fts5UnicodeIsdiacritic(int c){
183296  unsigned int mask0 = 0x08029FDF;
183297  unsigned int mask1 = 0x000361F8;
183298  if( c<768 || c>817 ) return 0;
183299  return (c < 768+32) ?
183300      (mask0 & (1 << (c-768))) :
183301      (mask1 & (1 << (c-768-32)));
183302}
183303
183304
183305/*
183306** Interpret the argument as a unicode codepoint. If the codepoint
183307** is an upper case character that has a lower case equivalent,
183308** return the codepoint corresponding to the lower case version.
183309** Otherwise, return a copy of the argument.
183310**
183311** The results are undefined if the value passed to this function
183312** is less than zero.
183313*/
183314static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
183315  /* Each entry in the following array defines a rule for folding a range
183316  ** of codepoints to lower case. The rule applies to a range of nRange
183317  ** codepoints starting at codepoint iCode.
183318  **
183319  ** If the least significant bit in flags is clear, then the rule applies
183320  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
183321  ** need to be folded). Or, if it is set, then the rule only applies to
183322  ** every second codepoint in the range, starting with codepoint C.
183323  **
183324  ** The 7 most significant bits in flags are an index into the aiOff[]
183325  ** array. If a specific codepoint C does require folding, then its lower
183326  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
183327  **
183328  ** The contents of this array are generated by parsing the CaseFolding.txt
183329  ** file distributed as part of the "Unicode Character Database". See
183330  ** http://www.unicode.org for details.
183331  */
183332  static const struct TableEntry {
183333    unsigned short iCode;
183334    unsigned char flags;
183335    unsigned char nRange;
183336  } aEntry[] = {
183337    {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
183338    {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
183339    {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
183340    {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
183341    {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
183342    {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
183343    {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
183344    {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
183345    {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
183346    {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
183347    {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
183348    {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
183349    {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
183350    {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
183351    {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
183352    {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
183353    {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
183354    {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
183355    {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
183356    {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
183357    {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
183358    {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
183359    {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
183360    {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
183361    {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
183362    {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
183363    {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
183364    {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
183365    {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
183366    {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
183367    {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
183368    {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
183369    {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
183370    {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
183371    {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
183372    {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
183373    {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
183374    {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
183375    {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
183376    {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
183377    {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
183378    {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
183379    {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
183380    {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
183381    {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
183382    {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
183383    {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
183384    {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
183385    {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
183386    {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
183387    {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
183388    {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
183389    {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
183390    {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
183391    {65313, 14, 26},
183392  };
183393  static const unsigned short aiOff[] = {
183394   1,     2,     8,     15,    16,    26,    28,    32,
183395   37,    38,    40,    48,    63,    64,    69,    71,
183396   79,    80,    116,   202,   203,   205,   206,   207,
183397   209,   210,   211,   213,   214,   217,   218,   219,
183398   775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
183399   54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
183400   57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
183401   65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
183402   65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
183403   65514, 65521, 65527, 65528, 65529,
183404  };
183405
183406  int ret = c;
183407
183408  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
183409
183410  if( c<128 ){
183411    if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
183412  }else if( c<65536 ){
183413    const struct TableEntry *p;
183414    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
183415    int iLo = 0;
183416    int iRes = -1;
183417
183418    assert( c>aEntry[0].iCode );
183419    while( iHi>=iLo ){
183420      int iTest = (iHi + iLo) / 2;
183421      int cmp = (c - aEntry[iTest].iCode);
183422      if( cmp>=0 ){
183423        iRes = iTest;
183424        iLo = iTest+1;
183425      }else{
183426        iHi = iTest-1;
183427      }
183428    }
183429
183430    assert( iRes>=0 && c>=aEntry[iRes].iCode );
183431    p = &aEntry[iRes];
183432    if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
183433      ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
183434      assert( ret>0 );
183435    }
183436
183437    if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
183438  }
183439
183440  else if( c>=66560 && c<66600 ){
183441    ret = c + 40;
183442  }
183443
183444  return ret;
183445}
183446
183447/*
183448** 2015 May 30
183449**
183450** The author disclaims copyright to this source code.  In place of
183451** a legal notice, here is a blessing:
183452**
183453**    May you do good and not evil.
183454**    May you find forgiveness for yourself and forgive others.
183455**    May you share freely, never taking more than you give.
183456**
183457******************************************************************************
183458**
183459** Routines for varint serialization and deserialization.
183460*/
183461
183462
183463
183464/*
183465** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
183466** Except, this version does handle the single byte case that the core
183467** version depends on being handled before its function is called.
183468*/
183469static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
183470  u32 a,b;
183471
183472  /* The 1-byte case. Overwhelmingly the most common. */
183473  a = *p;
183474  /* a: p0 (unmasked) */
183475  if (!(a&0x80))
183476  {
183477    /* Values between 0 and 127 */
183478    *v = a;
183479    return 1;
183480  }
183481
183482  /* The 2-byte case */
183483  p++;
183484  b = *p;
183485  /* b: p1 (unmasked) */
183486  if (!(b&0x80))
183487  {
183488    /* Values between 128 and 16383 */
183489    a &= 0x7f;
183490    a = a<<7;
183491    *v = a | b;
183492    return 2;
183493  }
183494
183495  /* The 3-byte case */
183496  p++;
183497  a = a<<14;
183498  a |= *p;
183499  /* a: p0<<14 | p2 (unmasked) */
183500  if (!(a&0x80))
183501  {
183502    /* Values between 16384 and 2097151 */
183503    a &= (0x7f<<14)|(0x7f);
183504    b &= 0x7f;
183505    b = b<<7;
183506    *v = a | b;
183507    return 3;
183508  }
183509
183510  /* A 32-bit varint is used to store size information in btrees.
183511  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
183512  ** A 3-byte varint is sufficient, for example, to record the size
183513  ** of a 1048569-byte BLOB or string.
183514  **
183515  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
183516  ** rare larger cases can be handled by the slower 64-bit varint
183517  ** routine.
183518  */
183519  {
183520    u64 v64;
183521    u8 n;
183522    p -= 2;
183523    n = sqlite3Fts5GetVarint(p, &v64);
183524    *v = (u32)v64;
183525    assert( n>3 && n<=9 );
183526    return n;
183527  }
183528}
183529
183530
183531/*
183532** Bitmasks used by sqlite3GetVarint().  These precomputed constants
183533** are defined here rather than simply putting the constant expressions
183534** inline in order to work around bugs in the RVT compiler.
183535**
183536** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
183537**
183538** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
183539*/
183540#define SLOT_2_0     0x001fc07f
183541#define SLOT_4_2_0   0xf01fc07f
183542
183543/*
183544** Read a 64-bit variable-length integer from memory starting at p[0].
183545** Return the number of bytes read.  The value is stored in *v.
183546*/
183547static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
183548  u32 a,b,s;
183549
183550  a = *p;
183551  /* a: p0 (unmasked) */
183552  if (!(a&0x80))
183553  {
183554    *v = a;
183555    return 1;
183556  }
183557
183558  p++;
183559  b = *p;
183560  /* b: p1 (unmasked) */
183561  if (!(b&0x80))
183562  {
183563    a &= 0x7f;
183564    a = a<<7;
183565    a |= b;
183566    *v = a;
183567    return 2;
183568  }
183569
183570  /* Verify that constants are precomputed correctly */
183571  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
183572  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
183573
183574  p++;
183575  a = a<<14;
183576  a |= *p;
183577  /* a: p0<<14 | p2 (unmasked) */
183578  if (!(a&0x80))
183579  {
183580    a &= SLOT_2_0;
183581    b &= 0x7f;
183582    b = b<<7;
183583    a |= b;
183584    *v = a;
183585    return 3;
183586  }
183587
183588  /* CSE1 from below */
183589  a &= SLOT_2_0;
183590  p++;
183591  b = b<<14;
183592  b |= *p;
183593  /* b: p1<<14 | p3 (unmasked) */
183594  if (!(b&0x80))
183595  {
183596    b &= SLOT_2_0;
183597    /* moved CSE1 up */
183598    /* a &= (0x7f<<14)|(0x7f); */
183599    a = a<<7;
183600    a |= b;
183601    *v = a;
183602    return 4;
183603  }
183604
183605  /* a: p0<<14 | p2 (masked) */
183606  /* b: p1<<14 | p3 (unmasked) */
183607  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
183608  /* moved CSE1 up */
183609  /* a &= (0x7f<<14)|(0x7f); */
183610  b &= SLOT_2_0;
183611  s = a;
183612  /* s: p0<<14 | p2 (masked) */
183613
183614  p++;
183615  a = a<<14;
183616  a |= *p;
183617  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
183618  if (!(a&0x80))
183619  {
183620    /* we can skip these cause they were (effectively) done above in calc'ing s */
183621    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
183622    /* b &= (0x7f<<14)|(0x7f); */
183623    b = b<<7;
183624    a |= b;
183625    s = s>>18;
183626    *v = ((u64)s)<<32 | a;
183627    return 5;
183628  }
183629
183630  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
183631  s = s<<7;
183632  s |= b;
183633  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
183634
183635  p++;
183636  b = b<<14;
183637  b |= *p;
183638  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
183639  if (!(b&0x80))
183640  {
183641    /* we can skip this cause it was (effectively) done above in calc'ing s */
183642    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
183643    a &= SLOT_2_0;
183644    a = a<<7;
183645    a |= b;
183646    s = s>>18;
183647    *v = ((u64)s)<<32 | a;
183648    return 6;
183649  }
183650
183651  p++;
183652  a = a<<14;
183653  a |= *p;
183654  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
183655  if (!(a&0x80))
183656  {
183657    a &= SLOT_4_2_0;
183658    b &= SLOT_2_0;
183659    b = b<<7;
183660    a |= b;
183661    s = s>>11;
183662    *v = ((u64)s)<<32 | a;
183663    return 7;
183664  }
183665
183666  /* CSE2 from below */
183667  a &= SLOT_2_0;
183668  p++;
183669  b = b<<14;
183670  b |= *p;
183671  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
183672  if (!(b&0x80))
183673  {
183674    b &= SLOT_4_2_0;
183675    /* moved CSE2 up */
183676    /* a &= (0x7f<<14)|(0x7f); */
183677    a = a<<7;
183678    a |= b;
183679    s = s>>4;
183680    *v = ((u64)s)<<32 | a;
183681    return 8;
183682  }
183683
183684  p++;
183685  a = a<<15;
183686  a |= *p;
183687  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
183688
183689  /* moved CSE2 up */
183690  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
183691  b &= SLOT_2_0;
183692  b = b<<8;
183693  a |= b;
183694
183695  s = s<<4;
183696  b = p[-4];
183697  b &= 0x7f;
183698  b = b>>3;
183699  s |= b;
183700
183701  *v = ((u64)s)<<32 | a;
183702
183703  return 9;
183704}
183705
183706/*
183707** The variable-length integer encoding is as follows:
183708**
183709** KEY:
183710**         A = 0xxxxxxx    7 bits of data and one flag bit
183711**         B = 1xxxxxxx    7 bits of data and one flag bit
183712**         C = xxxxxxxx    8 bits of data
183713**
183714**  7 bits - A
183715** 14 bits - BA
183716** 21 bits - BBA
183717** 28 bits - BBBA
183718** 35 bits - BBBBA
183719** 42 bits - BBBBBA
183720** 49 bits - BBBBBBA
183721** 56 bits - BBBBBBBA
183722** 64 bits - BBBBBBBBC
183723*/
183724
183725#ifdef SQLITE_NOINLINE
183726# define FTS5_NOINLINE SQLITE_NOINLINE
183727#else
183728# define FTS5_NOINLINE
183729#endif
183730
183731/*
183732** Write a 64-bit variable-length integer to memory starting at p[0].
183733** The length of data write will be between 1 and 9 bytes.  The number
183734** of bytes written is returned.
183735**
183736** A variable-length integer consists of the lower 7 bits of each byte
183737** for all bytes that have the 8th bit set and one byte with the 8th
183738** bit clear.  Except, if we get to the 9th byte, it stores the full
183739** 8 bits and is the last byte.
183740*/
183741static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
183742  int i, j, n;
183743  u8 buf[10];
183744  if( v & (((u64)0xff000000)<<32) ){
183745    p[8] = (u8)v;
183746    v >>= 8;
183747    for(i=7; i>=0; i--){
183748      p[i] = (u8)((v & 0x7f) | 0x80);
183749      v >>= 7;
183750    }
183751    return 9;
183752  }
183753  n = 0;
183754  do{
183755    buf[n++] = (u8)((v & 0x7f) | 0x80);
183756    v >>= 7;
183757  }while( v!=0 );
183758  buf[0] &= 0x7f;
183759  assert( n<=9 );
183760  for(i=0, j=n-1; j>=0; j--, i++){
183761    p[i] = buf[j];
183762  }
183763  return n;
183764}
183765
183766static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
183767  if( v<=0x7f ){
183768    p[0] = v&0x7f;
183769    return 1;
183770  }
183771  if( v<=0x3fff ){
183772    p[0] = ((v>>7)&0x7f)|0x80;
183773    p[1] = v&0x7f;
183774    return 2;
183775  }
183776  return fts5PutVarint64(p,v);
183777}
183778
183779
183780static int sqlite3Fts5GetVarintLen(u32 iVal){
183781  if( iVal<(1 << 7 ) ) return 1;
183782  if( iVal<(1 << 14) ) return 2;
183783  if( iVal<(1 << 21) ) return 3;
183784  if( iVal<(1 << 28) ) return 4;
183785  return 5;
183786}
183787
183788
183789/*
183790** 2015 May 08
183791**
183792** The author disclaims copyright to this source code.  In place of
183793** a legal notice, here is a blessing:
183794**
183795**    May you do good and not evil.
183796**    May you find forgiveness for yourself and forgive others.
183797**    May you share freely, never taking more than you give.
183798**
183799******************************************************************************
183800**
183801** This is an SQLite virtual table module implementing direct access to an
183802** existing FTS5 index. The module may create several different types of
183803** tables:
183804**
183805** col:
183806**     CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
183807**
183808**   One row for each term/column combination. The value of $doc is set to
183809**   the number of fts5 rows that contain at least one instance of term
183810**   $term within column $col. Field $cnt is set to the total number of
183811**   instances of term $term in column $col (in any row of the fts5 table).
183812**
183813** row:
183814**     CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
183815**
183816**   One row for each term in the database. The value of $doc is set to
183817**   the number of fts5 rows that contain at least one instance of term
183818**   $term. Field $cnt is set to the total number of instances of term
183819**   $term in the database.
183820*/
183821
183822
183823
183824
183825typedef struct Fts5VocabTable Fts5VocabTable;
183826typedef struct Fts5VocabCursor Fts5VocabCursor;
183827
183828struct Fts5VocabTable {
183829  sqlite3_vtab base;
183830  char *zFts5Tbl;                 /* Name of fts5 table */
183831  char *zFts5Db;                  /* Db containing fts5 table */
183832  sqlite3 *db;                    /* Database handle */
183833  Fts5Global *pGlobal;            /* FTS5 global object for this database */
183834  int eType;                      /* FTS5_VOCAB_COL or ROW */
183835};
183836
183837struct Fts5VocabCursor {
183838  sqlite3_vtab_cursor base;
183839  sqlite3_stmt *pStmt;            /* Statement holding lock on pIndex */
183840  Fts5Index *pIndex;              /* Associated FTS5 index */
183841
183842  int bEof;                       /* True if this cursor is at EOF */
183843  Fts5IndexIter *pIter;           /* Term/rowid iterator object */
183844
183845  /* These are used by 'col' tables only */
183846  int nCol;
183847  int iCol;
183848  i64 *aCnt;
183849  i64 *aDoc;
183850
183851  /* Output values */
183852  i64 rowid;                      /* This table's current rowid value */
183853  Fts5Buffer term;                /* Current value of 'term' column */
183854  i64 aVal[3];                    /* Up to three columns left of 'term' */
183855};
183856
183857#define FTS5_VOCAB_COL    0
183858#define FTS5_VOCAB_ROW    1
183859
183860#define FTS5_VOCAB_COL_SCHEMA  "term, col, doc, cnt"
183861#define FTS5_VOCAB_ROW_SCHEMA  "term, doc, cnt"
183862
183863/*
183864** Translate a string containing an fts5vocab table type to an
183865** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
183866** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
183867** and return SQLITE_ERROR.
183868*/
183869static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
183870  int rc = SQLITE_OK;
183871  char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
183872  if( rc==SQLITE_OK ){
183873    sqlite3Fts5Dequote(zCopy);
183874    if( sqlite3_stricmp(zCopy, "col")==0 ){
183875      *peType = FTS5_VOCAB_COL;
183876    }else
183877
183878    if( sqlite3_stricmp(zCopy, "row")==0 ){
183879      *peType = FTS5_VOCAB_ROW;
183880    }else
183881    {
183882      *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
183883      rc = SQLITE_ERROR;
183884    }
183885    sqlite3_free(zCopy);
183886  }
183887
183888  return rc;
183889}
183890
183891
183892/*
183893** The xDisconnect() virtual table method.
183894*/
183895static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
183896  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
183897  sqlite3_free(pTab);
183898  return SQLITE_OK;
183899}
183900
183901/*
183902** The xDestroy() virtual table method.
183903*/
183904static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
183905  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
183906  sqlite3_free(pTab);
183907  return SQLITE_OK;
183908}
183909
183910/*
183911** This function is the implementation of both the xConnect and xCreate
183912** methods of the FTS3 virtual table.
183913**
183914** The argv[] array contains the following:
183915**
183916**   argv[0]   -> module name  ("fts5vocab")
183917**   argv[1]   -> database name
183918**   argv[2]   -> table name
183919**
183920** then:
183921**
183922**   argv[3]   -> name of fts5 table
183923**   argv[4]   -> type of fts5vocab table
183924**
183925** or, for tables in the TEMP schema only.
183926**
183927**   argv[3]   -> name of fts5 tables database
183928**   argv[4]   -> name of fts5 table
183929**   argv[5]   -> type of fts5vocab table
183930*/
183931static int fts5VocabInitVtab(
183932  sqlite3 *db,                    /* The SQLite database connection */
183933  void *pAux,                     /* Pointer to Fts5Global object */
183934  int argc,                       /* Number of elements in argv array */
183935  const char * const *argv,       /* xCreate/xConnect argument array */
183936  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
183937  char **pzErr                    /* Write any error message here */
183938){
183939  const char *azSchema[] = {
183940    "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA  ")",
183941    "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA  ")"
183942  };
183943
183944  Fts5VocabTable *pRet = 0;
183945  int rc = SQLITE_OK;             /* Return code */
183946  int bDb;
183947
183948  bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
183949
183950  if( argc!=5 && bDb==0 ){
183951    *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
183952    rc = SQLITE_ERROR;
183953  }else{
183954    int nByte;                      /* Bytes of space to allocate */
183955    const char *zDb = bDb ? argv[3] : argv[1];
183956    const char *zTab = bDb ? argv[4] : argv[3];
183957    const char *zType = bDb ? argv[5] : argv[4];
183958    int nDb = strlen(zDb)+1;
183959    int nTab = strlen(zTab)+1;
183960    int eType;
183961
183962    rc = fts5VocabTableType(zType, pzErr, &eType);
183963    if( rc==SQLITE_OK ){
183964      assert( eType>=0 && eType<sizeof(azSchema)/sizeof(azSchema[0]) );
183965      rc = sqlite3_declare_vtab(db, azSchema[eType]);
183966    }
183967
183968    nByte = sizeof(Fts5VocabTable) + nDb + nTab;
183969    pRet = sqlite3Fts5MallocZero(&rc, nByte);
183970    if( pRet ){
183971      pRet->pGlobal = (Fts5Global*)pAux;
183972      pRet->eType = eType;
183973      pRet->db = db;
183974      pRet->zFts5Tbl = (char*)&pRet[1];
183975      pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
183976      memcpy(pRet->zFts5Tbl, zTab, nTab);
183977      memcpy(pRet->zFts5Db, zDb, nDb);
183978      sqlite3Fts5Dequote(pRet->zFts5Tbl);
183979      sqlite3Fts5Dequote(pRet->zFts5Db);
183980    }
183981  }
183982
183983  *ppVTab = (sqlite3_vtab*)pRet;
183984  return rc;
183985}
183986
183987
183988/*
183989** The xConnect() and xCreate() methods for the virtual table. All the
183990** work is done in function fts5VocabInitVtab().
183991*/
183992static int fts5VocabConnectMethod(
183993  sqlite3 *db,                    /* Database connection */
183994  void *pAux,                     /* Pointer to tokenizer hash table */
183995  int argc,                       /* Number of elements in argv array */
183996  const char * const *argv,       /* xCreate/xConnect argument array */
183997  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
183998  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
183999){
184000  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
184001}
184002static int fts5VocabCreateMethod(
184003  sqlite3 *db,                    /* Database connection */
184004  void *pAux,                     /* Pointer to tokenizer hash table */
184005  int argc,                       /* Number of elements in argv array */
184006  const char * const *argv,       /* xCreate/xConnect argument array */
184007  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
184008  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
184009){
184010  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
184011}
184012
184013/*
184014** Implementation of the xBestIndex method.
184015*/
184016static int fts5VocabBestIndexMethod(
184017  sqlite3_vtab *pVTab,
184018  sqlite3_index_info *pInfo
184019){
184020  return SQLITE_OK;
184021}
184022
184023/*
184024** Implementation of xOpen method.
184025*/
184026static int fts5VocabOpenMethod(
184027  sqlite3_vtab *pVTab,
184028  sqlite3_vtab_cursor **ppCsr
184029){
184030  Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
184031  Fts5Index *pIndex = 0;
184032  int nCol = 0;
184033  Fts5VocabCursor *pCsr = 0;
184034  int rc = SQLITE_OK;
184035  sqlite3_stmt *pStmt = 0;
184036  char *zSql = 0;
184037  int nByte;
184038
184039  zSql = sqlite3Fts5Mprintf(&rc,
184040      "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
184041      pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
184042  );
184043  if( zSql ){
184044    rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
184045  }
184046  sqlite3_free(zSql);
184047  assert( rc==SQLITE_OK || pStmt==0 );
184048  if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
184049
184050  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
184051    i64 iId = sqlite3_column_int64(pStmt, 0);
184052    pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &nCol);
184053  }
184054
184055  if( rc==SQLITE_OK && pIndex==0 ){
184056    rc = sqlite3_finalize(pStmt);
184057    pStmt = 0;
184058    if( rc==SQLITE_OK ){
184059      pVTab->zErrMsg = sqlite3_mprintf(
184060          "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
184061      );
184062      rc = SQLITE_ERROR;
184063    }
184064  }
184065
184066  nByte = nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
184067  pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
184068  if( pCsr ){
184069    pCsr->pIndex = pIndex;
184070    pCsr->pStmt = pStmt;
184071    pCsr->nCol = nCol;
184072    pCsr->aCnt = (i64*)&pCsr[1];
184073    pCsr->aDoc = &pCsr->aCnt[nCol];
184074  }else{
184075    sqlite3_finalize(pStmt);
184076  }
184077
184078  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
184079  return rc;
184080}
184081
184082static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
184083  pCsr->rowid = 0;
184084  sqlite3Fts5IterClose(pCsr->pIter);
184085  pCsr->pIter = 0;
184086}
184087
184088/*
184089** Close the cursor.  For additional information see the documentation
184090** on the xClose method of the virtual table interface.
184091*/
184092static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
184093  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
184094  fts5VocabResetCursor(pCsr);
184095  sqlite3Fts5BufferFree(&pCsr->term);
184096  sqlite3_finalize(pCsr->pStmt);
184097  sqlite3_free(pCsr);
184098  return SQLITE_OK;
184099}
184100
184101
184102/*
184103** Advance the cursor to the next row in the table.
184104*/
184105static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
184106  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
184107  Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
184108  int rc = SQLITE_OK;
184109
184110  pCsr->rowid++;
184111
184112  if( pTab->eType==FTS5_VOCAB_COL ){
184113    for(pCsr->iCol++; pCsr->iCol<pCsr->nCol; pCsr->iCol++){
184114      if( pCsr->aCnt[pCsr->iCol] ) break;
184115    }
184116  }
184117
184118  if( pTab->eType==FTS5_VOCAB_ROW || pCsr->iCol>=pCsr->nCol ){
184119    if( sqlite3Fts5IterEof(pCsr->pIter) ){
184120      pCsr->bEof = 1;
184121    }else{
184122      const char *zTerm;
184123      int nTerm;
184124
184125      zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
184126      sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
184127      memset(pCsr->aVal, 0, sizeof(pCsr->aVal));
184128      memset(pCsr->aCnt, 0, pCsr->nCol * sizeof(i64));
184129      memset(pCsr->aDoc, 0, pCsr->nCol * sizeof(i64));
184130      pCsr->iCol = 0;
184131
184132      assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
184133      while( rc==SQLITE_OK ){
184134        i64 dummy;
184135        const u8 *pPos; int nPos;   /* Position list */
184136        i64 iPos = 0;               /* 64-bit position read from poslist */
184137        int iOff = 0;               /* Current offset within position list */
184138
184139        rc = sqlite3Fts5IterPoslist(pCsr->pIter, 0, &pPos, &nPos, &dummy);
184140        if( rc==SQLITE_OK ){
184141          if( pTab->eType==FTS5_VOCAB_ROW ){
184142            while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
184143              pCsr->aVal[1]++;
184144            }
184145            pCsr->aVal[0]++;
184146          }else{
184147            int iCol = -1;
184148            while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
184149              int ii = FTS5_POS2COLUMN(iPos);
184150              pCsr->aCnt[ii]++;
184151              if( iCol!=ii ){
184152                pCsr->aDoc[ii]++;
184153                iCol = ii;
184154              }
184155            }
184156          }
184157          rc = sqlite3Fts5IterNextScan(pCsr->pIter);
184158        }
184159        if( rc==SQLITE_OK ){
184160          zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
184161          if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ) break;
184162          if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
184163        }
184164      }
184165    }
184166  }
184167
184168  if( pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
184169    while( pCsr->aCnt[pCsr->iCol]==0 ) pCsr->iCol++;
184170    pCsr->aVal[0] = pCsr->iCol;
184171    pCsr->aVal[1] = pCsr->aDoc[pCsr->iCol];
184172    pCsr->aVal[2] = pCsr->aCnt[pCsr->iCol];
184173  }
184174  return rc;
184175}
184176
184177/*
184178** This is the xFilter implementation for the virtual table.
184179*/
184180static int fts5VocabFilterMethod(
184181  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
184182  int idxNum,                     /* Strategy index */
184183  const char *idxStr,             /* Unused */
184184  int nVal,                       /* Number of elements in apVal */
184185  sqlite3_value **apVal           /* Arguments for the indexing scheme */
184186){
184187  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
184188  int rc;
184189  const int flags = FTS5INDEX_QUERY_SCAN;
184190
184191  fts5VocabResetCursor(pCsr);
184192  rc = sqlite3Fts5IndexQuery(pCsr->pIndex, 0, 0, flags, 0, &pCsr->pIter);
184193  if( rc==SQLITE_OK ){
184194    rc = fts5VocabNextMethod(pCursor);
184195  }
184196
184197  return rc;
184198}
184199
184200/*
184201** This is the xEof method of the virtual table. SQLite calls this
184202** routine to find out if it has reached the end of a result set.
184203*/
184204static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
184205  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
184206  return pCsr->bEof;
184207}
184208
184209static int fts5VocabColumnMethod(
184210  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
184211  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
184212  int iCol                        /* Index of column to read value from */
184213){
184214  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
184215  switch( iCol ){
184216    case 0: /* term */
184217      sqlite3_result_text(
184218          pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
184219      );
184220      break;
184221
184222    default:
184223      assert( iCol<4 && iCol>0 );
184224      sqlite3_result_int64(pCtx, pCsr->aVal[iCol-1]);
184225      break;
184226  }
184227  return SQLITE_OK;
184228}
184229
184230/*
184231** This is the xRowid method. The SQLite core calls this routine to
184232** retrieve the rowid for the current row of the result set. The
184233** rowid should be written to *pRowid.
184234*/
184235static int fts5VocabRowidMethod(
184236  sqlite3_vtab_cursor *pCursor,
184237  sqlite_int64 *pRowid
184238){
184239  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
184240  *pRowid = pCsr->rowid;
184241  return SQLITE_OK;
184242}
184243
184244static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
184245  static const sqlite3_module fts5Vocab = {
184246    /* iVersion      */ 2,
184247    /* xCreate       */ fts5VocabCreateMethod,
184248    /* xConnect      */ fts5VocabConnectMethod,
184249    /* xBestIndex    */ fts5VocabBestIndexMethod,
184250    /* xDisconnect   */ fts5VocabDisconnectMethod,
184251    /* xDestroy      */ fts5VocabDestroyMethod,
184252    /* xOpen         */ fts5VocabOpenMethod,
184253    /* xClose        */ fts5VocabCloseMethod,
184254    /* xFilter       */ fts5VocabFilterMethod,
184255    /* xNext         */ fts5VocabNextMethod,
184256    /* xEof          */ fts5VocabEofMethod,
184257    /* xColumn       */ fts5VocabColumnMethod,
184258    /* xRowid        */ fts5VocabRowidMethod,
184259    /* xUpdate       */ 0,
184260    /* xBegin        */ 0,
184261    /* xSync         */ 0,
184262    /* xCommit       */ 0,
184263    /* xRollback     */ 0,
184264    /* xFindFunction */ 0,
184265    /* xRename       */ 0,
184266    /* xSavepoint    */ 0,
184267    /* xRelease      */ 0,
184268    /* xRollbackTo   */ 0,
184269  };
184270  void *p = (void*)pGlobal;
184271
184272  return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
184273}
184274
184275
184276
184277
184278
184279#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
184280
184281/************** End of fts5.c ************************************************/
184282